Adapt key-manager to work with OpenSSL 1.1 preserving 1.0 compatibility
[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 #if __GNUC__ >= 6
51 #pragma GCC diagnostic ignored "-Wunused-const-variable"
52 #endif
53
54 #define SQLCIPHER_CORE 1
55 #define SQLCIPHER_AMALGAMATION 1
56 #ifndef SQLCIPHER_PRIVATE
57 # define SQLCIPHER_PRIVATE static
58 #endif
59 #ifndef SQLCIPHER_API
60 # define SQLCIPHER_API
61 #endif
62 /************** Begin file sqlcipherInt.h ***************************************/
63 /*
64 ** 2001 September 15
65 **
66 ** The author disclaims copyright to this source code.  In place of
67 ** a legal notice, here is a blessing:
68 **
69 **    May you do good and not evil.
70 **    May you find forgiveness for yourself and forgive others.
71 **    May you share freely, never taking more than you give.
72 **
73 *************************************************************************
74 ** Internal interface definitions for SQLite.
75 **
76 */
77 #ifndef _SQLCIPHERINT_H_
78 #define _SQLCIPHERINT_H_
79
80 /*
81 ** These #defines should enable >2GB file support on POSIX if the
82 ** underlying operating system supports it.  If the OS lacks
83 ** large file support, or if the OS is windows, these should be no-ops.
84 **
85 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
86 ** system #includes.  Hence, this block of code must be the very first
87 ** code in all source files.
88 **
89 ** Large file support can be disabled using the -DSQLCIPHER_DISABLE_LFS switch
90 ** on the compiler command line.  This is necessary if you are compiling
91 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
92 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
93 ** without this option, LFS is enable.  But LFS does not exist in the kernel
94 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
95 ** portability you should omit LFS.
96 **
97 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
98 */
99 #ifndef SQLCIPHER_DISABLE_LFS
100 # define _LARGE_FILE       1
101 # ifndef _FILE_OFFSET_BITS
102 #   define _FILE_OFFSET_BITS 64
103 # endif
104 # define _LARGEFILE_SOURCE 1
105 #endif
106
107 /*
108 ** Include the configuration header output by 'configure' if we're using the
109 ** autoconf-based build
110 */
111 #ifdef _HAVE_SQLCIPHER_CONFIG_H
112 #include "config.h"
113 #endif
114
115 /************** Include sqlcipherLimit.h in the middle of sqlcipherInt.h ***********/
116 /************** Begin file sqlcipherLimit.h *************************************/
117 /*
118 ** 2007 May 7
119 **
120 ** The author disclaims copyright to this source code.  In place of
121 ** a legal notice, here is a blessing:
122 **
123 **    May you do good and not evil.
124 **    May you find forgiveness for yourself and forgive others.
125 **    May you share freely, never taking more than you give.
126 **
127 *************************************************************************
128 ** 
129 ** This file defines various limits of what SQLite can process.
130 */
131
132 /*
133 ** The maximum length of a TEXT or BLOB in bytes.   This also
134 ** limits the size of a row in a table or index.
135 **
136 ** The hard limit is the ability of a 32-bit signed integer
137 ** to count the size: 2^31-1 or 2147483647.
138 */
139 #ifndef SQLCIPHER_MAX_LENGTH
140 # define SQLCIPHER_MAX_LENGTH 1000000000
141 #endif
142
143 /*
144 ** This is the maximum number of
145 **
146 **    * Columns in a table
147 **    * Columns in an index
148 **    * Columns in a view
149 **    * Terms in the SET clause of an UPDATE statement
150 **    * Terms in the result set of a SELECT statement
151 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
152 **    * Terms in the VALUES clause of an INSERT statement
153 **
154 ** The hard upper limit here is 32676.  Most database people will
155 ** tell you that in a well-normalized database, you usually should
156 ** not have more than a dozen or so columns in any table.  And if
157 ** that is the case, there is no point in having more than a few
158 ** dozen values in any of the other situations described above.
159 */
160 #ifndef SQLCIPHER_MAX_COLUMN
161 # define SQLCIPHER_MAX_COLUMN 2000
162 #endif
163
164 /*
165 ** The maximum length of a single SQL statement in bytes.
166 **
167 ** It used to be the case that setting this value to zero would
168 ** turn the limit off.  That is no longer true.  It is not possible
169 ** to turn this limit off.
170 */
171 #ifndef SQLCIPHER_MAX_SQL_LENGTH
172 # define SQLCIPHER_MAX_SQL_LENGTH 1000000000
173 #endif
174
175 /*
176 ** The maximum depth of an expression tree. This is limited to 
177 ** some extent by SQLCIPHER_MAX_SQL_LENGTH. But sometime you might 
178 ** want to place more severe limits on the complexity of an 
179 ** expression.
180 **
181 ** A value of 0 used to mean that the limit was not enforced.
182 ** But that is no longer true.  The limit is now strictly enforced
183 ** at all times.
184 */
185 #ifndef SQLCIPHER_MAX_EXPR_DEPTH
186 # define SQLCIPHER_MAX_EXPR_DEPTH 1000
187 #endif
188
189 /*
190 ** The maximum number of terms in a compound SELECT statement.
191 ** The code generator for compound SELECT statements does one
192 ** level of recursion for each term.  A stack overflow can result
193 ** if the number of terms is too large.  In practice, most SQL
194 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
195 ** any limit on the number of terms in a compount SELECT.
196 */
197 #ifndef SQLCIPHER_MAX_COMPOUND_SELECT
198 # define SQLCIPHER_MAX_COMPOUND_SELECT 500
199 #endif
200
201 /*
202 ** The maximum number of opcodes in a VDBE program.
203 ** Not currently enforced.
204 */
205 #ifndef SQLCIPHER_MAX_VDBE_OP
206 # define SQLCIPHER_MAX_VDBE_OP 25000
207 #endif
208
209 /*
210 ** The maximum number of arguments to an SQL function.
211 */
212 #ifndef SQLCIPHER_MAX_FUNCTION_ARG
213 # define SQLCIPHER_MAX_FUNCTION_ARG 127
214 #endif
215
216 /*
217 ** The maximum number of in-memory pages to use for the main database
218 ** table and for temporary tables.  The SQLCIPHER_DEFAULT_CACHE_SIZE
219 */
220 #ifndef SQLCIPHER_DEFAULT_CACHE_SIZE
221 # define SQLCIPHER_DEFAULT_CACHE_SIZE  2000
222 #endif
223 #ifndef SQLCIPHER_DEFAULT_TEMP_CACHE_SIZE
224 # define SQLCIPHER_DEFAULT_TEMP_CACHE_SIZE  500
225 #endif
226
227 /*
228 ** The default number of frames to accumulate in the log file before
229 ** checkpointing the database in WAL mode.
230 */
231 #ifndef SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT
232 # define SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT  1000
233 #endif
234
235 /*
236 ** The maximum number of attached databases.  This must be between 0
237 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
238 ** is used internally to track attached databases.
239 */
240 #ifndef SQLCIPHER_MAX_ATTACHED
241 # define SQLCIPHER_MAX_ATTACHED 10
242 #endif
243
244
245 /*
246 ** The maximum value of a ?nnn wildcard that the parser will accept.
247 */
248 #ifndef SQLCIPHER_MAX_VARIABLE_NUMBER
249 # define SQLCIPHER_MAX_VARIABLE_NUMBER 999
250 #endif
251
252 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
253 ** imposed by the use of 16-bit offsets within each page.
254 **
255 ** Earlier versions of SQLite allowed the user to change this value at
256 ** compile time. This is no longer permitted, on the grounds that it creates
257 ** a library that is technically incompatible with an SQLite library 
258 ** compiled with a different limit. If a process operating on a database 
259 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
260 ** compiled with the default page-size limit will not be able to rollback 
261 ** the aborted transaction. This could lead to database corruption.
262 */
263 #ifdef SQLCIPHER_MAX_PAGE_SIZE
264 # undef SQLCIPHER_MAX_PAGE_SIZE
265 #endif
266 #define SQLCIPHER_MAX_PAGE_SIZE 65536
267
268
269 /*
270 ** The default size of a database page.
271 */
272 #ifndef SQLCIPHER_DEFAULT_PAGE_SIZE
273 # define SQLCIPHER_DEFAULT_PAGE_SIZE 1024
274 #endif
275 #if SQLCIPHER_DEFAULT_PAGE_SIZE>SQLCIPHER_MAX_PAGE_SIZE
276 # undef SQLCIPHER_DEFAULT_PAGE_SIZE
277 # define SQLCIPHER_DEFAULT_PAGE_SIZE SQLCIPHER_MAX_PAGE_SIZE
278 #endif
279
280 /*
281 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
282 ** with page size SQLCIPHER_DEFAULT_PAGE_SIZE. However, based on certain
283 ** device characteristics (sector-size and atomic write() support),
284 ** SQLite may choose a larger value. This constant is the maximum value
285 ** SQLite will choose on its own.
286 */
287 #ifndef SQLCIPHER_MAX_DEFAULT_PAGE_SIZE
288 # define SQLCIPHER_MAX_DEFAULT_PAGE_SIZE 8192
289 #endif
290 #if SQLCIPHER_MAX_DEFAULT_PAGE_SIZE>SQLCIPHER_MAX_PAGE_SIZE
291 # undef SQLCIPHER_MAX_DEFAULT_PAGE_SIZE
292 # define SQLCIPHER_MAX_DEFAULT_PAGE_SIZE SQLCIPHER_MAX_PAGE_SIZE
293 #endif
294
295
296 /*
297 ** Maximum number of pages in one database file.
298 **
299 ** This is really just the default value for the max_page_count pragma.
300 ** This value can be lowered (or raised) at run-time using that the
301 ** max_page_count macro.
302 */
303 #ifndef SQLCIPHER_MAX_PAGE_COUNT
304 # define SQLCIPHER_MAX_PAGE_COUNT 1073741823
305 #endif
306
307 /*
308 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
309 ** operator.
310 */
311 #ifndef SQLCIPHER_MAX_LIKE_PATTERN_LENGTH
312 # define SQLCIPHER_MAX_LIKE_PATTERN_LENGTH 50000
313 #endif
314
315 /*
316 ** Maximum depth of recursion for triggers.
317 **
318 ** A value of 1 means that a trigger program will not be able to itself
319 ** fire any triggers. A value of 0 means that no trigger programs at all 
320 ** may be executed.
321 */
322 #ifndef SQLCIPHER_MAX_TRIGGER_DEPTH
323 # define SQLCIPHER_MAX_TRIGGER_DEPTH 1000
324 #endif
325
326 /************** End of sqlcipherLimit.h *****************************************/
327 /************** Continuing where we left off in sqlcipherInt.h ******************/
328
329 /* Disable nuisance warnings on Borland compilers */
330 #if defined(__BORLANDC__)
331 #pragma warn -rch /* unreachable code */
332 #pragma warn -ccc /* Condition is always true or false */
333 #pragma warn -aus /* Assigned value is never used */
334 #pragma warn -csu /* Comparing signed and unsigned */
335 #pragma warn -spa /* Suspicious pointer arithmetic */
336 #endif
337
338 /* Needed for various definitions... */
339 #ifndef _GNU_SOURCE
340 # define _GNU_SOURCE
341 #endif
342
343 /*
344 ** Include standard header files as necessary
345 */
346 #ifdef HAVE_STDINT_H
347 #include <stdint.h>
348 #endif
349 #ifdef HAVE_INTTYPES_H
350 #include <inttypes.h>
351 #endif
352
353 /*
354 ** The following macros are used to cast pointers to integers and
355 ** integers to pointers.  The way you do this varies from one compiler
356 ** to the next, so we have developed the following set of #if statements
357 ** to generate appropriate macros for a wide range of compilers.
358 **
359 ** The correct "ANSI" way to do this is to use the intptr_t type. 
360 ** Unfortunately, that typedef is not available on all compilers, or
361 ** if it is available, it requires an #include of specific headers
362 ** that vary from one machine to the next.
363 **
364 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
365 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
366 ** So we have to define the macros in different ways depending on the
367 ** compiler.
368 */
369 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
370 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
371 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
372 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
373 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
374 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
375 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
376 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
377 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(intptr_t)(X))
378 #else                          /* Generates a warning - but it always works */
379 # define SQLCIPHER_INT_TO_PTR(X)  ((void*)(X))
380 # define SQLCIPHER_PTR_TO_INT(X)  ((int)(X))
381 #endif
382
383 /*
384 ** The SQLCIPHER_THREADSAFE macro must be defined as 0, 1, or 2.
385 ** 0 means mutexes are permanently disable and the library is never
386 ** threadsafe.  1 means the library is serialized which is the highest
387 ** level of threadsafety.  2 means the libary is multithreaded - multiple
388 ** threads can use SQLite as long as no two threads try to use the same
389 ** database connection at the same time.
390 **
391 ** Older versions of SQLite used an optional THREADSAFE macro.
392 ** We support that for legacy.
393 */
394 #if !defined(SQLCIPHER_THREADSAFE)
395 #if defined(THREADSAFE)
396 # define SQLCIPHER_THREADSAFE THREADSAFE
397 #else
398 # define SQLCIPHER_THREADSAFE 1 /* IMP: R-07272-22309 */
399 #endif
400 #endif
401
402 /*
403 ** The SQLCIPHER_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
404 ** It determines whether or not the features related to 
405 ** SQLCIPHER_CONFIG_MEMSTATUS are available by default or not. This value can
406 ** be overridden at runtime using the sqlcipher3_config() API.
407 */
408 #if !defined(SQLCIPHER_DEFAULT_MEMSTATUS)
409 # define SQLCIPHER_DEFAULT_MEMSTATUS 1
410 #endif
411
412 /*
413 ** Exactly one of the following macros must be defined in order to
414 ** specify which memory allocation subsystem to use.
415 **
416 **     SQLCIPHER_SYSTEM_MALLOC          // Use normal system malloc()
417 **     SQLCIPHER_WIN32_MALLOC           // Use Win32 native heap API
418 **     SQLCIPHER_MEMDEBUG               // Debugging version of system malloc()
419 **
420 ** On Windows, if the SQLCIPHER_WIN32_MALLOC_VALIDATE macro is defined and the
421 ** assert() macro is enabled, each call into the Win32 native heap subsystem
422 ** will cause HeapValidate to be called.  If heap validation should fail, an
423 ** assertion will be triggered.
424 **
425 ** (Historical note:  There used to be several other options, but we've
426 ** pared it down to just these three.)
427 **
428 ** If none of the above are defined, then set SQLCIPHER_SYSTEM_MALLOC as
429 ** the default.
430 */
431 #if defined(SQLCIPHER_SYSTEM_MALLOC)+defined(SQLCIPHER_WIN32_MALLOC)+defined(SQLCIPHER_MEMDEBUG)>1
432 # error "At most one of the following compile-time configuration options\
433  is allows: SQLCIPHER_SYSTEM_MALLOC, SQLCIPHER_WIN32_MALLOC, SQLCIPHER_MEMDEBUG"
434 #endif
435 #if defined(SQLCIPHER_SYSTEM_MALLOC)+defined(SQLCIPHER_WIN32_MALLOC)+defined(SQLCIPHER_MEMDEBUG)==0
436 # define SQLCIPHER_SYSTEM_MALLOC 1
437 #endif
438
439 /*
440 ** If SQLCIPHER_MALLOC_SOFT_LIMIT is not zero, then try to keep the
441 ** sizes of memory allocations below this value where possible.
442 */
443 #if !defined(SQLCIPHER_MALLOC_SOFT_LIMIT)
444 # define SQLCIPHER_MALLOC_SOFT_LIMIT 1024
445 #endif
446
447 /*
448 ** We need to define _XOPEN_SOURCE as follows in order to enable
449 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
450 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
451 ** so it is omitted there.  See ticket #2673.
452 **
453 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
454 ** implemented on some systems.  So we avoid defining it at all
455 ** if it is already defined or if it is unneeded because we are
456 ** not doing a threadsafe build.  Ticket #2681.
457 **
458 ** See also ticket #2741.
459 */
460 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLCIPHER_THREADSAFE
461 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
462 #endif
463
464 /*
465 ** The TCL headers are only needed when compiling the TCL bindings.
466 */
467 #if defined(SQLCIPHER_TCL) || defined(TCLSH)
468 # include <tcl.h>
469 #endif
470
471 /*
472 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
473 ** Setting NDEBUG makes the code smaller and run faster.  So the following
474 ** lines are added to automatically set NDEBUG unless the -DSQLCIPHER_DEBUG=1
475 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
476 ** feature.
477 */
478 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
479 # define NDEBUG 1
480 #endif
481
482 /*
483 ** The testcase() macro is used to aid in coverage testing.  When 
484 ** doing coverage testing, the condition inside the argument to
485 ** testcase() must be evaluated both true and false in order to
486 ** get full branch coverage.  The testcase() macro is inserted
487 ** to help ensure adequate test coverage in places where simple
488 ** condition/decision coverage is inadequate.  For example, testcase()
489 ** can be used to make sure boundary values are tested.  For
490 ** bitmask tests, testcase() can be used to make sure each bit
491 ** is significant and used at least once.  On switch statements
492 ** where multiple cases go to the same block of code, testcase()
493 ** can insure that all cases are evaluated.
494 **
495 */
496 #ifdef SQLCIPHER_COVERAGE_TEST
497 SQLCIPHER_PRIVATE   void sqlcipher3Coverage(int);
498 # define testcase(X)  if( X ){ sqlcipher3Coverage(__LINE__); }
499 #else
500 # define testcase(X)
501 #endif
502
503 /*
504 ** The TESTONLY macro is used to enclose variable declarations or
505 ** other bits of code that are needed to support the arguments
506 ** within testcase() and assert() macros.
507 */
508 #if !defined(NDEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
509 # define TESTONLY(X)  X
510 #else
511 # define TESTONLY(X)
512 #endif
513
514 /*
515 ** Sometimes we need a small amount of code such as a variable initialization
516 ** to setup for a later assert() statement.  We do not want this code to
517 ** appear when assert() is disabled.  The following macro is therefore
518 ** used to contain that setup code.  The "VVA" acronym stands for
519 ** "Verification, Validation, and Accreditation".  In other words, the
520 ** code within VVA_ONLY() will only run during verification processes.
521 */
522 #ifndef NDEBUG
523 # define VVA_ONLY(X)  X
524 #else
525 # define VVA_ONLY(X)
526 #endif
527
528 /*
529 ** The ALWAYS and NEVER macros surround boolean expressions which 
530 ** are intended to always be true or false, respectively.  Such
531 ** expressions could be omitted from the code completely.  But they
532 ** are included in a few cases in order to enhance the resilience
533 ** of SQLite to unexpected behavior - to make the code "self-healing"
534 ** or "ductile" rather than being "brittle" and crashing at the first
535 ** hint of unplanned behavior.
536 **
537 ** In other words, ALWAYS and NEVER are added for defensive code.
538 **
539 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
540 ** be true and false so that the unreachable code then specify will
541 ** not be counted as untested code.
542 */
543 #if defined(SQLCIPHER_COVERAGE_TEST)
544 # define ALWAYS(X)      (1)
545 # define NEVER(X)       (0)
546 #elif !defined(NDEBUG)
547 # define ALWAYS(X)      ((X)?1:(assert(0),0))
548 # define NEVER(X)       ((X)?(assert(0),1):0)
549 #else
550 # define ALWAYS(X)      (X)
551 # define NEVER(X)       (X)
552 #endif
553
554 /*
555 ** Return true (non-zero) if the input is a integer that is too large
556 ** to fit in 32-bits.  This macro is used inside of various testcase()
557 ** macros to verify that we have tested SQLite for large-file support.
558 */
559 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
560
561 /*
562 ** The macro unlikely() is a hint that surrounds a boolean
563 ** expression that is usually false.  Macro likely() surrounds
564 ** a boolean expression that is usually true.  GCC is able to
565 ** use these hints to generate better code, sometimes.
566 */
567 #if defined(__GNUC__) && 0
568 # define likely(X)    __builtin_expect((X),1)
569 # define unlikely(X)  __builtin_expect((X),0)
570 #else
571 # define likely(X)    !!(X)
572 # define unlikely(X)  !!(X)
573 #endif
574
575 /************** Include sqlcipher3.h in the middle of sqlcipherInt.h ***************/
576 /************** Begin file sqlcipher3.h *****************************************/
577 /*
578 ** 2001 September 15
579 **
580 ** The author disclaims copyright to this source code.  In place of
581 ** a legal notice, here is a blessing:
582 **
583 **    May you do good and not evil.
584 **    May you find forgiveness for yourself and forgive others.
585 **    May you share freely, never taking more than you give.
586 **
587 *************************************************************************
588 ** This header file defines the interface that the SQLite library
589 ** presents to client programs.  If a C-function, structure, datatype,
590 ** or constant definition does not appear in this file, then it is
591 ** not a published API of SQLite, is subject to change without
592 ** notice, and should not be referenced by programs that use SQLite.
593 **
594 ** Some of the definitions that are in this file are marked as
595 ** "experimental".  Experimental interfaces are normally new
596 ** features recently added to SQLite.  We do not anticipate changes
597 ** to experimental interfaces but reserve the right to make minor changes
598 ** if experience from use "in the wild" suggest such changes are prudent.
599 **
600 ** The official C-language API documentation for SQLite is derived
601 ** from comments in this file.  This file is the authoritative source
602 ** on how SQLite interfaces are suppose to operate.
603 **
604 ** The name of this file under configuration management is "sqlcipher.h.in".
605 ** The makefile makes some minor changes to this file (such as inserting
606 ** the version number) and changes its name to "sqlcipher3.h" as
607 ** part of the build process.
608 */
609 #ifndef _SQLCIPHER3_H_
610 #define _SQLCIPHER3_H_
611 #include <stdarg.h>     /* Needed for the definition of va_list */
612
613 /*
614 ** Make sure we can call this stuff from C++.
615 */
616 #if 0
617 extern "C" {
618 #endif
619
620
621 /*
622 ** Add the ability to override 'extern'
623 */
624 #ifndef SQLCIPHER_EXTERN
625 # define SQLCIPHER_EXTERN extern
626 #endif
627
628 #ifndef SQLCIPHER_API
629 # define SQLCIPHER_API
630 #endif
631
632
633 /*
634 ** These no-op macros are used in front of interfaces to mark those
635 ** interfaces as either deprecated or experimental.  New applications
636 ** should not use deprecated interfaces - they are support for backwards
637 ** compatibility only.  Application writers should be aware that
638 ** experimental interfaces are subject to change in point releases.
639 **
640 ** These macros used to resolve to various kinds of compiler magic that
641 ** would generate warning messages when they were used.  But that
642 ** compiler magic ended up generating such a flurry of bug reports
643 ** that we have taken it all out and gone back to using simple
644 ** noop macros.
645 */
646 #define SQLCIPHER_DEPRECATED
647 #define SQLCIPHER_EXPERIMENTAL
648
649 /*
650 ** Ensure these symbols were not defined by some previous header file.
651 */
652 #ifdef SQLCIPHER_VERSION
653 # undef SQLCIPHER_VERSION
654 #endif
655 #ifdef SQLCIPHER_VERSION_NUMBER
656 # undef SQLCIPHER_VERSION_NUMBER
657 #endif
658
659 /*
660 ** CAPI3REF: Compile-Time Library Version Numbers
661 **
662 ** ^(The [SQLCIPHER_VERSION] C preprocessor macro in the sqlcipher3.h header
663 ** evaluates to a string literal that is the SQLite version in the
664 ** format "X.Y.Z" where X is the major version number (always 3 for
665 ** SQLite3) and Y is the minor version number and Z is the release number.)^
666 ** ^(The [SQLCIPHER_VERSION_NUMBER] C preprocessor macro resolves to an integer
667 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
668 ** numbers used in [SQLCIPHER_VERSION].)^
669 ** The SQLCIPHER_VERSION_NUMBER for any given release of SQLite will also
670 ** be larger than the release from which it is derived.  Either Y will
671 ** be held constant and Z will be incremented or else Y will be incremented
672 ** and Z will be reset to zero.
673 **
674 ** Since version 3.6.18, SQLite source code has been stored in the
675 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
676 ** system</a>.  ^The SQLCIPHER_SOURCE_ID macro evaluates to
677 ** a string which identifies a particular check-in of SQLite
678 ** within its configuration management system.  ^The SQLCIPHER_SOURCE_ID
679 ** string contains the date and time of the check-in (UTC) and an SHA1
680 ** hash of the entire source tree.
681 **
682 ** See also: [sqlcipher3_libversion()],
683 ** [sqlcipher3_libversion_number()], [sqlcipher3_sourceid()],
684 ** [sqlcipher_version()] and [sqlcipher_source_id()].
685 */
686 #define SQLCIPHER_VERSION        "3.7.9"
687 #define SQLCIPHER_VERSION_NUMBER 3007009
688 #define SQLCIPHER_SOURCE_ID      "2011-11-01 00:52:41 c7c6050ef060877ebe77b41d959e9df13f8c9b5e"
689
690 /*
691 ** CAPI3REF: Run-Time Library Version Numbers
692 ** KEYWORDS: sqlcipher3_version, sqlcipher3_sourceid
693 **
694 ** These interfaces provide the same information as the [SQLCIPHER_VERSION],
695 ** [SQLCIPHER_VERSION_NUMBER], and [SQLCIPHER_SOURCE_ID] C preprocessor macros
696 ** but are associated with the library instead of the header file.  ^(Cautious
697 ** programmers might include assert() statements in their application to
698 ** verify that values returned by these interfaces match the macros in
699 ** the header, and thus insure that the application is
700 ** compiled with matching library and header files.
701 **
702 ** <blockquote><pre>
703 ** assert( sqlcipher3_libversion_number()==SQLCIPHER_VERSION_NUMBER );
704 ** assert( strcmp(sqlcipher3_sourceid(),SQLCIPHER_SOURCE_ID)==0 );
705 ** assert( strcmp(sqlcipher3_libversion(),SQLCIPHER_VERSION)==0 );
706 ** </pre></blockquote>)^
707 **
708 ** ^The sqlcipher3_version[] string constant contains the text of [SQLCIPHER_VERSION]
709 ** macro.  ^The sqlcipher3_libversion() function returns a pointer to the
710 ** to the sqlcipher3_version[] string constant.  The sqlcipher3_libversion()
711 ** function is provided for use in DLLs since DLL users usually do not have
712 ** direct access to string constants within the DLL.  ^The
713 ** sqlcipher3_libversion_number() function returns an integer equal to
714 ** [SQLCIPHER_VERSION_NUMBER].  ^The sqlcipher3_sourceid() function returns 
715 ** a pointer to a string constant whose value is the same as the 
716 ** [SQLCIPHER_SOURCE_ID] C preprocessor macro.
717 **
718 ** See also: [sqlcipher_version()] and [sqlcipher_source_id()].
719 */
720 SQLCIPHER_API const char sqlcipher3_version[] = SQLCIPHER_VERSION;
721 SQLCIPHER_API const char *sqlcipher3_libversion(void);
722 SQLCIPHER_API const char *sqlcipher3_sourceid(void);
723 SQLCIPHER_API int sqlcipher3_libversion_number(void);
724
725 /*
726 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
727 **
728 ** ^The sqlcipher3_compileoption_used() function returns 0 or 1 
729 ** indicating whether the specified option was defined at 
730 ** compile time.  ^The SQLCIPHER_ prefix may be omitted from the 
731 ** option name passed to sqlcipher3_compileoption_used().  
732 **
733 ** ^The sqlcipher3_compileoption_get() function allows iterating
734 ** over the list of options that were defined at compile time by
735 ** returning the N-th compile time option string.  ^If N is out of range,
736 ** sqlcipher3_compileoption_get() returns a NULL pointer.  ^The SQLCIPHER_ 
737 ** prefix is omitted from any strings returned by 
738 ** sqlcipher3_compileoption_get().
739 **
740 ** ^Support for the diagnostic functions sqlcipher3_compileoption_used()
741 ** and sqlcipher3_compileoption_get() may be omitted by specifying the 
742 ** [SQLCIPHER_OMIT_COMPILEOPTION_DIAGS] option at compile time.
743 **
744 ** See also: SQL functions [sqlcipher_compileoption_used()] and
745 ** [sqlcipher_compileoption_get()] and the [compile_options pragma].
746 */
747 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
748 SQLCIPHER_API int sqlcipher3_compileoption_used(const char *zOptName);
749 SQLCIPHER_API const char *sqlcipher3_compileoption_get(int N);
750 #endif
751
752 /*
753 ** CAPI3REF: Test To See If The Library Is Threadsafe
754 **
755 ** ^The sqlcipher3_threadsafe() function returns zero if and only if
756 ** SQLite was compiled mutexing code omitted due to the
757 ** [SQLCIPHER_THREADSAFE] compile-time option being set to 0.
758 **
759 ** SQLite can be compiled with or without mutexes.  When
760 ** the [SQLCIPHER_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
761 ** are enabled and SQLite is threadsafe.  When the
762 ** [SQLCIPHER_THREADSAFE] macro is 0, 
763 ** the mutexes are omitted.  Without the mutexes, it is not safe
764 ** to use SQLite concurrently from more than one thread.
765 **
766 ** Enabling mutexes incurs a measurable performance penalty.
767 ** So if speed is of utmost importance, it makes sense to disable
768 ** the mutexes.  But for maximum safety, mutexes should be enabled.
769 ** ^The default behavior is for mutexes to be enabled.
770 **
771 ** This interface can be used by an application to make sure that the
772 ** version of SQLite that it is linking against was compiled with
773 ** the desired setting of the [SQLCIPHER_THREADSAFE] macro.
774 **
775 ** This interface only reports on the compile-time mutex setting
776 ** of the [SQLCIPHER_THREADSAFE] flag.  If SQLite is compiled with
777 ** SQLCIPHER_THREADSAFE=1 or =2 then mutexes are enabled by default but
778 ** can be fully or partially disabled using a call to [sqlcipher3_config()]
779 ** with the verbs [SQLCIPHER_CONFIG_SINGLETHREAD], [SQLCIPHER_CONFIG_MULTITHREAD],
780 ** or [SQLCIPHER_CONFIG_MUTEX].  ^(The return value of the
781 ** sqlcipher3_threadsafe() function shows only the compile-time setting of
782 ** thread safety, not any run-time changes to that setting made by
783 ** sqlcipher3_config(). In other words, the return value from sqlcipher3_threadsafe()
784 ** is unchanged by calls to sqlcipher3_config().)^
785 **
786 ** See the [threading mode] documentation for additional information.
787 */
788 SQLCIPHER_API int sqlcipher3_threadsafe(void);
789
790 /*
791 ** CAPI3REF: Database Connection Handle
792 ** KEYWORDS: {database connection} {database connections}
793 **
794 ** Each open SQLite database is represented by a pointer to an instance of
795 ** the opaque structure named "sqlcipher3".  It is useful to think of an sqlcipher3
796 ** pointer as an object.  The [sqlcipher3_open()], [sqlcipher3_open16()], and
797 ** [sqlcipher3_open_v2()] interfaces are its constructors, and [sqlcipher3_close()]
798 ** is its destructor.  There are many other interfaces (such as
799 ** [sqlcipher3_prepare_v2()], [sqlcipher3_create_function()], and
800 ** [sqlcipher3_busy_timeout()] to name but three) that are methods on an
801 ** sqlcipher3 object.
802 */
803 typedef struct sqlcipher3 sqlcipher3;
804
805 /*
806 ** CAPI3REF: 64-Bit Integer Types
807 ** KEYWORDS: sqlcipher_int64 sqlcipher_uint64
808 **
809 ** Because there is no cross-platform way to specify 64-bit integer types
810 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
811 **
812 ** The sqlcipher3_int64 and sqlcipher3_uint64 are the preferred type definitions.
813 ** The sqlcipher_int64 and sqlcipher_uint64 types are supported for backwards
814 ** compatibility only.
815 **
816 ** ^The sqlcipher3_int64 and sqlcipher_int64 types can store integer values
817 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
818 ** sqlcipher3_uint64 and sqlcipher_uint64 types can store integer values 
819 ** between 0 and +18446744073709551615 inclusive.
820 */
821 #ifdef SQLCIPHER_INT64_TYPE
822   typedef SQLCIPHER_INT64_TYPE sqlcipher_int64;
823   typedef unsigned SQLCIPHER_INT64_TYPE sqlcipher_uint64;
824 #elif defined(_MSC_VER) || defined(__BORLANDC__)
825   typedef __int64 sqlcipher_int64;
826   typedef unsigned __int64 sqlcipher_uint64;
827 #else
828   typedef long long int sqlcipher_int64;
829   typedef unsigned long long int sqlcipher_uint64;
830 #endif
831 typedef sqlcipher_int64 sqlcipher3_int64;
832 typedef sqlcipher_uint64 sqlcipher3_uint64;
833
834 /*
835 ** If compiling for a processor that lacks floating point support,
836 ** substitute integer for floating-point.
837 */
838 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
839 # define double sqlcipher3_int64
840 #endif
841
842 /*
843 ** CAPI3REF: Closing A Database Connection
844 **
845 ** ^The sqlcipher3_close() routine is the destructor for the [sqlcipher3] object.
846 ** ^Calls to sqlcipher3_close() return SQLCIPHER_OK if the [sqlcipher3] object is
847 ** successfully destroyed and all associated resources are deallocated.
848 **
849 ** Applications must [sqlcipher3_finalize | finalize] all [prepared statements]
850 ** and [sqlcipher3_blob_close | close] all [BLOB handles] associated with
851 ** the [sqlcipher3] object prior to attempting to close the object.  ^If
852 ** sqlcipher3_close() is called on a [database connection] that still has
853 ** outstanding [prepared statements] or [BLOB handles], then it returns
854 ** SQLCIPHER_BUSY.
855 **
856 ** ^If [sqlcipher3_close()] is invoked while a transaction is open,
857 ** the transaction is automatically rolled back.
858 **
859 ** The C parameter to [sqlcipher3_close(C)] must be either a NULL
860 ** pointer or an [sqlcipher3] object pointer obtained
861 ** from [sqlcipher3_open()], [sqlcipher3_open16()], or
862 ** [sqlcipher3_open_v2()], and not previously closed.
863 ** ^Calling sqlcipher3_close() with a NULL pointer argument is a 
864 ** harmless no-op.
865 */
866 SQLCIPHER_API int sqlcipher3_close(sqlcipher3 *);
867
868 /*
869 ** The type for a callback function.
870 ** This is legacy and deprecated.  It is included for historical
871 ** compatibility and is not documented.
872 */
873 typedef int (*sqlcipher3_callback)(void*,int,char**, char**);
874
875 /*
876 ** CAPI3REF: One-Step Query Execution Interface
877 **
878 ** The sqlcipher3_exec() interface is a convenience wrapper around
879 ** [sqlcipher3_prepare_v2()], [sqlcipher3_step()], and [sqlcipher3_finalize()],
880 ** that allows an application to run multiple statements of SQL
881 ** without having to use a lot of C code. 
882 **
883 ** ^The sqlcipher3_exec() interface runs zero or more UTF-8 encoded,
884 ** semicolon-separate SQL statements passed into its 2nd argument,
885 ** in the context of the [database connection] passed in as its 1st
886 ** argument.  ^If the callback function of the 3rd argument to
887 ** sqlcipher3_exec() is not NULL, then it is invoked for each result row
888 ** coming out of the evaluated SQL statements.  ^The 4th argument to
889 ** sqlcipher3_exec() is relayed through to the 1st argument of each
890 ** callback invocation.  ^If the callback pointer to sqlcipher3_exec()
891 ** is NULL, then no callback is ever invoked and result rows are
892 ** ignored.
893 **
894 ** ^If an error occurs while evaluating the SQL statements passed into
895 ** sqlcipher3_exec(), then execution of the current statement stops and
896 ** subsequent statements are skipped.  ^If the 5th parameter to sqlcipher3_exec()
897 ** is not NULL then any error message is written into memory obtained
898 ** from [sqlcipher3_malloc()] and passed back through the 5th parameter.
899 ** To avoid memory leaks, the application should invoke [sqlcipher3_free()]
900 ** on error message strings returned through the 5th parameter of
901 ** of sqlcipher3_exec() after the error message string is no longer needed.
902 ** ^If the 5th parameter to sqlcipher3_exec() is not NULL and no errors
903 ** occur, then sqlcipher3_exec() sets the pointer in its 5th parameter to
904 ** NULL before returning.
905 **
906 ** ^If an sqlcipher3_exec() callback returns non-zero, the sqlcipher3_exec()
907 ** routine returns SQLCIPHER_ABORT without invoking the callback again and
908 ** without running any subsequent SQL statements.
909 **
910 ** ^The 2nd argument to the sqlcipher3_exec() callback function is the
911 ** number of columns in the result.  ^The 3rd argument to the sqlcipher3_exec()
912 ** callback is an array of pointers to strings obtained as if from
913 ** [sqlcipher3_column_text()], one for each column.  ^If an element of a
914 ** result row is NULL then the corresponding string pointer for the
915 ** sqlcipher3_exec() callback is a NULL pointer.  ^The 4th argument to the
916 ** sqlcipher3_exec() callback is an array of pointers to strings where each
917 ** entry represents the name of corresponding result column as obtained
918 ** from [sqlcipher3_column_name()].
919 **
920 ** ^If the 2nd parameter to sqlcipher3_exec() is a NULL pointer, a pointer
921 ** to an empty string, or a pointer that contains only whitespace and/or 
922 ** SQL comments, then no SQL statements are evaluated and the database
923 ** is not changed.
924 **
925 ** Restrictions:
926 **
927 ** <ul>
928 ** <li> The application must insure that the 1st parameter to sqlcipher3_exec()
929 **      is a valid and open [database connection].
930 ** <li> The application must not close [database connection] specified by
931 **      the 1st parameter to sqlcipher3_exec() while sqlcipher3_exec() is running.
932 ** <li> The application must not modify the SQL statement text passed into
933 **      the 2nd parameter of sqlcipher3_exec() while sqlcipher3_exec() is running.
934 ** </ul>
935 */
936 SQLCIPHER_API int sqlcipher3_exec(
937   sqlcipher3*,                                  /* An open database */
938   const char *sql,                           /* SQL to be evaluated */
939   int (*callback)(void*,int,char**,char**),  /* Callback function */
940   void *,                                    /* 1st argument to callback */
941   char **errmsg                              /* Error msg written here */
942 );
943
944 /*
945 ** CAPI3REF: Result Codes
946 ** KEYWORDS: SQLCIPHER_OK {error code} {error codes}
947 ** KEYWORDS: {result code} {result codes}
948 **
949 ** Many SQLite functions return an integer result code from the set shown
950 ** here in order to indicates success or failure.
951 **
952 ** New error codes may be added in future versions of SQLite.
953 **
954 ** See also: [SQLCIPHER_IOERR_READ | extended result codes],
955 ** [sqlcipher3_vtab_on_conflict()] [SQLCIPHER_ROLLBACK | result codes].
956 */
957 #define SQLCIPHER_OK           0   /* Successful result */
958 /* beginning-of-error-codes */
959 #define SQLCIPHER_ERROR        1   /* SQL error or missing database */
960 #define SQLCIPHER_INTERNAL     2   /* Internal logic error in SQLite */
961 #define SQLCIPHER_PERM         3   /* Access permission denied */
962 #define SQLCIPHER_ABORT        4   /* Callback routine requested an abort */
963 #define SQLCIPHER_BUSY         5   /* The database file is locked */
964 #define SQLCIPHER_LOCKED       6   /* A table in the database is locked */
965 #define SQLCIPHER_NOMEM        7   /* A malloc() failed */
966 #define SQLCIPHER_READONLY     8   /* Attempt to write a readonly database */
967 #define SQLCIPHER_INTERRUPT    9   /* Operation terminated by sqlcipher3_interrupt()*/
968 #define SQLCIPHER_IOERR       10   /* Some kind of disk I/O error occurred */
969 #define SQLCIPHER_CORRUPT     11   /* The database disk image is malformed */
970 #define SQLCIPHER_NOTFOUND    12   /* Unknown opcode in sqlcipher3_file_control() */
971 #define SQLCIPHER_FULL        13   /* Insertion failed because database is full */
972 #define SQLCIPHER_CANTOPEN    14   /* Unable to open the database file */
973 #define SQLCIPHER_PROTOCOL    15   /* Database lock protocol error */
974 #define SQLCIPHER_EMPTY       16   /* Database is empty */
975 #define SQLCIPHER_SCHEMA      17   /* The database schema changed */
976 #define SQLCIPHER_TOOBIG      18   /* String or BLOB exceeds size limit */
977 #define SQLCIPHER_CONSTRAINT  19   /* Abort due to constraint violation */
978 #define SQLCIPHER_MISMATCH    20   /* Data type mismatch */
979 #define SQLCIPHER_MISUSE      21   /* Library used incorrectly */
980 #define SQLCIPHER_NOLFS       22   /* Uses OS features not supported on host */
981 #define SQLCIPHER_AUTH        23   /* Authorization denied */
982 #define SQLCIPHER_FORMAT      24   /* Auxiliary database format error */
983 #define SQLCIPHER_RANGE       25   /* 2nd parameter to sqlcipher3_bind out of range */
984 #define SQLCIPHER_NOTADB      26   /* File opened that is not a database file */
985 #define SQLCIPHER_ROW         100  /* sqlcipher3_step() has another row ready */
986 #define SQLCIPHER_DONE        101  /* sqlcipher3_step() has finished executing */
987 /* end-of-error-codes */
988
989 /*
990 ** CAPI3REF: Extended Result Codes
991 ** KEYWORDS: {extended error code} {extended error codes}
992 ** KEYWORDS: {extended result code} {extended result codes}
993 **
994 ** In its default configuration, SQLite API routines return one of 26 integer
995 ** [SQLCIPHER_OK | result codes].  However, experience has shown that many of
996 ** these result codes are too coarse-grained.  They do not provide as
997 ** much information about problems as programmers might like.  In an effort to
998 ** address this, newer versions of SQLite (version 3.3.8 and later) include
999 ** support for additional result codes that provide more detailed information
1000 ** about errors. The extended result codes are enabled or disabled
1001 ** on a per database connection basis using the
1002 ** [sqlcipher3_extended_result_codes()] API.
1003 **
1004 ** Some of the available extended result codes are listed here.
1005 ** One may expect the number of extended result codes will be expand
1006 ** over time.  Software that uses extended result codes should expect
1007 ** to see new result codes in future releases of SQLite.
1008 **
1009 ** The SQLCIPHER_OK result code will never be extended.  It will always
1010 ** be exactly zero.
1011 */
1012 #define SQLCIPHER_IOERR_READ              (SQLCIPHER_IOERR | (1<<8))
1013 #define SQLCIPHER_IOERR_SHORT_READ        (SQLCIPHER_IOERR | (2<<8))
1014 #define SQLCIPHER_IOERR_WRITE             (SQLCIPHER_IOERR | (3<<8))
1015 #define SQLCIPHER_IOERR_FSYNC             (SQLCIPHER_IOERR | (4<<8))
1016 #define SQLCIPHER_IOERR_DIR_FSYNC         (SQLCIPHER_IOERR | (5<<8))
1017 #define SQLCIPHER_IOERR_TRUNCATE          (SQLCIPHER_IOERR | (6<<8))
1018 #define SQLCIPHER_IOERR_FSTAT             (SQLCIPHER_IOERR | (7<<8))
1019 #define SQLCIPHER_IOERR_UNLOCK            (SQLCIPHER_IOERR | (8<<8))
1020 #define SQLCIPHER_IOERR_RDLOCK            (SQLCIPHER_IOERR | (9<<8))
1021 #define SQLCIPHER_IOERR_DELETE            (SQLCIPHER_IOERR | (10<<8))
1022 #define SQLCIPHER_IOERR_BLOCKED           (SQLCIPHER_IOERR | (11<<8))
1023 #define SQLCIPHER_IOERR_NOMEM             (SQLCIPHER_IOERR | (12<<8))
1024 #define SQLCIPHER_IOERR_ACCESS            (SQLCIPHER_IOERR | (13<<8))
1025 #define SQLCIPHER_IOERR_CHECKRESERVEDLOCK (SQLCIPHER_IOERR | (14<<8))
1026 #define SQLCIPHER_IOERR_LOCK              (SQLCIPHER_IOERR | (15<<8))
1027 #define SQLCIPHER_IOERR_CLOSE             (SQLCIPHER_IOERR | (16<<8))
1028 #define SQLCIPHER_IOERR_DIR_CLOSE         (SQLCIPHER_IOERR | (17<<8))
1029 #define SQLCIPHER_IOERR_SHMOPEN           (SQLCIPHER_IOERR | (18<<8))
1030 #define SQLCIPHER_IOERR_SHMSIZE           (SQLCIPHER_IOERR | (19<<8))
1031 #define SQLCIPHER_IOERR_SHMLOCK           (SQLCIPHER_IOERR | (20<<8))
1032 #define SQLCIPHER_IOERR_SHMMAP            (SQLCIPHER_IOERR | (21<<8))
1033 #define SQLCIPHER_IOERR_SEEK              (SQLCIPHER_IOERR | (22<<8))
1034 #define SQLCIPHER_LOCKED_SHAREDCACHE      (SQLCIPHER_LOCKED |  (1<<8))
1035 #define SQLCIPHER_BUSY_RECOVERY           (SQLCIPHER_BUSY   |  (1<<8))
1036 #define SQLCIPHER_CANTOPEN_NOTEMPDIR      (SQLCIPHER_CANTOPEN | (1<<8))
1037 #define SQLCIPHER_CORRUPT_VTAB            (SQLCIPHER_CORRUPT | (1<<8))
1038 #define SQLCIPHER_READONLY_RECOVERY       (SQLCIPHER_READONLY | (1<<8))
1039 #define SQLCIPHER_READONLY_CANTLOCK       (SQLCIPHER_READONLY | (2<<8))
1040
1041 /*
1042 ** CAPI3REF: Flags For File Open Operations
1043 **
1044 ** These bit values are intended for use in the
1045 ** 3rd parameter to the [sqlcipher3_open_v2()] interface and
1046 ** in the 4th parameter to the [sqlcipher3_vfs.xOpen] method.
1047 */
1048 #define SQLCIPHER_OPEN_READONLY         0x00000001  /* Ok for sqlcipher3_open_v2() */
1049 #define SQLCIPHER_OPEN_READWRITE        0x00000002  /* Ok for sqlcipher3_open_v2() */
1050 #define SQLCIPHER_OPEN_CREATE           0x00000004  /* Ok for sqlcipher3_open_v2() */
1051 #define SQLCIPHER_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1052 #define SQLCIPHER_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1053 #define SQLCIPHER_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1054 #define SQLCIPHER_OPEN_URI              0x00000040  /* Ok for sqlcipher3_open_v2() */
1055 #define SQLCIPHER_OPEN_MAIN_DB          0x00000100  /* VFS only */
1056 #define SQLCIPHER_OPEN_TEMP_DB          0x00000200  /* VFS only */
1057 #define SQLCIPHER_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1058 #define SQLCIPHER_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1059 #define SQLCIPHER_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1060 #define SQLCIPHER_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1061 #define SQLCIPHER_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1062 #define SQLCIPHER_OPEN_NOMUTEX          0x00008000  /* Ok for sqlcipher3_open_v2() */
1063 #define SQLCIPHER_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlcipher3_open_v2() */
1064 #define SQLCIPHER_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlcipher3_open_v2() */
1065 #define SQLCIPHER_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlcipher3_open_v2() */
1066 #define SQLCIPHER_OPEN_WAL              0x00080000  /* VFS only */
1067
1068 /* Reserved:                         0x00F00000 */
1069
1070 /*
1071 ** CAPI3REF: Device Characteristics
1072 **
1073 ** The xDeviceCharacteristics method of the [sqlcipher3_io_methods]
1074 ** object returns an integer which is a vector of the these
1075 ** bit values expressing I/O characteristics of the mass storage
1076 ** device that holds the file that the [sqlcipher3_io_methods]
1077 ** refers to.
1078 **
1079 ** The SQLCIPHER_IOCAP_ATOMIC property means that all writes of
1080 ** any size are atomic.  The SQLCIPHER_IOCAP_ATOMICnnn values
1081 ** mean that writes of blocks that are nnn bytes in size and
1082 ** are aligned to an address which is an integer multiple of
1083 ** nnn are atomic.  The SQLCIPHER_IOCAP_SAFE_APPEND value means
1084 ** that when data is appended to a file, the data is appended
1085 ** first then the size of the file is extended, never the other
1086 ** way around.  The SQLCIPHER_IOCAP_SEQUENTIAL property means that
1087 ** information is written to disk in the same order as calls
1088 ** to xWrite().
1089 */
1090 #define SQLCIPHER_IOCAP_ATOMIC                 0x00000001
1091 #define SQLCIPHER_IOCAP_ATOMIC512              0x00000002
1092 #define SQLCIPHER_IOCAP_ATOMIC1K               0x00000004
1093 #define SQLCIPHER_IOCAP_ATOMIC2K               0x00000008
1094 #define SQLCIPHER_IOCAP_ATOMIC4K               0x00000010
1095 #define SQLCIPHER_IOCAP_ATOMIC8K               0x00000020
1096 #define SQLCIPHER_IOCAP_ATOMIC16K              0x00000040
1097 #define SQLCIPHER_IOCAP_ATOMIC32K              0x00000080
1098 #define SQLCIPHER_IOCAP_ATOMIC64K              0x00000100
1099 #define SQLCIPHER_IOCAP_SAFE_APPEND            0x00000200
1100 #define SQLCIPHER_IOCAP_SEQUENTIAL             0x00000400
1101 #define SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1102
1103 /*
1104 ** CAPI3REF: File Locking Levels
1105 **
1106 ** SQLite uses one of these integer values as the second
1107 ** argument to calls it makes to the xLock() and xUnlock() methods
1108 ** of an [sqlcipher3_io_methods] object.
1109 */
1110 #define SQLCIPHER_LOCK_NONE          0
1111 #define SQLCIPHER_LOCK_SHARED        1
1112 #define SQLCIPHER_LOCK_RESERVED      2
1113 #define SQLCIPHER_LOCK_PENDING       3
1114 #define SQLCIPHER_LOCK_EXCLUSIVE     4
1115
1116 /*
1117 ** CAPI3REF: Synchronization Type Flags
1118 **
1119 ** When SQLite invokes the xSync() method of an
1120 ** [sqlcipher3_io_methods] object it uses a combination of
1121 ** these integer values as the second argument.
1122 **
1123 ** When the SQLCIPHER_SYNC_DATAONLY flag is used, it means that the
1124 ** sync operation only needs to flush data to mass storage.  Inode
1125 ** information need not be flushed. If the lower four bits of the flag
1126 ** equal SQLCIPHER_SYNC_NORMAL, that means to use normal fsync() semantics.
1127 ** If the lower four bits equal SQLCIPHER_SYNC_FULL, that means
1128 ** to use Mac OS X style fullsync instead of fsync().
1129 **
1130 ** Do not confuse the SQLCIPHER_SYNC_NORMAL and SQLCIPHER_SYNC_FULL flags
1131 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1132 ** settings.  The [synchronous pragma] determines when calls to the
1133 ** xSync VFS method occur and applies uniformly across all platforms.
1134 ** The SQLCIPHER_SYNC_NORMAL and SQLCIPHER_SYNC_FULL flags determine how
1135 ** energetic or rigorous or forceful the sync operations are and
1136 ** only make a difference on Mac OSX for the default SQLite code.
1137 ** (Third-party VFS implementations might also make the distinction
1138 ** between SQLCIPHER_SYNC_NORMAL and SQLCIPHER_SYNC_FULL, but among the
1139 ** operating systems natively supported by SQLite, only Mac OSX
1140 ** cares about the difference.)
1141 */
1142 #define SQLCIPHER_SYNC_NORMAL        0x00002
1143 #define SQLCIPHER_SYNC_FULL          0x00003
1144 #define SQLCIPHER_SYNC_DATAONLY      0x00010
1145
1146 /*
1147 ** CAPI3REF: OS Interface Open File Handle
1148 **
1149 ** An [sqlcipher3_file] object represents an open file in the 
1150 ** [sqlcipher3_vfs | OS interface layer].  Individual OS interface
1151 ** implementations will
1152 ** want to subclass this object by appending additional fields
1153 ** for their own use.  The pMethods entry is a pointer to an
1154 ** [sqlcipher3_io_methods] object that defines methods for performing
1155 ** I/O operations on the open file.
1156 */
1157 typedef struct sqlcipher3_file sqlcipher3_file;
1158 struct sqlcipher3_file {
1159   const struct sqlcipher3_io_methods *pMethods;  /* Methods for an open file */
1160 };
1161
1162 /*
1163 ** CAPI3REF: OS Interface File Virtual Methods Object
1164 **
1165 ** Every file opened by the [sqlcipher3_vfs.xOpen] method populates an
1166 ** [sqlcipher3_file] object (or, more commonly, a subclass of the
1167 ** [sqlcipher3_file] object) with a pointer to an instance of this object.
1168 ** This object defines the methods used to perform various operations
1169 ** against the open file represented by the [sqlcipher3_file] object.
1170 **
1171 ** If the [sqlcipher3_vfs.xOpen] method sets the sqlcipher3_file.pMethods element 
1172 ** to a non-NULL pointer, then the sqlcipher3_io_methods.xClose method
1173 ** may be invoked even if the [sqlcipher3_vfs.xOpen] reported that it failed.  The
1174 ** only way to prevent a call to xClose following a failed [sqlcipher3_vfs.xOpen]
1175 ** is for the [sqlcipher3_vfs.xOpen] to set the sqlcipher3_file.pMethods element
1176 ** to NULL.
1177 **
1178 ** The flags argument to xSync may be one of [SQLCIPHER_SYNC_NORMAL] or
1179 ** [SQLCIPHER_SYNC_FULL].  The first choice is the normal fsync().
1180 ** The second choice is a Mac OS X style fullsync.  The [SQLCIPHER_SYNC_DATAONLY]
1181 ** flag may be ORed in to indicate that only the data of the file
1182 ** and not its inode needs to be synced.
1183 **
1184 ** The integer values to xLock() and xUnlock() are one of
1185 ** <ul>
1186 ** <li> [SQLCIPHER_LOCK_NONE],
1187 ** <li> [SQLCIPHER_LOCK_SHARED],
1188 ** <li> [SQLCIPHER_LOCK_RESERVED],
1189 ** <li> [SQLCIPHER_LOCK_PENDING], or
1190 ** <li> [SQLCIPHER_LOCK_EXCLUSIVE].
1191 ** </ul>
1192 ** xLock() increases the lock. xUnlock() decreases the lock.
1193 ** The xCheckReservedLock() method checks whether any database connection,
1194 ** either in this process or in some other process, is holding a RESERVED,
1195 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1196 ** if such a lock exists and false otherwise.
1197 **
1198 ** The xFileControl() method is a generic interface that allows custom
1199 ** VFS implementations to directly control an open file using the
1200 ** [sqlcipher3_file_control()] interface.  The second "op" argument is an
1201 ** integer opcode.  The third argument is a generic pointer intended to
1202 ** point to a structure that may contain arguments or space in which to
1203 ** write return values.  Potential uses for xFileControl() might be
1204 ** functions to enable blocking locks with timeouts, to change the
1205 ** locking strategy (for example to use dot-file locks), to inquire
1206 ** about the status of a lock, or to break stale locks.  The SQLite
1207 ** core reserves all opcodes less than 100 for its own use.
1208 ** A [SQLCIPHER_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1209 ** Applications that define a custom xFileControl method should use opcodes
1210 ** greater than 100 to avoid conflicts.  VFS implementations should
1211 ** return [SQLCIPHER_NOTFOUND] for file control opcodes that they do not
1212 ** recognize.
1213 **
1214 ** The xSectorSize() method returns the sector size of the
1215 ** device that underlies the file.  The sector size is the
1216 ** minimum write that can be performed without disturbing
1217 ** other bytes in the file.  The xDeviceCharacteristics()
1218 ** method returns a bit vector describing behaviors of the
1219 ** underlying device:
1220 **
1221 ** <ul>
1222 ** <li> [SQLCIPHER_IOCAP_ATOMIC]
1223 ** <li> [SQLCIPHER_IOCAP_ATOMIC512]
1224 ** <li> [SQLCIPHER_IOCAP_ATOMIC1K]
1225 ** <li> [SQLCIPHER_IOCAP_ATOMIC2K]
1226 ** <li> [SQLCIPHER_IOCAP_ATOMIC4K]
1227 ** <li> [SQLCIPHER_IOCAP_ATOMIC8K]
1228 ** <li> [SQLCIPHER_IOCAP_ATOMIC16K]
1229 ** <li> [SQLCIPHER_IOCAP_ATOMIC32K]
1230 ** <li> [SQLCIPHER_IOCAP_ATOMIC64K]
1231 ** <li> [SQLCIPHER_IOCAP_SAFE_APPEND]
1232 ** <li> [SQLCIPHER_IOCAP_SEQUENTIAL]
1233 ** </ul>
1234 **
1235 ** The SQLCIPHER_IOCAP_ATOMIC property means that all writes of
1236 ** any size are atomic.  The SQLCIPHER_IOCAP_ATOMICnnn values
1237 ** mean that writes of blocks that are nnn bytes in size and
1238 ** are aligned to an address which is an integer multiple of
1239 ** nnn are atomic.  The SQLCIPHER_IOCAP_SAFE_APPEND value means
1240 ** that when data is appended to a file, the data is appended
1241 ** first then the size of the file is extended, never the other
1242 ** way around.  The SQLCIPHER_IOCAP_SEQUENTIAL property means that
1243 ** information is written to disk in the same order as calls
1244 ** to xWrite().
1245 **
1246 ** If xRead() returns SQLCIPHER_IOERR_SHORT_READ it must also fill
1247 ** in the unread portions of the buffer with zeros.  A VFS that
1248 ** fails to zero-fill short reads might seem to work.  However,
1249 ** failure to zero-fill short reads will eventually lead to
1250 ** database corruption.
1251 */
1252 typedef struct sqlcipher3_io_methods sqlcipher3_io_methods;
1253 struct sqlcipher3_io_methods {
1254   int iVersion;
1255   int (*xClose)(sqlcipher3_file*);
1256   int (*xRead)(sqlcipher3_file*, void*, int iAmt, sqlcipher3_int64 iOfst);
1257   int (*xWrite)(sqlcipher3_file*, const void*, int iAmt, sqlcipher3_int64 iOfst);
1258   int (*xTruncate)(sqlcipher3_file*, sqlcipher3_int64 size);
1259   int (*xSync)(sqlcipher3_file*, int flags);
1260   int (*xFileSize)(sqlcipher3_file*, sqlcipher3_int64 *pSize);
1261   int (*xLock)(sqlcipher3_file*, int);
1262   int (*xUnlock)(sqlcipher3_file*, int);
1263   int (*xCheckReservedLock)(sqlcipher3_file*, int *pResOut);
1264   int (*xFileControl)(sqlcipher3_file*, int op, void *pArg);
1265   int (*xSectorSize)(sqlcipher3_file*);
1266   int (*xDeviceCharacteristics)(sqlcipher3_file*);
1267   /* Methods above are valid for version 1 */
1268   int (*xShmMap)(sqlcipher3_file*, int iPg, int pgsz, int, void volatile**);
1269   int (*xShmLock)(sqlcipher3_file*, int offset, int n, int flags);
1270   void (*xShmBarrier)(sqlcipher3_file*);
1271   int (*xShmUnmap)(sqlcipher3_file*, int deleteFlag);
1272   /* Methods above are valid for version 2 */
1273   /* Additional methods may be added in future releases */
1274 };
1275
1276 /*
1277 ** CAPI3REF: Standard File Control Opcodes
1278 **
1279 ** These integer constants are opcodes for the xFileControl method
1280 ** of the [sqlcipher3_io_methods] object and for the [sqlcipher3_file_control()]
1281 ** interface.
1282 **
1283 ** The [SQLCIPHER_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1284 ** opcode causes the xFileControl method to write the current state of
1285 ** the lock (one of [SQLCIPHER_LOCK_NONE], [SQLCIPHER_LOCK_SHARED],
1286 ** [SQLCIPHER_LOCK_RESERVED], [SQLCIPHER_LOCK_PENDING], or [SQLCIPHER_LOCK_EXCLUSIVE])
1287 ** into an integer that the pArg argument points to. This capability
1288 ** is used during testing and only needs to be supported when SQLCIPHER_TEST
1289 ** is defined.
1290 **
1291 ** The [SQLCIPHER_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1292 ** layer a hint of how large the database file will grow to be during the
1293 ** current transaction.  This hint is not guaranteed to be accurate but it
1294 ** is often close.  The underlying VFS might choose to preallocate database
1295 ** file space based on this hint in order to help writes to the database
1296 ** file run faster.
1297 **
1298 ** The [SQLCIPHER_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1299 ** extends and truncates the database file in chunks of a size specified
1300 ** by the user. The fourth argument to [sqlcipher3_file_control()] should 
1301 ** point to an integer (type int) containing the new chunk-size to use
1302 ** for the nominated database. Allocating database file space in large
1303 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1304 ** improve performance on some systems.
1305 **
1306 ** The [SQLCIPHER_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1307 ** to the [sqlcipher3_file] object associated with a particular database
1308 ** connection.  See the [sqlcipher3_file_control()] documentation for
1309 ** additional information.
1310 **
1311 ** ^(The [SQLCIPHER_FCNTL_SYNC_OMITTED] opcode is generated internally by
1312 ** SQLite and sent to all VFSes in place of a call to the xSync method
1313 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1314 ** Some specialized VFSes need this signal in order to operate correctly
1315 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1316 ** VFSes do not need this signal and should silently ignore this opcode.
1317 ** Applications should not call [sqlcipher3_file_control()] with this
1318 ** opcode as doing so may disrupt the operation of the specialized VFSes
1319 ** that do require it.  
1320 **
1321 ** ^The [SQLCIPHER_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1322 ** retry counts and intervals for certain disk I/O operations for the
1323 ** windows [VFS] in order to work to provide robustness against
1324 ** anti-virus programs.  By default, the windows VFS will retry file read,
1325 ** file write, and file delete operations up to 10 times, with a delay
1326 ** of 25 milliseconds before the first retry and with the delay increasing
1327 ** by an additional 25 milliseconds with each subsequent retry.  This
1328 ** opcode allows those to values (10 retries and 25 milliseconds of delay)
1329 ** to be adjusted.  The values are changed for all database connections
1330 ** within the same process.  The argument is a pointer to an array of two
1331 ** integers where the first integer i the new retry count and the second
1332 ** integer is the delay.  If either integer is negative, then the setting
1333 ** is not changed but instead the prior value of that setting is written
1334 ** into the array entry, allowing the current retry settings to be
1335 ** interrogated.  The zDbName parameter is ignored.
1336 **
1337 ** ^The [SQLCIPHER_FCNTL_PERSIST_WAL] opcode is used to set or query the
1338 ** persistent [WAL | Write AHead Log] setting.  By default, the auxiliary
1339 ** write ahead log and shared memory files used for transaction control
1340 ** are automatically deleted when the latest connection to the database
1341 ** closes.  Setting persistent WAL mode causes those files to persist after
1342 ** close.  Persisting the files is useful when other processes that do not
1343 ** have write permission on the directory containing the database file want
1344 ** to read the database file, as the WAL and shared memory files must exist
1345 ** in order for the database to be readable.  The fourth parameter to
1346 ** [sqlcipher3_file_control()] for this opcode should be a pointer to an integer.
1347 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1348 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1349 ** WAL persistence setting.
1350 **
1351 ** ^The [SQLCIPHER_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1352 ** a write transaction to indicate that, unless it is rolled back for some
1353 ** reason, the entire database file will be overwritten by the current 
1354 ** transaction. This is used by VACUUM operations.
1355 */
1356 #define SQLCIPHER_FCNTL_LOCKSTATE        1
1357 #define SQLCIPHER_GET_LOCKPROXYFILE      2
1358 #define SQLCIPHER_SET_LOCKPROXYFILE      3
1359 #define SQLCIPHER_LAST_ERRNO             4
1360 #define SQLCIPHER_FCNTL_SIZE_HINT        5
1361 #define SQLCIPHER_FCNTL_CHUNK_SIZE       6
1362 #define SQLCIPHER_FCNTL_FILE_POINTER     7
1363 #define SQLCIPHER_FCNTL_SYNC_OMITTED     8
1364 #define SQLCIPHER_FCNTL_WIN32_AV_RETRY   9
1365 #define SQLCIPHER_FCNTL_PERSIST_WAL     10
1366 #define SQLCIPHER_FCNTL_OVERWRITE       11
1367
1368 /*
1369 ** CAPI3REF: Mutex Handle
1370 **
1371 ** The mutex module within SQLite defines [sqlcipher3_mutex] to be an
1372 ** abstract type for a mutex object.  The SQLite core never looks
1373 ** at the internal representation of an [sqlcipher3_mutex].  It only
1374 ** deals with pointers to the [sqlcipher3_mutex] object.
1375 **
1376 ** Mutexes are created using [sqlcipher3_mutex_alloc()].
1377 */
1378 typedef struct sqlcipher3_mutex sqlcipher3_mutex;
1379
1380 /*
1381 ** CAPI3REF: OS Interface Object
1382 **
1383 ** An instance of the sqlcipher3_vfs object defines the interface between
1384 ** the SQLite core and the underlying operating system.  The "vfs"
1385 ** in the name of the object stands for "virtual file system".  See
1386 ** the [VFS | VFS documentation] for further information.
1387 **
1388 ** The value of the iVersion field is initially 1 but may be larger in
1389 ** future versions of SQLite.  Additional fields may be appended to this
1390 ** object when the iVersion value is increased.  Note that the structure
1391 ** of the sqlcipher3_vfs object changes in the transaction between
1392 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1393 ** modified.
1394 **
1395 ** The szOsFile field is the size of the subclassed [sqlcipher3_file]
1396 ** structure used by this VFS.  mxPathname is the maximum length of
1397 ** a pathname in this VFS.
1398 **
1399 ** Registered sqlcipher3_vfs objects are kept on a linked list formed by
1400 ** the pNext pointer.  The [sqlcipher3_vfs_register()]
1401 ** and [sqlcipher3_vfs_unregister()] interfaces manage this list
1402 ** in a thread-safe way.  The [sqlcipher3_vfs_find()] interface
1403 ** searches the list.  Neither the application code nor the VFS
1404 ** implementation should use the pNext pointer.
1405 **
1406 ** The pNext field is the only field in the sqlcipher3_vfs
1407 ** structure that SQLite will ever modify.  SQLite will only access
1408 ** or modify this field while holding a particular static mutex.
1409 ** The application should never modify anything within the sqlcipher3_vfs
1410 ** object once the object has been registered.
1411 **
1412 ** The zName field holds the name of the VFS module.  The name must
1413 ** be unique across all VFS modules.
1414 **
1415 ** [[sqlcipher3_vfs.xOpen]]
1416 ** ^SQLite guarantees that the zFilename parameter to xOpen
1417 ** is either a NULL pointer or string obtained
1418 ** from xFullPathname() with an optional suffix added.
1419 ** ^If a suffix is added to the zFilename parameter, it will
1420 ** consist of a single "-" character followed by no more than
1421 ** 10 alphanumeric and/or "-" characters.
1422 ** ^SQLite further guarantees that
1423 ** the string will be valid and unchanged until xClose() is
1424 ** called. Because of the previous sentence,
1425 ** the [sqlcipher3_file] can safely store a pointer to the
1426 ** filename if it needs to remember the filename for some reason.
1427 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1428 ** must invent its own temporary name for the file.  ^Whenever the 
1429 ** xFilename parameter is NULL it will also be the case that the
1430 ** flags parameter will include [SQLCIPHER_OPEN_DELETEONCLOSE].
1431 **
1432 ** The flags argument to xOpen() includes all bits set in
1433 ** the flags argument to [sqlcipher3_open_v2()].  Or if [sqlcipher3_open()]
1434 ** or [sqlcipher3_open16()] is used, then flags includes at least
1435 ** [SQLCIPHER_OPEN_READWRITE] | [SQLCIPHER_OPEN_CREATE]. 
1436 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1437 ** include [SQLCIPHER_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1438 **
1439 ** ^(SQLite will also add one of the following flags to the xOpen()
1440 ** call, depending on the object being opened:
1441 **
1442 ** <ul>
1443 ** <li>  [SQLCIPHER_OPEN_MAIN_DB]
1444 ** <li>  [SQLCIPHER_OPEN_MAIN_JOURNAL]
1445 ** <li>  [SQLCIPHER_OPEN_TEMP_DB]
1446 ** <li>  [SQLCIPHER_OPEN_TEMP_JOURNAL]
1447 ** <li>  [SQLCIPHER_OPEN_TRANSIENT_DB]
1448 ** <li>  [SQLCIPHER_OPEN_SUBJOURNAL]
1449 ** <li>  [SQLCIPHER_OPEN_MASTER_JOURNAL]
1450 ** <li>  [SQLCIPHER_OPEN_WAL]
1451 ** </ul>)^
1452 **
1453 ** The file I/O implementation can use the object type flags to
1454 ** change the way it deals with files.  For example, an application
1455 ** that does not care about crash recovery or rollback might make
1456 ** the open of a journal file a no-op.  Writes to this journal would
1457 ** also be no-ops, and any attempt to read the journal would return
1458 ** SQLCIPHER_IOERR.  Or the implementation might recognize that a database
1459 ** file will be doing page-aligned sector reads and writes in a random
1460 ** order and set up its I/O subsystem accordingly.
1461 **
1462 ** SQLite might also add one of the following flags to the xOpen method:
1463 **
1464 ** <ul>
1465 ** <li> [SQLCIPHER_OPEN_DELETEONCLOSE]
1466 ** <li> [SQLCIPHER_OPEN_EXCLUSIVE]
1467 ** </ul>
1468 **
1469 ** The [SQLCIPHER_OPEN_DELETEONCLOSE] flag means the file should be
1470 ** deleted when it is closed.  ^The [SQLCIPHER_OPEN_DELETEONCLOSE]
1471 ** will be set for TEMP databases and their journals, transient
1472 ** databases, and subjournals.
1473 **
1474 ** ^The [SQLCIPHER_OPEN_EXCLUSIVE] flag is always used in conjunction
1475 ** with the [SQLCIPHER_OPEN_CREATE] flag, which are both directly
1476 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1477 ** API.  The SQLCIPHER_OPEN_EXCLUSIVE flag, when paired with the 
1478 ** SQLCIPHER_OPEN_CREATE, is used to indicate that file should always
1479 ** be created, and that it is an error if it already exists.
1480 ** It is <i>not</i> used to indicate the file should be opened 
1481 ** for exclusive access.
1482 **
1483 ** ^At least szOsFile bytes of memory are allocated by SQLite
1484 ** to hold the  [sqlcipher3_file] structure passed as the third
1485 ** argument to xOpen.  The xOpen method does not have to
1486 ** allocate the structure; it should just fill it in.  Note that
1487 ** the xOpen method must set the sqlcipher3_file.pMethods to either
1488 ** a valid [sqlcipher3_io_methods] object or to NULL.  xOpen must do
1489 ** this even if the open fails.  SQLite expects that the sqlcipher3_file.pMethods
1490 ** element will be valid after xOpen returns regardless of the success
1491 ** or failure of the xOpen call.
1492 **
1493 ** [[sqlcipher3_vfs.xAccess]]
1494 ** ^The flags argument to xAccess() may be [SQLCIPHER_ACCESS_EXISTS]
1495 ** to test for the existence of a file, or [SQLCIPHER_ACCESS_READWRITE] to
1496 ** test whether a file is readable and writable, or [SQLCIPHER_ACCESS_READ]
1497 ** to test whether a file is at least readable.   The file can be a
1498 ** directory.
1499 **
1500 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1501 ** output buffer xFullPathname.  The exact size of the output buffer
1502 ** is also passed as a parameter to both  methods. If the output buffer
1503 ** is not large enough, [SQLCIPHER_CANTOPEN] should be returned. Since this is
1504 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1505 ** to prevent this by setting mxPathname to a sufficiently large value.
1506 **
1507 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1508 ** interfaces are not strictly a part of the filesystem, but they are
1509 ** included in the VFS structure for completeness.
1510 ** The xRandomness() function attempts to return nBytes bytes
1511 ** of good-quality randomness into zOut.  The return value is
1512 ** the actual number of bytes of randomness obtained.
1513 ** The xSleep() method causes the calling thread to sleep for at
1514 ** least the number of microseconds given.  ^The xCurrentTime()
1515 ** method returns a Julian Day Number for the current date and time as
1516 ** a floating point value.
1517 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1518 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1519 ** a 24-hour day).  
1520 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1521 ** date and time if that method is available (if iVersion is 2 or 
1522 ** greater and the function pointer is not NULL) and will fall back
1523 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1524 **
1525 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1526 ** are not used by the SQLite core.  These optional interfaces are provided
1527 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1528 ** system calls with functions under its control, a test program can
1529 ** simulate faults and error conditions that would otherwise be difficult
1530 ** or impossible to induce.  The set of system calls that can be overridden
1531 ** varies from one VFS to another, and from one version of the same VFS to the
1532 ** next.  Applications that use these interfaces must be prepared for any
1533 ** or all of these interfaces to be NULL or for their behavior to change
1534 ** from one release to the next.  Applications must not attempt to access
1535 ** any of these methods if the iVersion of the VFS is less than 3.
1536 */
1537 typedef struct sqlcipher3_vfs sqlcipher3_vfs;
1538 typedef void (*sqlcipher3_syscall_ptr)(void);
1539 struct sqlcipher3_vfs {
1540   int iVersion;            /* Structure version number (currently 3) */
1541   int szOsFile;            /* Size of subclassed sqlcipher3_file */
1542   int mxPathname;          /* Maximum file pathname length */
1543   sqlcipher3_vfs *pNext;      /* Next registered VFS */
1544   const char *zName;       /* Name of this virtual file system */
1545   void *pAppData;          /* Pointer to application-specific data */
1546   int (*xOpen)(sqlcipher3_vfs*, const char *zName, sqlcipher3_file*,
1547                int flags, int *pOutFlags);
1548   int (*xDelete)(sqlcipher3_vfs*, const char *zName, int syncDir);
1549   int (*xAccess)(sqlcipher3_vfs*, const char *zName, int flags, int *pResOut);
1550   int (*xFullPathname)(sqlcipher3_vfs*, const char *zName, int nOut, char *zOut);
1551   void *(*xDlOpen)(sqlcipher3_vfs*, const char *zFilename);
1552   void (*xDlError)(sqlcipher3_vfs*, int nByte, char *zErrMsg);
1553   void (*(*xDlSym)(sqlcipher3_vfs*,void*, const char *zSymbol))(void);
1554   void (*xDlClose)(sqlcipher3_vfs*, void*);
1555   int (*xRandomness)(sqlcipher3_vfs*, int nByte, char *zOut);
1556   int (*xSleep)(sqlcipher3_vfs*, int microseconds);
1557   int (*xCurrentTime)(sqlcipher3_vfs*, double*);
1558   int (*xGetLastError)(sqlcipher3_vfs*, int, char *);
1559   /*
1560   ** The methods above are in version 1 of the sqlcipher_vfs object
1561   ** definition.  Those that follow are added in version 2 or later
1562   */
1563   int (*xCurrentTimeInt64)(sqlcipher3_vfs*, sqlcipher3_int64*);
1564   /*
1565   ** The methods above are in versions 1 and 2 of the sqlcipher_vfs object.
1566   ** Those below are for version 3 and greater.
1567   */
1568   int (*xSetSystemCall)(sqlcipher3_vfs*, const char *zName, sqlcipher3_syscall_ptr);
1569   sqlcipher3_syscall_ptr (*xGetSystemCall)(sqlcipher3_vfs*, const char *zName);
1570   const char *(*xNextSystemCall)(sqlcipher3_vfs*, const char *zName);
1571   /*
1572   ** The methods above are in versions 1 through 3 of the sqlcipher_vfs object.
1573   ** New fields may be appended in figure versions.  The iVersion
1574   ** value will increment whenever this happens. 
1575   */
1576 };
1577
1578 /*
1579 ** CAPI3REF: Flags for the xAccess VFS method
1580 **
1581 ** These integer constants can be used as the third parameter to
1582 ** the xAccess method of an [sqlcipher3_vfs] object.  They determine
1583 ** what kind of permissions the xAccess method is looking for.
1584 ** With SQLCIPHER_ACCESS_EXISTS, the xAccess method
1585 ** simply checks whether the file exists.
1586 ** With SQLCIPHER_ACCESS_READWRITE, the xAccess method
1587 ** checks whether the named directory is both readable and writable
1588 ** (in other words, if files can be added, removed, and renamed within
1589 ** the directory).
1590 ** The SQLCIPHER_ACCESS_READWRITE constant is currently used only by the
1591 ** [temp_store_directory pragma], though this could change in a future
1592 ** release of SQLite.
1593 ** With SQLCIPHER_ACCESS_READ, the xAccess method
1594 ** checks whether the file is readable.  The SQLCIPHER_ACCESS_READ constant is
1595 ** currently unused, though it might be used in a future release of
1596 ** SQLite.
1597 */
1598 #define SQLCIPHER_ACCESS_EXISTS    0
1599 #define SQLCIPHER_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1600 #define SQLCIPHER_ACCESS_READ      2   /* Unused */
1601
1602 /*
1603 ** CAPI3REF: Flags for the xShmLock VFS method
1604 **
1605 ** These integer constants define the various locking operations
1606 ** allowed by the xShmLock method of [sqlcipher3_io_methods].  The
1607 ** following are the only legal combinations of flags to the
1608 ** xShmLock method:
1609 **
1610 ** <ul>
1611 ** <li>  SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED
1612 ** <li>  SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE
1613 ** <li>  SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED
1614 ** <li>  SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE
1615 ** </ul>
1616 **
1617 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1618 ** was given no the corresponding lock.  
1619 **
1620 ** The xShmLock method can transition between unlocked and SHARED or
1621 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1622 ** and EXCLUSIVE.
1623 */
1624 #define SQLCIPHER_SHM_UNLOCK       1
1625 #define SQLCIPHER_SHM_LOCK         2
1626 #define SQLCIPHER_SHM_SHARED       4
1627 #define SQLCIPHER_SHM_EXCLUSIVE    8
1628
1629 /*
1630 ** CAPI3REF: Maximum xShmLock index
1631 **
1632 ** The xShmLock method on [sqlcipher3_io_methods] may use values
1633 ** between 0 and this upper bound as its "offset" argument.
1634 ** The SQLite core will never attempt to acquire or release a
1635 ** lock outside of this range
1636 */
1637 #define SQLCIPHER_SHM_NLOCK        8
1638
1639
1640 /*
1641 ** CAPI3REF: Initialize The SQLite Library
1642 **
1643 ** ^The sqlcipher3_initialize() routine initializes the
1644 ** SQLite library.  ^The sqlcipher3_shutdown() routine
1645 ** deallocates any resources that were allocated by sqlcipher3_initialize().
1646 ** These routines are designed to aid in process initialization and
1647 ** shutdown on embedded systems.  Workstation applications using
1648 ** SQLite normally do not need to invoke either of these routines.
1649 **
1650 ** A call to sqlcipher3_initialize() is an "effective" call if it is
1651 ** the first time sqlcipher3_initialize() is invoked during the lifetime of
1652 ** the process, or if it is the first time sqlcipher3_initialize() is invoked
1653 ** following a call to sqlcipher3_shutdown().  ^(Only an effective call
1654 ** of sqlcipher3_initialize() does any initialization.  All other calls
1655 ** are harmless no-ops.)^
1656 **
1657 ** A call to sqlcipher3_shutdown() is an "effective" call if it is the first
1658 ** call to sqlcipher3_shutdown() since the last sqlcipher3_initialize().  ^(Only
1659 ** an effective call to sqlcipher3_shutdown() does any deinitialization.
1660 ** All other valid calls to sqlcipher3_shutdown() are harmless no-ops.)^
1661 **
1662 ** The sqlcipher3_initialize() interface is threadsafe, but sqlcipher3_shutdown()
1663 ** is not.  The sqlcipher3_shutdown() interface must only be called from a
1664 ** single thread.  All open [database connections] must be closed and all
1665 ** other SQLite resources must be deallocated prior to invoking
1666 ** sqlcipher3_shutdown().
1667 **
1668 ** Among other things, ^sqlcipher3_initialize() will invoke
1669 ** sqlcipher3_os_init().  Similarly, ^sqlcipher3_shutdown()
1670 ** will invoke sqlcipher3_os_end().
1671 **
1672 ** ^The sqlcipher3_initialize() routine returns [SQLCIPHER_OK] on success.
1673 ** ^If for some reason, sqlcipher3_initialize() is unable to initialize
1674 ** the library (perhaps it is unable to allocate a needed resource such
1675 ** as a mutex) it returns an [error code] other than [SQLCIPHER_OK].
1676 **
1677 ** ^The sqlcipher3_initialize() routine is called internally by many other
1678 ** SQLite interfaces so that an application usually does not need to
1679 ** invoke sqlcipher3_initialize() directly.  For example, [sqlcipher3_open()]
1680 ** calls sqlcipher3_initialize() so the SQLite library will be automatically
1681 ** initialized when [sqlcipher3_open()] is called if it has not be initialized
1682 ** already.  ^However, if SQLite is compiled with the [SQLCIPHER_OMIT_AUTOINIT]
1683 ** compile-time option, then the automatic calls to sqlcipher3_initialize()
1684 ** are omitted and the application must call sqlcipher3_initialize() directly
1685 ** prior to using any other SQLite interface.  For maximum portability,
1686 ** it is recommended that applications always invoke sqlcipher3_initialize()
1687 ** directly prior to using any other SQLite interface.  Future releases
1688 ** of SQLite may require this.  In other words, the behavior exhibited
1689 ** when SQLite is compiled with [SQLCIPHER_OMIT_AUTOINIT] might become the
1690 ** default behavior in some future release of SQLite.
1691 **
1692 ** The sqlcipher3_os_init() routine does operating-system specific
1693 ** initialization of the SQLite library.  The sqlcipher3_os_end()
1694 ** routine undoes the effect of sqlcipher3_os_init().  Typical tasks
1695 ** performed by these routines include allocation or deallocation
1696 ** of static resources, initialization of global variables,
1697 ** setting up a default [sqlcipher3_vfs] module, or setting up
1698 ** a default configuration using [sqlcipher3_config()].
1699 **
1700 ** The application should never invoke either sqlcipher3_os_init()
1701 ** or sqlcipher3_os_end() directly.  The application should only invoke
1702 ** sqlcipher3_initialize() and sqlcipher3_shutdown().  The sqlcipher3_os_init()
1703 ** interface is called automatically by sqlcipher3_initialize() and
1704 ** sqlcipher3_os_end() is called by sqlcipher3_shutdown().  Appropriate
1705 ** implementations for sqlcipher3_os_init() and sqlcipher3_os_end()
1706 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1707 ** When [custom builds | built for other platforms]
1708 ** (using the [SQLCIPHER_OS_OTHER=1] compile-time
1709 ** option) the application must supply a suitable implementation for
1710 ** sqlcipher3_os_init() and sqlcipher3_os_end().  An application-supplied
1711 ** implementation of sqlcipher3_os_init() or sqlcipher3_os_end()
1712 ** must return [SQLCIPHER_OK] on success and some other [error code] upon
1713 ** failure.
1714 */
1715 SQLCIPHER_API int sqlcipher3_initialize(void);
1716 SQLCIPHER_API int sqlcipher3_shutdown(void);
1717 SQLCIPHER_API int sqlcipher3_os_init(void);
1718 SQLCIPHER_API int sqlcipher3_os_end(void);
1719
1720 /*
1721 ** CAPI3REF: Configuring The SQLite Library
1722 **
1723 ** The sqlcipher3_config() interface is used to make global configuration
1724 ** changes to SQLite in order to tune SQLite to the specific needs of
1725 ** the application.  The default configuration is recommended for most
1726 ** applications and so this routine is usually not necessary.  It is
1727 ** provided to support rare applications with unusual needs.
1728 **
1729 ** The sqlcipher3_config() interface is not threadsafe.  The application
1730 ** must insure that no other SQLite interfaces are invoked by other
1731 ** threads while sqlcipher3_config() is running.  Furthermore, sqlcipher3_config()
1732 ** may only be invoked prior to library initialization using
1733 ** [sqlcipher3_initialize()] or after shutdown by [sqlcipher3_shutdown()].
1734 ** ^If sqlcipher3_config() is called after [sqlcipher3_initialize()] and before
1735 ** [sqlcipher3_shutdown()] then it will return SQLCIPHER_MISUSE.
1736 ** Note, however, that ^sqlcipher3_config() can be called as part of the
1737 ** implementation of an application-defined [sqlcipher3_os_init()].
1738 **
1739 ** The first argument to sqlcipher3_config() is an integer
1740 ** [configuration option] that determines
1741 ** what property of SQLite is to be configured.  Subsequent arguments
1742 ** vary depending on the [configuration option]
1743 ** in the first argument.
1744 **
1745 ** ^When a configuration option is set, sqlcipher3_config() returns [SQLCIPHER_OK].
1746 ** ^If the option is unknown or SQLite is unable to set the option
1747 ** then this routine returns a non-zero [error code].
1748 */
1749 SQLCIPHER_API int sqlcipher3_config(int, ...);
1750
1751 /*
1752 ** CAPI3REF: Configure database connections
1753 **
1754 ** The sqlcipher3_db_config() interface is used to make configuration
1755 ** changes to a [database connection].  The interface is similar to
1756 ** [sqlcipher3_config()] except that the changes apply to a single
1757 ** [database connection] (specified in the first argument).
1758 **
1759 ** The second argument to sqlcipher3_db_config(D,V,...)  is the
1760 ** [SQLCIPHER_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1761 ** that indicates what aspect of the [database connection] is being configured.
1762 ** Subsequent arguments vary depending on the configuration verb.
1763 **
1764 ** ^Calls to sqlcipher3_db_config() return SQLCIPHER_OK if and only if
1765 ** the call is considered successful.
1766 */
1767 SQLCIPHER_API int sqlcipher3_db_config(sqlcipher3*, int op, ...);
1768
1769 /*
1770 ** CAPI3REF: Memory Allocation Routines
1771 **
1772 ** An instance of this object defines the interface between SQLite
1773 ** and low-level memory allocation routines.
1774 **
1775 ** This object is used in only one place in the SQLite interface.
1776 ** A pointer to an instance of this object is the argument to
1777 ** [sqlcipher3_config()] when the configuration option is
1778 ** [SQLCIPHER_CONFIG_MALLOC] or [SQLCIPHER_CONFIG_GETMALLOC].  
1779 ** By creating an instance of this object
1780 ** and passing it to [sqlcipher3_config]([SQLCIPHER_CONFIG_MALLOC])
1781 ** during configuration, an application can specify an alternative
1782 ** memory allocation subsystem for SQLite to use for all of its
1783 ** dynamic memory needs.
1784 **
1785 ** Note that SQLite comes with several [built-in memory allocators]
1786 ** that are perfectly adequate for the overwhelming majority of applications
1787 ** and that this object is only useful to a tiny minority of applications
1788 ** with specialized memory allocation requirements.  This object is
1789 ** also used during testing of SQLite in order to specify an alternative
1790 ** memory allocator that simulates memory out-of-memory conditions in
1791 ** order to verify that SQLite recovers gracefully from such
1792 ** conditions.
1793 **
1794 ** The xMalloc, xRealloc, and xFree methods must work like the
1795 ** malloc(), realloc() and free() functions from the standard C library.
1796 ** ^SQLite guarantees that the second argument to
1797 ** xRealloc is always a value returned by a prior call to xRoundup.
1798 **
1799 ** xSize should return the allocated size of a memory allocation
1800 ** previously obtained from xMalloc or xRealloc.  The allocated size
1801 ** is always at least as big as the requested size but may be larger.
1802 **
1803 ** The xRoundup method returns what would be the allocated size of
1804 ** a memory allocation given a particular requested size.  Most memory
1805 ** allocators round up memory allocations at least to the next multiple
1806 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1807 ** Every memory allocation request coming in through [sqlcipher3_malloc()]
1808 ** or [sqlcipher3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1809 ** that causes the corresponding memory allocation to fail.
1810 **
1811 ** The xInit method initializes the memory allocator.  (For example,
1812 ** it might allocate any require mutexes or initialize internal data
1813 ** structures.  The xShutdown method is invoked (indirectly) by
1814 ** [sqlcipher3_shutdown()] and should deallocate any resources acquired
1815 ** by xInit.  The pAppData pointer is used as the only parameter to
1816 ** xInit and xShutdown.
1817 **
1818 ** SQLite holds the [SQLCIPHER_MUTEX_STATIC_MASTER] mutex when it invokes
1819 ** the xInit method, so the xInit method need not be threadsafe.  The
1820 ** xShutdown method is only called from [sqlcipher3_shutdown()] so it does
1821 ** not need to be threadsafe either.  For all other methods, SQLite
1822 ** holds the [SQLCIPHER_MUTEX_STATIC_MEM] mutex as long as the
1823 ** [SQLCIPHER_CONFIG_MEMSTATUS] configuration option is turned on (which
1824 ** it is by default) and so the methods are automatically serialized.
1825 ** However, if [SQLCIPHER_CONFIG_MEMSTATUS] is disabled, then the other
1826 ** methods must be threadsafe or else make their own arrangements for
1827 ** serialization.
1828 **
1829 ** SQLite will never invoke xInit() more than once without an intervening
1830 ** call to xShutdown().
1831 */
1832 typedef struct sqlcipher3_mem_methods sqlcipher3_mem_methods;
1833 struct sqlcipher3_mem_methods {
1834   void *(*xMalloc)(int);         /* Memory allocation function */
1835   void (*xFree)(void*);          /* Free a prior allocation */
1836   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1837   int (*xSize)(void*);           /* Return the size of an allocation */
1838   int (*xRoundup)(int);          /* Round up request size to allocation size */
1839   int (*xInit)(void*);           /* Initialize the memory allocator */
1840   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1841   void *pAppData;                /* Argument to xInit() and xShutdown() */
1842 };
1843
1844 /*
1845 ** CAPI3REF: Configuration Options
1846 ** KEYWORDS: {configuration option}
1847 **
1848 ** These constants are the available integer configuration options that
1849 ** can be passed as the first argument to the [sqlcipher3_config()] interface.
1850 **
1851 ** New configuration options may be added in future releases of SQLite.
1852 ** Existing configuration options might be discontinued.  Applications
1853 ** should check the return code from [sqlcipher3_config()] to make sure that
1854 ** the call worked.  The [sqlcipher3_config()] interface will return a
1855 ** non-zero [error code] if a discontinued or unsupported configuration option
1856 ** is invoked.
1857 **
1858 ** <dl>
1859 ** [[SQLCIPHER_CONFIG_SINGLETHREAD]] <dt>SQLCIPHER_CONFIG_SINGLETHREAD</dt>
1860 ** <dd>There are no arguments to this option.  ^This option sets the
1861 ** [threading mode] to Single-thread.  In other words, it disables
1862 ** all mutexing and puts SQLite into a mode where it can only be used
1863 ** by a single thread.   ^If SQLite is compiled with
1864 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1865 ** it is not possible to change the [threading mode] from its default
1866 ** value of Single-thread and so [sqlcipher3_config()] will return 
1867 ** [SQLCIPHER_ERROR] if called with the SQLCIPHER_CONFIG_SINGLETHREAD
1868 ** configuration option.</dd>
1869 **
1870 ** [[SQLCIPHER_CONFIG_MULTITHREAD]] <dt>SQLCIPHER_CONFIG_MULTITHREAD</dt>
1871 ** <dd>There are no arguments to this option.  ^This option sets the
1872 ** [threading mode] to Multi-thread.  In other words, it disables
1873 ** mutexing on [database connection] and [prepared statement] objects.
1874 ** The application is responsible for serializing access to
1875 ** [database connections] and [prepared statements].  But other mutexes
1876 ** are enabled so that SQLite will be safe to use in a multi-threaded
1877 ** environment as long as no two threads attempt to use the same
1878 ** [database connection] at the same time.  ^If SQLite is compiled with
1879 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1880 ** it is not possible to set the Multi-thread [threading mode] and
1881 ** [sqlcipher3_config()] will return [SQLCIPHER_ERROR] if called with the
1882 ** SQLCIPHER_CONFIG_MULTITHREAD configuration option.</dd>
1883 **
1884 ** [[SQLCIPHER_CONFIG_SERIALIZED]] <dt>SQLCIPHER_CONFIG_SERIALIZED</dt>
1885 ** <dd>There are no arguments to this option.  ^This option sets the
1886 ** [threading mode] to Serialized. In other words, this option enables
1887 ** all mutexes including the recursive
1888 ** mutexes on [database connection] and [prepared statement] objects.
1889 ** In this mode (which is the default when SQLite is compiled with
1890 ** [SQLCIPHER_THREADSAFE=1]) the SQLite library will itself serialize access
1891 ** to [database connections] and [prepared statements] so that the
1892 ** application is free to use the same [database connection] or the
1893 ** same [prepared statement] in different threads at the same time.
1894 ** ^If SQLite is compiled with
1895 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1896 ** it is not possible to set the Serialized [threading mode] and
1897 ** [sqlcipher3_config()] will return [SQLCIPHER_ERROR] if called with the
1898 ** SQLCIPHER_CONFIG_SERIALIZED configuration option.</dd>
1899 **
1900 ** [[SQLCIPHER_CONFIG_MALLOC]] <dt>SQLCIPHER_CONFIG_MALLOC</dt>
1901 ** <dd> ^(This option takes a single argument which is a pointer to an
1902 ** instance of the [sqlcipher3_mem_methods] structure.  The argument specifies
1903 ** alternative low-level memory allocation routines to be used in place of
1904 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1905 ** its own private copy of the content of the [sqlcipher3_mem_methods] structure
1906 ** before the [sqlcipher3_config()] call returns.</dd>
1907 **
1908 ** [[SQLCIPHER_CONFIG_GETMALLOC]] <dt>SQLCIPHER_CONFIG_GETMALLOC</dt>
1909 ** <dd> ^(This option takes a single argument which is a pointer to an
1910 ** instance of the [sqlcipher3_mem_methods] structure.  The [sqlcipher3_mem_methods]
1911 ** structure is filled with the currently defined memory allocation routines.)^
1912 ** This option can be used to overload the default memory allocation
1913 ** routines with a wrapper that simulations memory allocation failure or
1914 ** tracks memory usage, for example. </dd>
1915 **
1916 ** [[SQLCIPHER_CONFIG_MEMSTATUS]] <dt>SQLCIPHER_CONFIG_MEMSTATUS</dt>
1917 ** <dd> ^This option takes single argument of type int, interpreted as a 
1918 ** boolean, which enables or disables the collection of memory allocation 
1919 ** statistics. ^(When memory allocation statistics are disabled, the 
1920 ** following SQLite interfaces become non-operational:
1921 **   <ul>
1922 **   <li> [sqlcipher3_memory_used()]
1923 **   <li> [sqlcipher3_memory_highwater()]
1924 **   <li> [sqlcipher3_soft_heap_limit64()]
1925 **   <li> [sqlcipher3_status()]
1926 **   </ul>)^
1927 ** ^Memory allocation statistics are enabled by default unless SQLite is
1928 ** compiled with [SQLCIPHER_DEFAULT_MEMSTATUS]=0 in which case memory
1929 ** allocation statistics are disabled by default.
1930 ** </dd>
1931 **
1932 ** [[SQLCIPHER_CONFIG_SCRATCH]] <dt>SQLCIPHER_CONFIG_SCRATCH</dt>
1933 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1934 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1935 ** aligned memory buffer from which the scratch allocations will be
1936 ** drawn, the size of each scratch allocation (sz),
1937 ** and the maximum number of scratch allocations (N).  The sz
1938 ** argument must be a multiple of 16.
1939 ** The first argument must be a pointer to an 8-byte aligned buffer
1940 ** of at least sz*N bytes of memory.
1941 ** ^SQLite will use no more than two scratch buffers per thread.  So
1942 ** N should be set to twice the expected maximum number of threads.
1943 ** ^SQLite will never require a scratch buffer that is more than 6
1944 ** times the database page size. ^If SQLite needs needs additional
1945 ** scratch memory beyond what is provided by this configuration option, then 
1946 ** [sqlcipher3_malloc()] will be used to obtain the memory needed.</dd>
1947 **
1948 ** [[SQLCIPHER_CONFIG_PAGECACHE]] <dt>SQLCIPHER_CONFIG_PAGECACHE</dt>
1949 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1950 ** the database page cache with the default page cache implementation.  
1951 ** This configuration should not be used if an application-define page
1952 ** cache implementation is loaded using the SQLCIPHER_CONFIG_PCACHE option.
1953 ** There are three arguments to this option: A pointer to 8-byte aligned
1954 ** memory, the size of each page buffer (sz), and the number of pages (N).
1955 ** The sz argument should be the size of the largest database page
1956 ** (a power of two between 512 and 32768) plus a little extra for each
1957 ** page header.  ^The page header size is 20 to 40 bytes depending on
1958 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1959 ** to make sz a little too large.  The first
1960 ** argument should point to an allocation of at least sz*N bytes of memory.
1961 ** ^SQLite will use the memory provided by the first argument to satisfy its
1962 ** memory needs for the first N pages that it adds to cache.  ^If additional
1963 ** page cache memory is needed beyond what is provided by this option, then
1964 ** SQLite goes to [sqlcipher3_malloc()] for the additional storage space.
1965 ** The pointer in the first argument must
1966 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1967 ** will be undefined.</dd>
1968 **
1969 ** [[SQLCIPHER_CONFIG_HEAP]] <dt>SQLCIPHER_CONFIG_HEAP</dt>
1970 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1971 ** for all of its dynamic memory allocation needs beyond those provided
1972 ** for by [SQLCIPHER_CONFIG_SCRATCH] and [SQLCIPHER_CONFIG_PAGECACHE].
1973 ** There are three arguments: An 8-byte aligned pointer to the memory,
1974 ** the number of bytes in the memory buffer, and the minimum allocation size.
1975 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1976 ** to using its default memory allocator (the system malloc() implementation),
1977 ** undoing any prior invocation of [SQLCIPHER_CONFIG_MALLOC].  ^If the
1978 ** memory pointer is not NULL and either [SQLCIPHER_ENABLE_MEMSYS3] or
1979 ** [SQLCIPHER_ENABLE_MEMSYS5] are defined, then the alternative memory
1980 ** allocator is engaged to handle all of SQLites memory allocation needs.
1981 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1982 ** boundary or subsequent behavior of SQLite will be undefined.
1983 ** The minimum allocation size is capped at 2**12. Reasonable values
1984 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1985 **
1986 ** [[SQLCIPHER_CONFIG_MUTEX]] <dt>SQLCIPHER_CONFIG_MUTEX</dt>
1987 ** <dd> ^(This option takes a single argument which is a pointer to an
1988 ** instance of the [sqlcipher3_mutex_methods] structure.  The argument specifies
1989 ** alternative low-level mutex routines to be used in place
1990 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1991 ** content of the [sqlcipher3_mutex_methods] structure before the call to
1992 ** [sqlcipher3_config()] returns. ^If SQLite is compiled with
1993 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
1994 ** the entire mutexing subsystem is omitted from the build and hence calls to
1995 ** [sqlcipher3_config()] with the SQLCIPHER_CONFIG_MUTEX configuration option will
1996 ** return [SQLCIPHER_ERROR].</dd>
1997 **
1998 ** [[SQLCIPHER_CONFIG_GETMUTEX]] <dt>SQLCIPHER_CONFIG_GETMUTEX</dt>
1999 ** <dd> ^(This option takes a single argument which is a pointer to an
2000 ** instance of the [sqlcipher3_mutex_methods] structure.  The
2001 ** [sqlcipher3_mutex_methods]
2002 ** structure is filled with the currently defined mutex routines.)^
2003 ** This option can be used to overload the default mutex allocation
2004 ** routines with a wrapper used to track mutex usage for performance
2005 ** profiling or testing, for example.   ^If SQLite is compiled with
2006 ** the [SQLCIPHER_THREADSAFE | SQLCIPHER_THREADSAFE=0] compile-time option then
2007 ** the entire mutexing subsystem is omitted from the build and hence calls to
2008 ** [sqlcipher3_config()] with the SQLCIPHER_CONFIG_GETMUTEX configuration option will
2009 ** return [SQLCIPHER_ERROR].</dd>
2010 **
2011 ** [[SQLCIPHER_CONFIG_LOOKASIDE]] <dt>SQLCIPHER_CONFIG_LOOKASIDE</dt>
2012 ** <dd> ^(This option takes two arguments that determine the default
2013 ** memory allocation for the lookaside memory allocator on each
2014 ** [database connection].  The first argument is the
2015 ** size of each lookaside buffer slot and the second is the number of
2016 ** slots allocated to each database connection.)^  ^(This option sets the
2017 ** <i>default</i> lookaside size. The [SQLCIPHER_DBCONFIG_LOOKASIDE]
2018 ** verb to [sqlcipher3_db_config()] can be used to change the lookaside
2019 ** configuration on individual connections.)^ </dd>
2020 **
2021 ** [[SQLCIPHER_CONFIG_PCACHE]] <dt>SQLCIPHER_CONFIG_PCACHE</dt>
2022 ** <dd> ^(This option takes a single argument which is a pointer to
2023 ** an [sqlcipher3_pcache_methods] object.  This object specifies the interface
2024 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2025 ** object and uses it for page cache memory allocations.</dd>
2026 **
2027 ** [[SQLCIPHER_CONFIG_GETPCACHE]] <dt>SQLCIPHER_CONFIG_GETPCACHE</dt>
2028 ** <dd> ^(This option takes a single argument which is a pointer to an
2029 ** [sqlcipher3_pcache_methods] object.  SQLite copies of the current
2030 ** page cache implementation into that object.)^ </dd>
2031 **
2032 ** [[SQLCIPHER_CONFIG_LOG]] <dt>SQLCIPHER_CONFIG_LOG</dt>
2033 ** <dd> ^The SQLCIPHER_CONFIG_LOG option takes two arguments: a pointer to a
2034 ** function with a call signature of void(*)(void*,int,const char*), 
2035 ** and a pointer to void. ^If the function pointer is not NULL, it is
2036 ** invoked by [sqlcipher3_log()] to process each logging event.  ^If the
2037 ** function pointer is NULL, the [sqlcipher3_log()] interface becomes a no-op.
2038 ** ^The void pointer that is the second argument to SQLCIPHER_CONFIG_LOG is
2039 ** passed through as the first parameter to the application-defined logger
2040 ** function whenever that function is invoked.  ^The second parameter to
2041 ** the logger function is a copy of the first parameter to the corresponding
2042 ** [sqlcipher3_log()] call and is intended to be a [result code] or an
2043 ** [extended result code].  ^The third parameter passed to the logger is
2044 ** log message after formatting via [sqlcipher3_snprintf()].
2045 ** The SQLite logging interface is not reentrant; the logger function
2046 ** supplied by the application must not invoke any SQLite interface.
2047 ** In a multi-threaded application, the application-defined logger
2048 ** function must be threadsafe. </dd>
2049 **
2050 ** [[SQLCIPHER_CONFIG_URI]] <dt>SQLCIPHER_CONFIG_URI
2051 ** <dd> This option takes a single argument of type int. If non-zero, then
2052 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2053 ** is globally disabled. If URI handling is globally enabled, all filenames
2054 ** passed to [sqlcipher3_open()], [sqlcipher3_open_v2()], [sqlcipher3_open16()] or
2055 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2056 ** of whether or not the [SQLCIPHER_OPEN_URI] flag is set when the database
2057 ** connection is opened. If it is globally disabled, filenames are
2058 ** only interpreted as URIs if the SQLCIPHER_OPEN_URI flag is set when the
2059 ** database connection is opened. By default, URI handling is globally
2060 ** disabled. The default value may be changed by compiling with the
2061 ** [SQLCIPHER_USE_URI] symbol defined.
2062 ** </dl>
2063 */
2064 #define SQLCIPHER_CONFIG_SINGLETHREAD  1  /* nil */
2065 #define SQLCIPHER_CONFIG_MULTITHREAD   2  /* nil */
2066 #define SQLCIPHER_CONFIG_SERIALIZED    3  /* nil */
2067 #define SQLCIPHER_CONFIG_MALLOC        4  /* sqlcipher3_mem_methods* */
2068 #define SQLCIPHER_CONFIG_GETMALLOC     5  /* sqlcipher3_mem_methods* */
2069 #define SQLCIPHER_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2070 #define SQLCIPHER_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2071 #define SQLCIPHER_CONFIG_HEAP          8  /* void*, int nByte, int min */
2072 #define SQLCIPHER_CONFIG_MEMSTATUS     9  /* boolean */
2073 #define SQLCIPHER_CONFIG_MUTEX        10  /* sqlcipher3_mutex_methods* */
2074 #define SQLCIPHER_CONFIG_GETMUTEX     11  /* sqlcipher3_mutex_methods* */
2075 /* previously SQLCIPHER_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2076 #define SQLCIPHER_CONFIG_LOOKASIDE    13  /* int int */
2077 #define SQLCIPHER_CONFIG_PCACHE       14  /* sqlcipher3_pcache_methods* */
2078 #define SQLCIPHER_CONFIG_GETPCACHE    15  /* sqlcipher3_pcache_methods* */
2079 #define SQLCIPHER_CONFIG_LOG          16  /* xFunc, void* */
2080 #define SQLCIPHER_CONFIG_URI          17  /* int */
2081
2082 /*
2083 ** CAPI3REF: Database Connection Configuration Options
2084 **
2085 ** These constants are the available integer configuration options that
2086 ** can be passed as the second argument to the [sqlcipher3_db_config()] interface.
2087 **
2088 ** New configuration options may be added in future releases of SQLite.
2089 ** Existing configuration options might be discontinued.  Applications
2090 ** should check the return code from [sqlcipher3_db_config()] to make sure that
2091 ** the call worked.  ^The [sqlcipher3_db_config()] interface will return a
2092 ** non-zero [error code] if a discontinued or unsupported configuration option
2093 ** is invoked.
2094 **
2095 ** <dl>
2096 ** <dt>SQLCIPHER_DBCONFIG_LOOKASIDE</dt>
2097 ** <dd> ^This option takes three additional arguments that determine the 
2098 ** [lookaside memory allocator] configuration for the [database connection].
2099 ** ^The first argument (the third parameter to [sqlcipher3_db_config()] is a
2100 ** pointer to a memory buffer to use for lookaside memory.
2101 ** ^The first argument after the SQLCIPHER_DBCONFIG_LOOKASIDE verb
2102 ** may be NULL in which case SQLite will allocate the
2103 ** lookaside buffer itself using [sqlcipher3_malloc()]. ^The second argument is the
2104 ** size of each lookaside buffer slot.  ^The third argument is the number of
2105 ** slots.  The size of the buffer in the first argument must be greater than
2106 ** or equal to the product of the second and third arguments.  The buffer
2107 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2108 ** SQLCIPHER_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2109 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2110 ** configuration for a database connection can only be changed when that
2111 ** connection is not currently using lookaside memory, or in other words
2112 ** when the "current value" returned by
2113 ** [sqlcipher3_db_status](D,[SQLCIPHER_CONFIG_LOOKASIDE],...) is zero.
2114 ** Any attempt to change the lookaside memory configuration when lookaside
2115 ** memory is in use leaves the configuration unchanged and returns 
2116 ** [SQLCIPHER_BUSY].)^</dd>
2117 **
2118 ** <dt>SQLCIPHER_DBCONFIG_ENABLE_FKEY</dt>
2119 ** <dd> ^This option is used to enable or disable the enforcement of
2120 ** [foreign key constraints].  There should be two additional arguments.
2121 ** The first argument is an integer which is 0 to disable FK enforcement,
2122 ** positive to enable FK enforcement or negative to leave FK enforcement
2123 ** unchanged.  The second parameter is a pointer to an integer into which
2124 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2125 ** following this call.  The second parameter may be a NULL pointer, in
2126 ** which case the FK enforcement setting is not reported back. </dd>
2127 **
2128 ** <dt>SQLCIPHER_DBCONFIG_ENABLE_TRIGGER</dt>
2129 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2130 ** There should be two additional arguments.
2131 ** The first argument is an integer which is 0 to disable triggers,
2132 ** positive to enable triggers or negative to leave the setting unchanged.
2133 ** The second parameter is a pointer to an integer into which
2134 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2135 ** following this call.  The second parameter may be a NULL pointer, in
2136 ** which case the trigger setting is not reported back. </dd>
2137 **
2138 ** </dl>
2139 */
2140 #define SQLCIPHER_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2141 #define SQLCIPHER_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2142 #define SQLCIPHER_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2143
2144
2145 /*
2146 ** CAPI3REF: Enable Or Disable Extended Result Codes
2147 **
2148 ** ^The sqlcipher3_extended_result_codes() routine enables or disables the
2149 ** [extended result codes] feature of SQLite. ^The extended result
2150 ** codes are disabled by default for historical compatibility.
2151 */
2152 SQLCIPHER_API int sqlcipher3_extended_result_codes(sqlcipher3*, int onoff);
2153
2154 /*
2155 ** CAPI3REF: Last Insert Rowid
2156 **
2157 ** ^Each entry in an SQLite table has a unique 64-bit signed
2158 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2159 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2160 ** names are not also used by explicitly declared columns. ^If
2161 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2162 ** is another alias for the rowid.
2163 **
2164 ** ^This routine returns the [rowid] of the most recent
2165 ** successful [INSERT] into the database from the [database connection]
2166 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2167 ** records the last insert rowid of both ordinary tables and [virtual tables].
2168 ** ^If no successful [INSERT]s
2169 ** have ever occurred on that database connection, zero is returned.
2170 **
2171 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2172 ** method, then this routine will return the [rowid] of the inserted
2173 ** row as long as the trigger or virtual table method is running.
2174 ** But once the trigger or virtual table method ends, the value returned 
2175 ** by this routine reverts to what it was before the trigger or virtual
2176 ** table method began.)^
2177 **
2178 ** ^An [INSERT] that fails due to a constraint violation is not a
2179 ** successful [INSERT] and does not change the value returned by this
2180 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2181 ** and INSERT OR ABORT make no changes to the return value of this
2182 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2183 ** encounters a constraint violation, it does not fail.  The
2184 ** INSERT continues to completion after deleting rows that caused
2185 ** the constraint problem so INSERT OR REPLACE will always change
2186 ** the return value of this interface.)^
2187 **
2188 ** ^For the purposes of this routine, an [INSERT] is considered to
2189 ** be successful even if it is subsequently rolled back.
2190 **
2191 ** This function is accessible to SQL statements via the
2192 ** [last_insert_rowid() SQL function].
2193 **
2194 ** If a separate thread performs a new [INSERT] on the same
2195 ** database connection while the [sqlcipher3_last_insert_rowid()]
2196 ** function is running and thus changes the last insert [rowid],
2197 ** then the value returned by [sqlcipher3_last_insert_rowid()] is
2198 ** unpredictable and might not equal either the old or the new
2199 ** last insert [rowid].
2200 */
2201 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_last_insert_rowid(sqlcipher3*);
2202
2203 /*
2204 ** CAPI3REF: Count The Number Of Rows Modified
2205 **
2206 ** ^This function returns the number of database rows that were changed
2207 ** or inserted or deleted by the most recently completed SQL statement
2208 ** on the [database connection] specified by the first parameter.
2209 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2210 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2211 ** triggers or [foreign key actions] are not counted.)^ Use the
2212 ** [sqlcipher3_total_changes()] function to find the total number of changes
2213 ** including changes caused by triggers and foreign key actions.
2214 **
2215 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2216 ** are not counted.  Only real table changes are counted.
2217 **
2218 ** ^(A "row change" is a change to a single row of a single table
2219 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2220 ** are changed as side effects of [REPLACE] constraint resolution,
2221 ** rollback, ABORT processing, [DROP TABLE], or by any other
2222 ** mechanisms do not count as direct row changes.)^
2223 **
2224 ** A "trigger context" is a scope of execution that begins and
2225 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2226 ** Most SQL statements are
2227 ** evaluated outside of any trigger.  This is the "top level"
2228 ** trigger context.  If a trigger fires from the top level, a
2229 ** new trigger context is entered for the duration of that one
2230 ** trigger.  Subtriggers create subcontexts for their duration.
2231 **
2232 ** ^Calling [sqlcipher3_exec()] or [sqlcipher3_step()] recursively does
2233 ** not create a new trigger context.
2234 **
2235 ** ^This function returns the number of direct row changes in the
2236 ** most recent INSERT, UPDATE, or DELETE statement within the same
2237 ** trigger context.
2238 **
2239 ** ^Thus, when called from the top level, this function returns the
2240 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2241 ** that also occurred at the top level.  ^(Within the body of a trigger,
2242 ** the sqlcipher3_changes() interface can be called to find the number of
2243 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2244 ** statement within the body of the same trigger.
2245 ** However, the number returned does not include changes
2246 ** caused by subtriggers since those have their own context.)^
2247 **
2248 ** See also the [sqlcipher3_total_changes()] interface, the
2249 ** [count_changes pragma], and the [changes() SQL function].
2250 **
2251 ** If a separate thread makes changes on the same database connection
2252 ** while [sqlcipher3_changes()] is running then the value returned
2253 ** is unpredictable and not meaningful.
2254 */
2255 SQLCIPHER_API int sqlcipher3_changes(sqlcipher3*);
2256
2257 /*
2258 ** CAPI3REF: Total Number Of Rows Modified
2259 **
2260 ** ^This function returns the number of row changes caused by [INSERT],
2261 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2262 ** ^(The count returned by sqlcipher3_total_changes() includes all changes
2263 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2264 ** [foreign key actions]. However,
2265 ** the count does not include changes used to implement [REPLACE] constraints,
2266 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2267 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2268 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2269 ** are counted.)^
2270 ** ^The sqlcipher3_total_changes() function counts the changes as soon as
2271 ** the statement that makes them is completed (when the statement handle
2272 ** is passed to [sqlcipher3_reset()] or [sqlcipher3_finalize()]).
2273 **
2274 ** See also the [sqlcipher3_changes()] interface, the
2275 ** [count_changes pragma], and the [total_changes() SQL function].
2276 **
2277 ** If a separate thread makes changes on the same database connection
2278 ** while [sqlcipher3_total_changes()] is running then the value
2279 ** returned is unpredictable and not meaningful.
2280 */
2281 SQLCIPHER_API int sqlcipher3_total_changes(sqlcipher3*);
2282
2283 /*
2284 ** CAPI3REF: Interrupt A Long-Running Query
2285 **
2286 ** ^This function causes any pending database operation to abort and
2287 ** return at its earliest opportunity. This routine is typically
2288 ** called in response to a user action such as pressing "Cancel"
2289 ** or Ctrl-C where the user wants a long query operation to halt
2290 ** immediately.
2291 **
2292 ** ^It is safe to call this routine from a thread different from the
2293 ** thread that is currently running the database operation.  But it
2294 ** is not safe to call this routine with a [database connection] that
2295 ** is closed or might close before sqlcipher3_interrupt() returns.
2296 **
2297 ** ^If an SQL operation is very nearly finished at the time when
2298 ** sqlcipher3_interrupt() is called, then it might not have an opportunity
2299 ** to be interrupted and might continue to completion.
2300 **
2301 ** ^An SQL operation that is interrupted will return [SQLCIPHER_INTERRUPT].
2302 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2303 ** that is inside an explicit transaction, then the entire transaction
2304 ** will be rolled back automatically.
2305 **
2306 ** ^The sqlcipher3_interrupt(D) call is in effect until all currently running
2307 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2308 ** that are started after the sqlcipher3_interrupt() call and before the 
2309 ** running statements reaches zero are interrupted as if they had been
2310 ** running prior to the sqlcipher3_interrupt() call.  ^New SQL statements
2311 ** that are started after the running statement count reaches zero are
2312 ** not effected by the sqlcipher3_interrupt().
2313 ** ^A call to sqlcipher3_interrupt(D) that occurs when there are no running
2314 ** SQL statements is a no-op and has no effect on SQL statements
2315 ** that are started after the sqlcipher3_interrupt() call returns.
2316 **
2317 ** If the database connection closes while [sqlcipher3_interrupt()]
2318 ** is running then bad things will likely happen.
2319 */
2320 SQLCIPHER_API void sqlcipher3_interrupt(sqlcipher3*);
2321
2322 /*
2323 ** CAPI3REF: Determine If An SQL Statement Is Complete
2324 **
2325 ** These routines are useful during command-line input to determine if the
2326 ** currently entered text seems to form a complete SQL statement or
2327 ** if additional input is needed before sending the text into
2328 ** SQLite for parsing.  ^These routines return 1 if the input string
2329 ** appears to be a complete SQL statement.  ^A statement is judged to be
2330 ** complete if it ends with a semicolon token and is not a prefix of a
2331 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2332 ** string literals or quoted identifier names or comments are not
2333 ** independent tokens (they are part of the token in which they are
2334 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2335 ** and comments that follow the final semicolon are ignored.
2336 **
2337 ** ^These routines return 0 if the statement is incomplete.  ^If a
2338 ** memory allocation fails, then SQLCIPHER_NOMEM is returned.
2339 **
2340 ** ^These routines do not parse the SQL statements thus
2341 ** will not detect syntactically incorrect SQL.
2342 **
2343 ** ^(If SQLite has not been initialized using [sqlcipher3_initialize()] prior 
2344 ** to invoking sqlcipher3_complete16() then sqlcipher3_initialize() is invoked
2345 ** automatically by sqlcipher3_complete16().  If that initialization fails,
2346 ** then the return value from sqlcipher3_complete16() will be non-zero
2347 ** regardless of whether or not the input SQL is complete.)^
2348 **
2349 ** The input to [sqlcipher3_complete()] must be a zero-terminated
2350 ** UTF-8 string.
2351 **
2352 ** The input to [sqlcipher3_complete16()] must be a zero-terminated
2353 ** UTF-16 string in native byte order.
2354 */
2355 SQLCIPHER_API int sqlcipher3_complete(const char *sql);
2356 SQLCIPHER_API int sqlcipher3_complete16(const void *sql);
2357
2358 /*
2359 ** CAPI3REF: Register A Callback To Handle SQLCIPHER_BUSY Errors
2360 **
2361 ** ^This routine sets a callback function that might be invoked whenever
2362 ** an attempt is made to open a database table that another thread
2363 ** or process has locked.
2364 **
2365 ** ^If the busy callback is NULL, then [SQLCIPHER_BUSY] or [SQLCIPHER_IOERR_BLOCKED]
2366 ** is returned immediately upon encountering the lock.  ^If the busy callback
2367 ** is not NULL, then the callback might be invoked with two arguments.
2368 **
2369 ** ^The first argument to the busy handler is a copy of the void* pointer which
2370 ** is the third argument to sqlcipher3_busy_handler().  ^The second argument to
2371 ** the busy handler callback is the number of times that the busy handler has
2372 ** been invoked for this locking event.  ^If the
2373 ** busy callback returns 0, then no additional attempts are made to
2374 ** access the database and [SQLCIPHER_BUSY] or [SQLCIPHER_IOERR_BLOCKED] is returned.
2375 ** ^If the callback returns non-zero, then another attempt
2376 ** is made to open the database for reading and the cycle repeats.
2377 **
2378 ** The presence of a busy handler does not guarantee that it will be invoked
2379 ** when there is lock contention. ^If SQLite determines that invoking the busy
2380 ** handler could result in a deadlock, it will go ahead and return [SQLCIPHER_BUSY]
2381 ** or [SQLCIPHER_IOERR_BLOCKED] instead of invoking the busy handler.
2382 ** Consider a scenario where one process is holding a read lock that
2383 ** it is trying to promote to a reserved lock and
2384 ** a second process is holding a reserved lock that it is trying
2385 ** to promote to an exclusive lock.  The first process cannot proceed
2386 ** because it is blocked by the second and the second process cannot
2387 ** proceed because it is blocked by the first.  If both processes
2388 ** invoke the busy handlers, neither will make any progress.  Therefore,
2389 ** SQLite returns [SQLCIPHER_BUSY] for the first process, hoping that this
2390 ** will induce the first process to release its read lock and allow
2391 ** the second process to proceed.
2392 **
2393 ** ^The default busy callback is NULL.
2394 **
2395 ** ^The [SQLCIPHER_BUSY] error is converted to [SQLCIPHER_IOERR_BLOCKED]
2396 ** when SQLite is in the middle of a large transaction where all the
2397 ** changes will not fit into the in-memory cache.  SQLite will
2398 ** already hold a RESERVED lock on the database file, but it needs
2399 ** to promote this lock to EXCLUSIVE so that it can spill cache
2400 ** pages into the database file without harm to concurrent
2401 ** readers.  ^If it is unable to promote the lock, then the in-memory
2402 ** cache will be left in an inconsistent state and so the error
2403 ** code is promoted from the relatively benign [SQLCIPHER_BUSY] to
2404 ** the more severe [SQLCIPHER_IOERR_BLOCKED].  ^This error code promotion
2405 ** forces an automatic rollback of the changes.  See the
2406 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2407 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2408 ** this is important.
2409 **
2410 ** ^(There can only be a single busy handler defined for each
2411 ** [database connection].  Setting a new busy handler clears any
2412 ** previously set handler.)^  ^Note that calling [sqlcipher3_busy_timeout()]
2413 ** will also set or clear the busy handler.
2414 **
2415 ** The busy callback should not take any actions which modify the
2416 ** database connection that invoked the busy handler.  Any such actions
2417 ** result in undefined behavior.
2418 ** 
2419 ** A busy handler must not close the database connection
2420 ** or [prepared statement] that invoked the busy handler.
2421 */
2422 SQLCIPHER_API int sqlcipher3_busy_handler(sqlcipher3*, int(*)(void*,int), void*);
2423
2424 /*
2425 ** CAPI3REF: Set A Busy Timeout
2426 **
2427 ** ^This routine sets a [sqlcipher3_busy_handler | busy handler] that sleeps
2428 ** for a specified amount of time when a table is locked.  ^The handler
2429 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2430 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2431 ** the handler returns 0 which causes [sqlcipher3_step()] to return
2432 ** [SQLCIPHER_BUSY] or [SQLCIPHER_IOERR_BLOCKED].
2433 **
2434 ** ^Calling this routine with an argument less than or equal to zero
2435 ** turns off all busy handlers.
2436 **
2437 ** ^(There can only be a single busy handler for a particular
2438 ** [database connection] any any given moment.  If another busy handler
2439 ** was defined  (using [sqlcipher3_busy_handler()]) prior to calling
2440 ** this routine, that other busy handler is cleared.)^
2441 */
2442 SQLCIPHER_API int sqlcipher3_busy_timeout(sqlcipher3*, int ms);
2443
2444 /*
2445 ** CAPI3REF: Convenience Routines For Running Queries
2446 **
2447 ** This is a legacy interface that is preserved for backwards compatibility.
2448 ** Use of this interface is not recommended.
2449 **
2450 ** Definition: A <b>result table</b> is memory data structure created by the
2451 ** [sqlcipher3_get_table()] interface.  A result table records the
2452 ** complete query results from one or more queries.
2453 **
2454 ** The table conceptually has a number of rows and columns.  But
2455 ** these numbers are not part of the result table itself.  These
2456 ** numbers are obtained separately.  Let N be the number of rows
2457 ** and M be the number of columns.
2458 **
2459 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2460 ** There are (N+1)*M elements in the array.  The first M pointers point
2461 ** to zero-terminated strings that  contain the names of the columns.
2462 ** The remaining entries all point to query results.  NULL values result
2463 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2464 ** string representation as returned by [sqlcipher3_column_text()].
2465 **
2466 ** A result table might consist of one or more memory allocations.
2467 ** It is not safe to pass a result table directly to [sqlcipher3_free()].
2468 ** A result table should be deallocated using [sqlcipher3_free_table()].
2469 **
2470 ** ^(As an example of the result table format, suppose a query result
2471 ** is as follows:
2472 **
2473 ** <blockquote><pre>
2474 **        Name        | Age
2475 **        -----------------------
2476 **        Alice       | 43
2477 **        Bob         | 28
2478 **        Cindy       | 21
2479 ** </pre></blockquote>
2480 **
2481 ** There are two column (M==2) and three rows (N==3).  Thus the
2482 ** result table has 8 entries.  Suppose the result table is stored
2483 ** in an array names azResult.  Then azResult holds this content:
2484 **
2485 ** <blockquote><pre>
2486 **        azResult&#91;0] = "Name";
2487 **        azResult&#91;1] = "Age";
2488 **        azResult&#91;2] = "Alice";
2489 **        azResult&#91;3] = "43";
2490 **        azResult&#91;4] = "Bob";
2491 **        azResult&#91;5] = "28";
2492 **        azResult&#91;6] = "Cindy";
2493 **        azResult&#91;7] = "21";
2494 ** </pre></blockquote>)^
2495 **
2496 ** ^The sqlcipher3_get_table() function evaluates one or more
2497 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2498 ** string of its 2nd parameter and returns a result table to the
2499 ** pointer given in its 3rd parameter.
2500 **
2501 ** After the application has finished with the result from sqlcipher3_get_table(),
2502 ** it must pass the result table pointer to sqlcipher3_free_table() in order to
2503 ** release the memory that was malloced.  Because of the way the
2504 ** [sqlcipher3_malloc()] happens within sqlcipher3_get_table(), the calling
2505 ** function must not try to call [sqlcipher3_free()] directly.  Only
2506 ** [sqlcipher3_free_table()] is able to release the memory properly and safely.
2507 **
2508 ** The sqlcipher3_get_table() interface is implemented as a wrapper around
2509 ** [sqlcipher3_exec()].  The sqlcipher3_get_table() routine does not have access
2510 ** to any internal data structures of SQLite.  It uses only the public
2511 ** interface defined here.  As a consequence, errors that occur in the
2512 ** wrapper layer outside of the internal [sqlcipher3_exec()] call are not
2513 ** reflected in subsequent calls to [sqlcipher3_errcode()] or
2514 ** [sqlcipher3_errmsg()].
2515 */
2516 SQLCIPHER_API int sqlcipher3_get_table(
2517   sqlcipher3 *db,          /* An open database */
2518   const char *zSql,     /* SQL to be evaluated */
2519   char ***pazResult,    /* Results of the query */
2520   int *pnRow,           /* Number of result rows written here */
2521   int *pnColumn,        /* Number of result columns written here */
2522   char **pzErrmsg       /* Error msg written here */
2523 );
2524 SQLCIPHER_API void sqlcipher3_free_table(char **result);
2525
2526 /*
2527 ** CAPI3REF: Formatted String Printing Functions
2528 **
2529 ** These routines are work-alikes of the "printf()" family of functions
2530 ** from the standard C library.
2531 **
2532 ** ^The sqlcipher3_mprintf() and sqlcipher3_vmprintf() routines write their
2533 ** results into memory obtained from [sqlcipher3_malloc()].
2534 ** The strings returned by these two routines should be
2535 ** released by [sqlcipher3_free()].  ^Both routines return a
2536 ** NULL pointer if [sqlcipher3_malloc()] is unable to allocate enough
2537 ** memory to hold the resulting string.
2538 **
2539 ** ^(The sqlcipher3_snprintf() routine is similar to "snprintf()" from
2540 ** the standard C library.  The result is written into the
2541 ** buffer supplied as the second parameter whose size is given by
2542 ** the first parameter. Note that the order of the
2543 ** first two parameters is reversed from snprintf().)^  This is an
2544 ** historical accident that cannot be fixed without breaking
2545 ** backwards compatibility.  ^(Note also that sqlcipher3_snprintf()
2546 ** returns a pointer to its buffer instead of the number of
2547 ** characters actually written into the buffer.)^  We admit that
2548 ** the number of characters written would be a more useful return
2549 ** value but we cannot change the implementation of sqlcipher3_snprintf()
2550 ** now without breaking compatibility.
2551 **
2552 ** ^As long as the buffer size is greater than zero, sqlcipher3_snprintf()
2553 ** guarantees that the buffer is always zero-terminated.  ^The first
2554 ** parameter "n" is the total size of the buffer, including space for
2555 ** the zero terminator.  So the longest string that can be completely
2556 ** written will be n-1 characters.
2557 **
2558 ** ^The sqlcipher3_vsnprintf() routine is a varargs version of sqlcipher3_snprintf().
2559 **
2560 ** These routines all implement some additional formatting
2561 ** options that are useful for constructing SQL statements.
2562 ** All of the usual printf() formatting options apply.  In addition, there
2563 ** is are "%q", "%Q", and "%z" options.
2564 **
2565 ** ^(The %q option works like %s in that it substitutes a null-terminated
2566 ** string from the argument list.  But %q also doubles every '\'' character.
2567 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2568 ** character it escapes that character and allows it to be inserted into
2569 ** the string.
2570 **
2571 ** For example, assume the string variable zText contains text as follows:
2572 **
2573 ** <blockquote><pre>
2574 **  char *zText = "It's a happy day!";
2575 ** </pre></blockquote>
2576 **
2577 ** One can use this text in an SQL statement as follows:
2578 **
2579 ** <blockquote><pre>
2580 **  char *zSQL = sqlcipher3_mprintf("INSERT INTO table VALUES('%q')", zText);
2581 **  sqlcipher3_exec(db, zSQL, 0, 0, 0);
2582 **  sqlcipher3_free(zSQL);
2583 ** </pre></blockquote>
2584 **
2585 ** Because the %q format string is used, the '\'' character in zText
2586 ** is escaped and the SQL generated is as follows:
2587 **
2588 ** <blockquote><pre>
2589 **  INSERT INTO table1 VALUES('It''s a happy day!')
2590 ** </pre></blockquote>
2591 **
2592 ** This is correct.  Had we used %s instead of %q, the generated SQL
2593 ** would have looked like this:
2594 **
2595 ** <blockquote><pre>
2596 **  INSERT INTO table1 VALUES('It's a happy day!');
2597 ** </pre></blockquote>
2598 **
2599 ** This second example is an SQL syntax error.  As a general rule you should
2600 ** always use %q instead of %s when inserting text into a string literal.
2601 **
2602 ** ^(The %Q option works like %q except it also adds single quotes around
2603 ** the outside of the total string.  Additionally, if the parameter in the
2604 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2605 ** single quotes).)^  So, for example, one could say:
2606 **
2607 ** <blockquote><pre>
2608 **  char *zSQL = sqlcipher3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2609 **  sqlcipher3_exec(db, zSQL, 0, 0, 0);
2610 **  sqlcipher3_free(zSQL);
2611 ** </pre></blockquote>
2612 **
2613 ** The code above will render a correct SQL statement in the zSQL
2614 ** variable even if the zText variable is a NULL pointer.
2615 **
2616 ** ^(The "%z" formatting option works like "%s" but with the
2617 ** addition that after the string has been read and copied into
2618 ** the result, [sqlcipher3_free()] is called on the input string.)^
2619 */
2620 SQLCIPHER_API char *sqlcipher3_mprintf(const char*,...);
2621 SQLCIPHER_API char *sqlcipher3_vmprintf(const char*, va_list);
2622 SQLCIPHER_API char *sqlcipher3_snprintf(int,char*,const char*, ...);
2623 SQLCIPHER_API char *sqlcipher3_vsnprintf(int,char*,const char*, va_list);
2624
2625 /*
2626 ** CAPI3REF: Memory Allocation Subsystem
2627 **
2628 ** The SQLite core uses these three routines for all of its own
2629 ** internal memory allocation needs. "Core" in the previous sentence
2630 ** does not include operating-system specific VFS implementation.  The
2631 ** Windows VFS uses native malloc() and free() for some operations.
2632 **
2633 ** ^The sqlcipher3_malloc() routine returns a pointer to a block
2634 ** of memory at least N bytes in length, where N is the parameter.
2635 ** ^If sqlcipher3_malloc() is unable to obtain sufficient free
2636 ** memory, it returns a NULL pointer.  ^If the parameter N to
2637 ** sqlcipher3_malloc() is zero or negative then sqlcipher3_malloc() returns
2638 ** a NULL pointer.
2639 **
2640 ** ^Calling sqlcipher3_free() with a pointer previously returned
2641 ** by sqlcipher3_malloc() or sqlcipher3_realloc() releases that memory so
2642 ** that it might be reused.  ^The sqlcipher3_free() routine is
2643 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2644 ** to sqlcipher3_free() is harmless.  After being freed, memory
2645 ** should neither be read nor written.  Even reading previously freed
2646 ** memory might result in a segmentation fault or other severe error.
2647 ** Memory corruption, a segmentation fault, or other severe error
2648 ** might result if sqlcipher3_free() is called with a non-NULL pointer that
2649 ** was not obtained from sqlcipher3_malloc() or sqlcipher3_realloc().
2650 **
2651 ** ^(The sqlcipher3_realloc() interface attempts to resize a
2652 ** prior memory allocation to be at least N bytes, where N is the
2653 ** second parameter.  The memory allocation to be resized is the first
2654 ** parameter.)^ ^ If the first parameter to sqlcipher3_realloc()
2655 ** is a NULL pointer then its behavior is identical to calling
2656 ** sqlcipher3_malloc(N) where N is the second parameter to sqlcipher3_realloc().
2657 ** ^If the second parameter to sqlcipher3_realloc() is zero or
2658 ** negative then the behavior is exactly the same as calling
2659 ** sqlcipher3_free(P) where P is the first parameter to sqlcipher3_realloc().
2660 ** ^sqlcipher3_realloc() returns a pointer to a memory allocation
2661 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2662 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2663 ** of the prior allocation are copied into the beginning of buffer returned
2664 ** by sqlcipher3_realloc() and the prior allocation is freed.
2665 ** ^If sqlcipher3_realloc() returns NULL, then the prior allocation
2666 ** is not freed.
2667 **
2668 ** ^The memory returned by sqlcipher3_malloc() and sqlcipher3_realloc()
2669 ** is always aligned to at least an 8 byte boundary, or to a
2670 ** 4 byte boundary if the [SQLCIPHER_4_BYTE_ALIGNED_MALLOC] compile-time
2671 ** option is used.
2672 **
2673 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2674 ** the SQLCIPHER_OMIT_MEMORY_ALLOCATION which would cause the built-in
2675 ** implementation of these routines to be omitted.  That capability
2676 ** is no longer provided.  Only built-in memory allocators can be used.
2677 **
2678 ** The Windows OS interface layer calls
2679 ** the system malloc() and free() directly when converting
2680 ** filenames between the UTF-8 encoding used by SQLite
2681 ** and whatever filename encoding is used by the particular Windows
2682 ** installation.  Memory allocation errors are detected, but
2683 ** they are reported back as [SQLCIPHER_CANTOPEN] or
2684 ** [SQLCIPHER_IOERR] rather than [SQLCIPHER_NOMEM].
2685 **
2686 ** The pointer arguments to [sqlcipher3_free()] and [sqlcipher3_realloc()]
2687 ** must be either NULL or else pointers obtained from a prior
2688 ** invocation of [sqlcipher3_malloc()] or [sqlcipher3_realloc()] that have
2689 ** not yet been released.
2690 **
2691 ** The application must not read or write any part of
2692 ** a block of memory after it has been released using
2693 ** [sqlcipher3_free()] or [sqlcipher3_realloc()].
2694 */
2695 SQLCIPHER_API void *sqlcipher3_malloc(int);
2696 SQLCIPHER_API void *sqlcipher3_realloc(void*, int);
2697 SQLCIPHER_API void sqlcipher3_free(void*);
2698
2699 /*
2700 ** CAPI3REF: Memory Allocator Statistics
2701 **
2702 ** SQLite provides these two interfaces for reporting on the status
2703 ** of the [sqlcipher3_malloc()], [sqlcipher3_free()], and [sqlcipher3_realloc()]
2704 ** routines, which form the built-in memory allocation subsystem.
2705 **
2706 ** ^The [sqlcipher3_memory_used()] routine returns the number of bytes
2707 ** of memory currently outstanding (malloced but not freed).
2708 ** ^The [sqlcipher3_memory_highwater()] routine returns the maximum
2709 ** value of [sqlcipher3_memory_used()] since the high-water mark
2710 ** was last reset.  ^The values returned by [sqlcipher3_memory_used()] and
2711 ** [sqlcipher3_memory_highwater()] include any overhead
2712 ** added by SQLite in its implementation of [sqlcipher3_malloc()],
2713 ** but not overhead added by the any underlying system library
2714 ** routines that [sqlcipher3_malloc()] may call.
2715 **
2716 ** ^The memory high-water mark is reset to the current value of
2717 ** [sqlcipher3_memory_used()] if and only if the parameter to
2718 ** [sqlcipher3_memory_highwater()] is true.  ^The value returned
2719 ** by [sqlcipher3_memory_highwater(1)] is the high-water mark
2720 ** prior to the reset.
2721 */
2722 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_used(void);
2723 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_highwater(int resetFlag);
2724
2725 /*
2726 ** CAPI3REF: Pseudo-Random Number Generator
2727 **
2728 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2729 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2730 ** already uses the largest possible [ROWID].  The PRNG is also used for
2731 ** the build-in random() and randomblob() SQL functions.  This interface allows
2732 ** applications to access the same PRNG for other purposes.
2733 **
2734 ** ^A call to this routine stores N bytes of randomness into buffer P.
2735 **
2736 ** ^The first time this routine is invoked (either internally or by
2737 ** the application) the PRNG is seeded using randomness obtained
2738 ** from the xRandomness method of the default [sqlcipher3_vfs] object.
2739 ** ^On all subsequent invocations, the pseudo-randomness is generated
2740 ** internally and without recourse to the [sqlcipher3_vfs] xRandomness
2741 ** method.
2742 */
2743 SQLCIPHER_API void sqlcipher3_randomness(int N, void *P);
2744
2745 /*
2746 ** CAPI3REF: Compile-Time Authorization Callbacks
2747 **
2748 ** ^This routine registers an authorizer callback with a particular
2749 ** [database connection], supplied in the first argument.
2750 ** ^The authorizer callback is invoked as SQL statements are being compiled
2751 ** by [sqlcipher3_prepare()] or its variants [sqlcipher3_prepare_v2()],
2752 ** [sqlcipher3_prepare16()] and [sqlcipher3_prepare16_v2()].  ^At various
2753 ** points during the compilation process, as logic is being created
2754 ** to perform various actions, the authorizer callback is invoked to
2755 ** see if those actions are allowed.  ^The authorizer callback should
2756 ** return [SQLCIPHER_OK] to allow the action, [SQLCIPHER_IGNORE] to disallow the
2757 ** specific action but allow the SQL statement to continue to be
2758 ** compiled, or [SQLCIPHER_DENY] to cause the entire SQL statement to be
2759 ** rejected with an error.  ^If the authorizer callback returns
2760 ** any value other than [SQLCIPHER_IGNORE], [SQLCIPHER_OK], or [SQLCIPHER_DENY]
2761 ** then the [sqlcipher3_prepare_v2()] or equivalent call that triggered
2762 ** the authorizer will fail with an error message.
2763 **
2764 ** When the callback returns [SQLCIPHER_OK], that means the operation
2765 ** requested is ok.  ^When the callback returns [SQLCIPHER_DENY], the
2766 ** [sqlcipher3_prepare_v2()] or equivalent call that triggered the
2767 ** authorizer will fail with an error message explaining that
2768 ** access is denied. 
2769 **
2770 ** ^The first parameter to the authorizer callback is a copy of the third
2771 ** parameter to the sqlcipher3_set_authorizer() interface. ^The second parameter
2772 ** to the callback is an integer [SQLCIPHER_COPY | action code] that specifies
2773 ** the particular action to be authorized. ^The third through sixth parameters
2774 ** to the callback are zero-terminated strings that contain additional
2775 ** details about the action to be authorized.
2776 **
2777 ** ^If the action code is [SQLCIPHER_READ]
2778 ** and the callback returns [SQLCIPHER_IGNORE] then the
2779 ** [prepared statement] statement is constructed to substitute
2780 ** a NULL value in place of the table column that would have
2781 ** been read if [SQLCIPHER_OK] had been returned.  The [SQLCIPHER_IGNORE]
2782 ** return can be used to deny an untrusted user access to individual
2783 ** columns of a table.
2784 ** ^If the action code is [SQLCIPHER_DELETE] and the callback returns
2785 ** [SQLCIPHER_IGNORE] then the [DELETE] operation proceeds but the
2786 ** [truncate optimization] is disabled and all rows are deleted individually.
2787 **
2788 ** An authorizer is used when [sqlcipher3_prepare | preparing]
2789 ** SQL statements from an untrusted source, to ensure that the SQL statements
2790 ** do not try to access data they are not allowed to see, or that they do not
2791 ** try to execute malicious statements that damage the database.  For
2792 ** example, an application may allow a user to enter arbitrary
2793 ** SQL queries for evaluation by a database.  But the application does
2794 ** not want the user to be able to make arbitrary changes to the
2795 ** database.  An authorizer could then be put in place while the
2796 ** user-entered SQL is being [sqlcipher3_prepare | prepared] that
2797 ** disallows everything except [SELECT] statements.
2798 **
2799 ** Applications that need to process SQL from untrusted sources
2800 ** might also consider lowering resource limits using [sqlcipher3_limit()]
2801 ** and limiting database size using the [max_page_count] [PRAGMA]
2802 ** in addition to using an authorizer.
2803 **
2804 ** ^(Only a single authorizer can be in place on a database connection
2805 ** at a time.  Each call to sqlcipher3_set_authorizer overrides the
2806 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2807 ** The authorizer is disabled by default.
2808 **
2809 ** The authorizer callback must not do anything that will modify
2810 ** the database connection that invoked the authorizer callback.
2811 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
2812 ** database connections for the meaning of "modify" in this paragraph.
2813 **
2814 ** ^When [sqlcipher3_prepare_v2()] is used to prepare a statement, the
2815 ** statement might be re-prepared during [sqlcipher3_step()] due to a 
2816 ** schema change.  Hence, the application should ensure that the
2817 ** correct authorizer callback remains in place during the [sqlcipher3_step()].
2818 **
2819 ** ^Note that the authorizer callback is invoked only during
2820 ** [sqlcipher3_prepare()] or its variants.  Authorization is not
2821 ** performed during statement evaluation in [sqlcipher3_step()], unless
2822 ** as stated in the previous paragraph, sqlcipher3_step() invokes
2823 ** sqlcipher3_prepare_v2() to reprepare a statement after a schema change.
2824 */
2825 SQLCIPHER_API int sqlcipher3_set_authorizer(
2826   sqlcipher3*,
2827   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2828   void *pUserData
2829 );
2830
2831 /*
2832 ** CAPI3REF: Authorizer Return Codes
2833 **
2834 ** The [sqlcipher3_set_authorizer | authorizer callback function] must
2835 ** return either [SQLCIPHER_OK] or one of these two constants in order
2836 ** to signal SQLite whether or not the action is permitted.  See the
2837 ** [sqlcipher3_set_authorizer | authorizer documentation] for additional
2838 ** information.
2839 **
2840 ** Note that SQLCIPHER_IGNORE is also used as a [SQLCIPHER_ROLLBACK | return code]
2841 ** from the [sqlcipher3_vtab_on_conflict()] interface.
2842 */
2843 #define SQLCIPHER_DENY   1   /* Abort the SQL statement with an error */
2844 #define SQLCIPHER_IGNORE 2   /* Don't allow access, but don't generate an error */
2845
2846 /*
2847 ** CAPI3REF: Authorizer Action Codes
2848 **
2849 ** The [sqlcipher3_set_authorizer()] interface registers a callback function
2850 ** that is invoked to authorize certain SQL statement actions.  The
2851 ** second parameter to the callback is an integer code that specifies
2852 ** what action is being authorized.  These are the integer action codes that
2853 ** the authorizer callback may be passed.
2854 **
2855 ** These action code values signify what kind of operation is to be
2856 ** authorized.  The 3rd and 4th parameters to the authorization
2857 ** callback function will be parameters or NULL depending on which of these
2858 ** codes is used as the second parameter.  ^(The 5th parameter to the
2859 ** authorizer callback is the name of the database ("main", "temp",
2860 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2861 ** is the name of the inner-most trigger or view that is responsible for
2862 ** the access attempt or NULL if this access attempt is directly from
2863 ** top-level SQL code.
2864 */
2865 /******************************************* 3rd ************ 4th ***********/
2866 #define SQLCIPHER_CREATE_INDEX          1   /* Index Name      Table Name      */
2867 #define SQLCIPHER_CREATE_TABLE          2   /* Table Name      NULL            */
2868 #define SQLCIPHER_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2869 #define SQLCIPHER_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2870 #define SQLCIPHER_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2871 #define SQLCIPHER_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2872 #define SQLCIPHER_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2873 #define SQLCIPHER_CREATE_VIEW           8   /* View Name       NULL            */
2874 #define SQLCIPHER_DELETE                9   /* Table Name      NULL            */
2875 #define SQLCIPHER_DROP_INDEX           10   /* Index Name      Table Name      */
2876 #define SQLCIPHER_DROP_TABLE           11   /* Table Name      NULL            */
2877 #define SQLCIPHER_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2878 #define SQLCIPHER_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2879 #define SQLCIPHER_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2880 #define SQLCIPHER_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2881 #define SQLCIPHER_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2882 #define SQLCIPHER_DROP_VIEW            17   /* View Name       NULL            */
2883 #define SQLCIPHER_INSERT               18   /* Table Name      NULL            */
2884 #define SQLCIPHER_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2885 #define SQLCIPHER_READ                 20   /* Table Name      Column Name     */
2886 #define SQLCIPHER_SELECT               21   /* NULL            NULL            */
2887 #define SQLCIPHER_TRANSACTION          22   /* Operation       NULL            */
2888 #define SQLCIPHER_UPDATE               23   /* Table Name      Column Name     */
2889 #define SQLCIPHER_ATTACH               24   /* Filename        NULL            */
2890 #define SQLCIPHER_DETACH               25   /* Database Name   NULL            */
2891 #define SQLCIPHER_ALTER_TABLE          26   /* Database Name   Table Name      */
2892 #define SQLCIPHER_REINDEX              27   /* Index Name      NULL            */
2893 #define SQLCIPHER_ANALYZE              28   /* Table Name      NULL            */
2894 #define SQLCIPHER_CREATE_VTABLE        29   /* Table Name      Module Name     */
2895 #define SQLCIPHER_DROP_VTABLE          30   /* Table Name      Module Name     */
2896 #define SQLCIPHER_FUNCTION             31   /* NULL            Function Name   */
2897 #define SQLCIPHER_SAVEPOINT            32   /* Operation       Savepoint Name  */
2898 #define SQLCIPHER_COPY                  0   /* No longer used */
2899
2900 /*
2901 ** CAPI3REF: Tracing And Profiling Functions
2902 **
2903 ** These routines register callback functions that can be used for
2904 ** tracing and profiling the execution of SQL statements.
2905 **
2906 ** ^The callback function registered by sqlcipher3_trace() is invoked at
2907 ** various times when an SQL statement is being run by [sqlcipher3_step()].
2908 ** ^The sqlcipher3_trace() callback is invoked with a UTF-8 rendering of the
2909 ** SQL statement text as the statement first begins executing.
2910 ** ^(Additional sqlcipher3_trace() callbacks might occur
2911 ** as each triggered subprogram is entered.  The callbacks for triggers
2912 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2913 **
2914 ** ^The callback function registered by sqlcipher3_profile() is invoked
2915 ** as each SQL statement finishes.  ^The profile callback contains
2916 ** the original statement text and an estimate of wall-clock time
2917 ** of how long that statement took to run.  ^The profile callback
2918 ** time is in units of nanoseconds, however the current implementation
2919 ** is only capable of millisecond resolution so the six least significant
2920 ** digits in the time are meaningless.  Future versions of SQLite
2921 ** might provide greater resolution on the profiler callback.  The
2922 ** sqlcipher3_profile() function is considered experimental and is
2923 ** subject to change in future versions of SQLite.
2924 */
2925 SQLCIPHER_API void *sqlcipher3_trace(sqlcipher3*, void(*xTrace)(void*,const char*), void*);
2926 SQLCIPHER_API SQLCIPHER_EXPERIMENTAL void *sqlcipher3_profile(sqlcipher3*,
2927    void(*xProfile)(void*,const char*,sqlcipher3_uint64), void*);
2928
2929 /*
2930 ** CAPI3REF: Query Progress Callbacks
2931 **
2932 ** ^The sqlcipher3_progress_handler(D,N,X,P) interface causes the callback
2933 ** function X to be invoked periodically during long running calls to
2934 ** [sqlcipher3_exec()], [sqlcipher3_step()] and [sqlcipher3_get_table()] for
2935 ** database connection D.  An example use for this
2936 ** interface is to keep a GUI updated during a large query.
2937 **
2938 ** ^The parameter P is passed through as the only parameter to the 
2939 ** callback function X.  ^The parameter N is the number of 
2940 ** [virtual machine instructions] that are evaluated between successive
2941 ** invocations of the callback X.
2942 **
2943 ** ^Only a single progress handler may be defined at one time per
2944 ** [database connection]; setting a new progress handler cancels the
2945 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2946 ** ^The progress handler is also disabled by setting N to a value less
2947 ** than 1.
2948 **
2949 ** ^If the progress callback returns non-zero, the operation is
2950 ** interrupted.  This feature can be used to implement a
2951 ** "Cancel" button on a GUI progress dialog box.
2952 **
2953 ** The progress handler callback must not do anything that will modify
2954 ** the database connection that invoked the progress handler.
2955 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
2956 ** database connections for the meaning of "modify" in this paragraph.
2957 **
2958 */
2959 SQLCIPHER_API void sqlcipher3_progress_handler(sqlcipher3*, int, int(*)(void*), void*);
2960
2961 /*
2962 ** CAPI3REF: Opening A New Database Connection
2963 **
2964 ** ^These routines open an SQLite database file as specified by the 
2965 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2966 ** sqlcipher3_open() and sqlcipher3_open_v2() and as UTF-16 in the native byte
2967 ** order for sqlcipher3_open16(). ^(A [database connection] handle is usually
2968 ** returned in *ppDb, even if an error occurs.  The only exception is that
2969 ** if SQLite is unable to allocate memory to hold the [sqlcipher3] object,
2970 ** a NULL will be written into *ppDb instead of a pointer to the [sqlcipher3]
2971 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2972 ** [SQLCIPHER_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2973 ** [sqlcipher3_errmsg()] or [sqlcipher3_errmsg16()] routines can be used to obtain
2974 ** an English language description of the error following a failure of any
2975 ** of the sqlcipher3_open() routines.
2976 **
2977 ** ^The default encoding for the database will be UTF-8 if
2978 ** sqlcipher3_open() or sqlcipher3_open_v2() is called and
2979 ** UTF-16 in the native byte order if sqlcipher3_open16() is used.
2980 **
2981 ** Whether or not an error occurs when it is opened, resources
2982 ** associated with the [database connection] handle should be released by
2983 ** passing it to [sqlcipher3_close()] when it is no longer required.
2984 **
2985 ** The sqlcipher3_open_v2() interface works like sqlcipher3_open()
2986 ** except that it accepts two additional parameters for additional control
2987 ** over the new database connection.  ^(The flags parameter to
2988 ** sqlcipher3_open_v2() can take one of
2989 ** the following three values, optionally combined with the 
2990 ** [SQLCIPHER_OPEN_NOMUTEX], [SQLCIPHER_OPEN_FULLMUTEX], [SQLCIPHER_OPEN_SHAREDCACHE],
2991 ** [SQLCIPHER_OPEN_PRIVATECACHE], and/or [SQLCIPHER_OPEN_URI] flags:)^
2992 **
2993 ** <dl>
2994 ** ^(<dt>[SQLCIPHER_OPEN_READONLY]</dt>
2995 ** <dd>The database is opened in read-only mode.  If the database does not
2996 ** already exist, an error is returned.</dd>)^
2997 **
2998 ** ^(<dt>[SQLCIPHER_OPEN_READWRITE]</dt>
2999 ** <dd>The database is opened for reading and writing if possible, or reading
3000 ** only if the file is write protected by the operating system.  In either
3001 ** case the database must already exist, otherwise an error is returned.</dd>)^
3002 **
3003 ** ^(<dt>[SQLCIPHER_OPEN_READWRITE] | [SQLCIPHER_OPEN_CREATE]</dt>
3004 ** <dd>The database is opened for reading and writing, and is created if
3005 ** it does not already exist. This is the behavior that is always used for
3006 ** sqlcipher3_open() and sqlcipher3_open16().</dd>)^
3007 ** </dl>
3008 **
3009 ** If the 3rd parameter to sqlcipher3_open_v2() is not one of the
3010 ** combinations shown above optionally combined with other
3011 ** [SQLCIPHER_OPEN_READONLY | SQLCIPHER_OPEN_* bits]
3012 ** then the behavior is undefined.
3013 **
3014 ** ^If the [SQLCIPHER_OPEN_NOMUTEX] flag is set, then the database connection
3015 ** opens in the multi-thread [threading mode] as long as the single-thread
3016 ** mode has not been set at compile-time or start-time.  ^If the
3017 ** [SQLCIPHER_OPEN_FULLMUTEX] flag is set then the database connection opens
3018 ** in the serialized [threading mode] unless single-thread was
3019 ** previously selected at compile-time or start-time.
3020 ** ^The [SQLCIPHER_OPEN_SHAREDCACHE] flag causes the database connection to be
3021 ** eligible to use [shared cache mode], regardless of whether or not shared
3022 ** cache is enabled using [sqlcipher3_enable_shared_cache()].  ^The
3023 ** [SQLCIPHER_OPEN_PRIVATECACHE] flag causes the database connection to not
3024 ** participate in [shared cache mode] even if it is enabled.
3025 **
3026 ** ^The fourth parameter to sqlcipher3_open_v2() is the name of the
3027 ** [sqlcipher3_vfs] object that defines the operating system interface that
3028 ** the new database connection should use.  ^If the fourth parameter is
3029 ** a NULL pointer then the default [sqlcipher3_vfs] object is used.
3030 **
3031 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3032 ** is created for the connection.  ^This in-memory database will vanish when
3033 ** the database connection is closed.  Future versions of SQLite might
3034 ** make use of additional special filenames that begin with the ":" character.
3035 ** It is recommended that when a database filename actually does begin with
3036 ** a ":" character you should prefix the filename with a pathname such as
3037 ** "./" to avoid ambiguity.
3038 **
3039 ** ^If the filename is an empty string, then a private, temporary
3040 ** on-disk database will be created.  ^This private database will be
3041 ** automatically deleted as soon as the database connection is closed.
3042 **
3043 ** [[URI filenames in sqlcipher3_open()]] <h3>URI Filenames</h3>
3044 **
3045 ** ^If [URI filename] interpretation is enabled, and the filename argument
3046 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3047 ** filename interpretation is enabled if the [SQLCIPHER_OPEN_URI] flag is
3048 ** set in the fourth argument to sqlcipher3_open_v2(), or if it has
3049 ** been enabled globally using the [SQLCIPHER_CONFIG_URI] option with the
3050 ** [sqlcipher3_config()] method or by the [SQLCIPHER_USE_URI] compile-time option.
3051 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3052 ** by default, but future releases of SQLite might enable URI filename
3053 ** interpretation by default.  See "[URI filenames]" for additional
3054 ** information.
3055 **
3056 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3057 ** authority, then it must be either an empty string or the string 
3058 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3059 ** error is returned to the caller. ^The fragment component of a URI, if 
3060 ** present, is ignored.
3061 **
3062 ** ^SQLite uses the path component of the URI as the name of the disk file
3063 ** which contains the database. ^If the path begins with a '/' character, 
3064 ** then it is interpreted as an absolute path. ^If the path does not begin 
3065 ** with a '/' (meaning that the authority section is omitted from the URI)
3066 ** then the path is interpreted as a relative path. 
3067 ** ^On windows, the first component of an absolute path 
3068 ** is a drive specification (e.g. "C:").
3069 **
3070 ** [[core URI query parameters]]
3071 ** The query component of a URI may contain parameters that are interpreted
3072 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3073 ** SQLite interprets the following three query parameters:
3074 **
3075 ** <ul>
3076 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3077 **     a VFS object that provides the operating system interface that should
3078 **     be used to access the database file on disk. ^If this option is set to
3079 **     an empty string the default VFS object is used. ^Specifying an unknown
3080 **     VFS is an error. ^If sqlcipher3_open_v2() is used and the vfs option is
3081 **     present, then the VFS specified by the option takes precedence over
3082 **     the value passed as the fourth parameter to sqlcipher3_open_v2().
3083 **
3084 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3085 **     "rwc". Attempting to set it to any other value is an error)^. 
3086 **     ^If "ro" is specified, then the database is opened for read-only 
3087 **     access, just as if the [SQLCIPHER_OPEN_READONLY] flag had been set in the 
3088 **     third argument to sqlcipher3_prepare_v2(). ^If the mode option is set to 
3089 **     "rw", then the database is opened for read-write (but not create) 
3090 **     access, as if SQLCIPHER_OPEN_READWRITE (but not SQLCIPHER_OPEN_CREATE) had 
3091 **     been set. ^Value "rwc" is equivalent to setting both 
3092 **     SQLCIPHER_OPEN_READWRITE and SQLCIPHER_OPEN_CREATE. ^If sqlcipher3_open_v2() is 
3093 **     used, it is an error to specify a value for the mode parameter that is 
3094 **     less restrictive than that specified by the flags passed as the third 
3095 **     parameter.
3096 **
3097 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3098 **     "private". ^Setting it to "shared" is equivalent to setting the
3099 **     SQLCIPHER_OPEN_SHAREDCACHE bit in the flags argument passed to
3100 **     sqlcipher3_open_v2(). ^Setting the cache parameter to "private" is 
3101 **     equivalent to setting the SQLCIPHER_OPEN_PRIVATECACHE bit.
3102 **     ^If sqlcipher3_open_v2() is used and the "cache" parameter is present in
3103 **     a URI filename, its value overrides any behaviour requested by setting
3104 **     SQLCIPHER_OPEN_PRIVATECACHE or SQLCIPHER_OPEN_SHAREDCACHE flag.
3105 ** </ul>
3106 **
3107 ** ^Specifying an unknown parameter in the query component of a URI is not an
3108 ** error.  Future versions of SQLite might understand additional query
3109 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3110 ** additional information.
3111 **
3112 ** [[URI filename examples]] <h3>URI filename examples</h3>
3113 **
3114 ** <table border="1" align=center cellpadding=5>
3115 ** <tr><th> URI filenames <th> Results
3116 ** <tr><td> file:data.db <td> 
3117 **          Open the file "data.db" in the current directory.
3118 ** <tr><td> file:/home/fred/data.db<br>
3119 **          file:///home/fred/data.db <br> 
3120 **          file://localhost/home/fred/data.db <br> <td> 
3121 **          Open the database file "/home/fred/data.db".
3122 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3123 **          An error. "darkstar" is not a recognized authority.
3124 ** <tr><td style="white-space:nowrap"> 
3125 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3126 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3127 **          C:. Note that the %20 escaping in this example is not strictly 
3128 **          necessary - space characters can be used literally
3129 **          in URI filenames.
3130 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3131 **          Open file "data.db" in the current directory for read-only access.
3132 **          Regardless of whether or not shared-cache mode is enabled by
3133 **          default, use a private cache.
3134 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3135 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3136 ** <tr><td> file:data.db?mode=readonly <td> 
3137 **          An error. "readonly" is not a valid option for the "mode" parameter.
3138 ** </table>
3139 **
3140 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3141 ** query components of a URI. A hexadecimal escape sequence consists of a
3142 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3143 ** specifying an octet value. ^Before the path or query components of a
3144 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3145 ** hexadecimal escape sequences replaced by a single byte containing the
3146 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3147 ** the results are undefined.
3148 **
3149 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3150 ** of sqlcipher3_open() and sqlcipher3_open_v2() must be UTF-8, not whatever
3151 ** codepage is currently defined.  Filenames containing international
3152 ** characters must be converted to UTF-8 prior to passing them into
3153 ** sqlcipher3_open() or sqlcipher3_open_v2().
3154 */
3155 SQLCIPHER_API int sqlcipher3_open(
3156   const char *filename,   /* Database filename (UTF-8) */
3157   sqlcipher3 **ppDb          /* OUT: SQLite db handle */
3158 );
3159 SQLCIPHER_API int sqlcipher3_open16(
3160   const void *filename,   /* Database filename (UTF-16) */
3161   sqlcipher3 **ppDb          /* OUT: SQLite db handle */
3162 );
3163 SQLCIPHER_API int sqlcipher3_open_v2(
3164   const char *filename,   /* Database filename (UTF-8) */
3165   sqlcipher3 **ppDb,         /* OUT: SQLite db handle */
3166   int flags,              /* Flags */
3167   const char *zVfs        /* Name of VFS module to use */
3168 );
3169
3170 /*
3171 ** CAPI3REF: Obtain Values For URI Parameters
3172 **
3173 ** This is a utility routine, useful to VFS implementations, that checks
3174 ** to see if a database file was a URI that contained a specific query 
3175 ** parameter, and if so obtains the value of the query parameter.
3176 **
3177 ** The zFilename argument is the filename pointer passed into the xOpen()
3178 ** method of a VFS implementation.  The zParam argument is the name of the
3179 ** query parameter we seek.  This routine returns the value of the zParam
3180 ** parameter if it exists.  If the parameter does not exist, this routine
3181 ** returns a NULL pointer.
3182 **
3183 ** If the zFilename argument to this function is not a pointer that SQLite
3184 ** passed into the xOpen VFS method, then the behavior of this routine
3185 ** is undefined and probably undesirable.
3186 */
3187 SQLCIPHER_API const char *sqlcipher3_uri_parameter(const char *zFilename, const char *zParam);
3188
3189
3190 /*
3191 ** CAPI3REF: Error Codes And Messages
3192 **
3193 ** ^The sqlcipher3_errcode() interface returns the numeric [result code] or
3194 ** [extended result code] for the most recent failed sqlcipher3_* API call
3195 ** associated with a [database connection]. If a prior API call failed
3196 ** but the most recent API call succeeded, the return value from
3197 ** sqlcipher3_errcode() is undefined.  ^The sqlcipher3_extended_errcode()
3198 ** interface is the same except that it always returns the 
3199 ** [extended result code] even when extended result codes are
3200 ** disabled.
3201 **
3202 ** ^The sqlcipher3_errmsg() and sqlcipher3_errmsg16() return English-language
3203 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3204 ** ^(Memory to hold the error message string is managed internally.
3205 ** The application does not need to worry about freeing the result.
3206 ** However, the error string might be overwritten or deallocated by
3207 ** subsequent calls to other SQLite interface functions.)^
3208 **
3209 ** When the serialized [threading mode] is in use, it might be the
3210 ** case that a second error occurs on a separate thread in between
3211 ** the time of the first error and the call to these interfaces.
3212 ** When that happens, the second error will be reported since these
3213 ** interfaces always report the most recent result.  To avoid
3214 ** this, each thread can obtain exclusive use of the [database connection] D
3215 ** by invoking [sqlcipher3_mutex_enter]([sqlcipher3_db_mutex](D)) before beginning
3216 ** to use D and invoking [sqlcipher3_mutex_leave]([sqlcipher3_db_mutex](D)) after
3217 ** all calls to the interfaces listed here are completed.
3218 **
3219 ** If an interface fails with SQLCIPHER_MISUSE, that means the interface
3220 ** was invoked incorrectly by the application.  In that case, the
3221 ** error code and message may or may not be set.
3222 */
3223 SQLCIPHER_API int sqlcipher3_errcode(sqlcipher3 *db);
3224 SQLCIPHER_API int sqlcipher3_extended_errcode(sqlcipher3 *db);
3225 SQLCIPHER_API const char *sqlcipher3_errmsg(sqlcipher3*);
3226 SQLCIPHER_API const void *sqlcipher3_errmsg16(sqlcipher3*);
3227
3228 /*
3229 ** CAPI3REF: SQL Statement Object
3230 ** KEYWORDS: {prepared statement} {prepared statements}
3231 **
3232 ** An instance of this object represents a single SQL statement.
3233 ** This object is variously known as a "prepared statement" or a
3234 ** "compiled SQL statement" or simply as a "statement".
3235 **
3236 ** The life of a statement object goes something like this:
3237 **
3238 ** <ol>
3239 ** <li> Create the object using [sqlcipher3_prepare_v2()] or a related
3240 **      function.
3241 ** <li> Bind values to [host parameters] using the sqlcipher3_bind_*()
3242 **      interfaces.
3243 ** <li> Run the SQL by calling [sqlcipher3_step()] one or more times.
3244 ** <li> Reset the statement using [sqlcipher3_reset()] then go back
3245 **      to step 2.  Do this zero or more times.
3246 ** <li> Destroy the object using [sqlcipher3_finalize()].
3247 ** </ol>
3248 **
3249 ** Refer to documentation on individual methods above for additional
3250 ** information.
3251 */
3252 typedef struct sqlcipher3_stmt sqlcipher3_stmt;
3253
3254 /*
3255 ** CAPI3REF: Run-time Limits
3256 **
3257 ** ^(This interface allows the size of various constructs to be limited
3258 ** on a connection by connection basis.  The first parameter is the
3259 ** [database connection] whose limit is to be set or queried.  The
3260 ** second parameter is one of the [limit categories] that define a
3261 ** class of constructs to be size limited.  The third parameter is the
3262 ** new limit for that construct.)^
3263 **
3264 ** ^If the new limit is a negative number, the limit is unchanged.
3265 ** ^(For each limit category SQLCIPHER_LIMIT_<i>NAME</i> there is a 
3266 ** [limits | hard upper bound]
3267 ** set at compile-time by a C preprocessor macro called
3268 ** [limits | SQLCIPHER_MAX_<i>NAME</i>].
3269 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3270 ** ^Attempts to increase a limit above its hard upper bound are
3271 ** silently truncated to the hard upper bound.
3272 **
3273 ** ^Regardless of whether or not the limit was changed, the 
3274 ** [sqlcipher3_limit()] interface returns the prior value of the limit.
3275 ** ^Hence, to find the current value of a limit without changing it,
3276 ** simply invoke this interface with the third parameter set to -1.
3277 **
3278 ** Run-time limits are intended for use in applications that manage
3279 ** both their own internal database and also databases that are controlled
3280 ** by untrusted external sources.  An example application might be a
3281 ** web browser that has its own databases for storing history and
3282 ** separate databases controlled by JavaScript applications downloaded
3283 ** off the Internet.  The internal databases can be given the
3284 ** large, default limits.  Databases managed by external sources can
3285 ** be given much smaller limits designed to prevent a denial of service
3286 ** attack.  Developers might also want to use the [sqlcipher3_set_authorizer()]
3287 ** interface to further control untrusted SQL.  The size of the database
3288 ** created by an untrusted script can be contained using the
3289 ** [max_page_count] [PRAGMA].
3290 **
3291 ** New run-time limit categories may be added in future releases.
3292 */
3293 SQLCIPHER_API int sqlcipher3_limit(sqlcipher3*, int id, int newVal);
3294
3295 /*
3296 ** CAPI3REF: Run-Time Limit Categories
3297 ** KEYWORDS: {limit category} {*limit categories}
3298 **
3299 ** These constants define various performance limits
3300 ** that can be lowered at run-time using [sqlcipher3_limit()].
3301 ** The synopsis of the meanings of the various limits is shown below.
3302 ** Additional information is available at [limits | Limits in SQLite].
3303 **
3304 ** <dl>
3305 ** [[SQLCIPHER_LIMIT_LENGTH]] ^(<dt>SQLCIPHER_LIMIT_LENGTH</dt>
3306 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3307 **
3308 ** [[SQLCIPHER_LIMIT_SQL_LENGTH]] ^(<dt>SQLCIPHER_LIMIT_SQL_LENGTH</dt>
3309 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3310 **
3311 ** [[SQLCIPHER_LIMIT_COLUMN]] ^(<dt>SQLCIPHER_LIMIT_COLUMN</dt>
3312 ** <dd>The maximum number of columns in a table definition or in the
3313 ** result set of a [SELECT] or the maximum number of columns in an index
3314 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3315 **
3316 ** [[SQLCIPHER_LIMIT_EXPR_DEPTH]] ^(<dt>SQLCIPHER_LIMIT_EXPR_DEPTH</dt>
3317 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3318 **
3319 ** [[SQLCIPHER_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLCIPHER_LIMIT_COMPOUND_SELECT</dt>
3320 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3321 **
3322 ** [[SQLCIPHER_LIMIT_VDBE_OP]] ^(<dt>SQLCIPHER_LIMIT_VDBE_OP</dt>
3323 ** <dd>The maximum number of instructions in a virtual machine program
3324 ** used to implement an SQL statement.  This limit is not currently
3325 ** enforced, though that might be added in some future release of
3326 ** SQLite.</dd>)^
3327 **
3328 ** [[SQLCIPHER_LIMIT_FUNCTION_ARG]] ^(<dt>SQLCIPHER_LIMIT_FUNCTION_ARG</dt>
3329 ** <dd>The maximum number of arguments on a function.</dd>)^
3330 **
3331 ** [[SQLCIPHER_LIMIT_ATTACHED]] ^(<dt>SQLCIPHER_LIMIT_ATTACHED</dt>
3332 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3333 **
3334 ** [[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH]]
3335 ** ^(<dt>SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH</dt>
3336 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3337 ** [GLOB] operators.</dd>)^
3338 **
3339 ** [[SQLCIPHER_LIMIT_VARIABLE_NUMBER]]
3340 ** ^(<dt>SQLCIPHER_LIMIT_VARIABLE_NUMBER</dt>
3341 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3342 **
3343 ** [[SQLCIPHER_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLCIPHER_LIMIT_TRIGGER_DEPTH</dt>
3344 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3345 ** </dl>
3346 */
3347 #define SQLCIPHER_LIMIT_LENGTH                    0
3348 #define SQLCIPHER_LIMIT_SQL_LENGTH                1
3349 #define SQLCIPHER_LIMIT_COLUMN                    2
3350 #define SQLCIPHER_LIMIT_EXPR_DEPTH                3
3351 #define SQLCIPHER_LIMIT_COMPOUND_SELECT           4
3352 #define SQLCIPHER_LIMIT_VDBE_OP                   5
3353 #define SQLCIPHER_LIMIT_FUNCTION_ARG              6
3354 #define SQLCIPHER_LIMIT_ATTACHED                  7
3355 #define SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH       8
3356 #define SQLCIPHER_LIMIT_VARIABLE_NUMBER           9
3357 #define SQLCIPHER_LIMIT_TRIGGER_DEPTH            10
3358
3359 /*
3360 ** CAPI3REF: Compiling An SQL Statement
3361 ** KEYWORDS: {SQL statement compiler}
3362 **
3363 ** To execute an SQL query, it must first be compiled into a byte-code
3364 ** program using one of these routines.
3365 **
3366 ** The first argument, "db", is a [database connection] obtained from a
3367 ** prior successful call to [sqlcipher3_open()], [sqlcipher3_open_v2()] or
3368 ** [sqlcipher3_open16()].  The database connection must not have been closed.
3369 **
3370 ** The second argument, "zSql", is the statement to be compiled, encoded
3371 ** as either UTF-8 or UTF-16.  The sqlcipher3_prepare() and sqlcipher3_prepare_v2()
3372 ** interfaces use UTF-8, and sqlcipher3_prepare16() and sqlcipher3_prepare16_v2()
3373 ** use UTF-16.
3374 **
3375 ** ^If the nByte argument is less than zero, then zSql is read up to the
3376 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3377 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3378 ** zSql string ends at either the first '\000' or '\u0000' character or
3379 ** the nByte-th byte, whichever comes first. If the caller knows
3380 ** that the supplied string is nul-terminated, then there is a small
3381 ** performance advantage to be gained by passing an nByte parameter that
3382 ** is equal to the number of bytes in the input string <i>including</i>
3383 ** the nul-terminator bytes as this saves SQLite from having to
3384 ** make a copy of the input string.
3385 **
3386 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3387 ** past the end of the first SQL statement in zSql.  These routines only
3388 ** compile the first statement in zSql, so *pzTail is left pointing to
3389 ** what remains uncompiled.
3390 **
3391 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3392 ** executed using [sqlcipher3_step()].  ^If there is an error, *ppStmt is set
3393 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3394 ** string or a comment) then *ppStmt is set to NULL.
3395 ** The calling procedure is responsible for deleting the compiled
3396 ** SQL statement using [sqlcipher3_finalize()] after it has finished with it.
3397 ** ppStmt may not be NULL.
3398 **
3399 ** ^On success, the sqlcipher3_prepare() family of routines return [SQLCIPHER_OK];
3400 ** otherwise an [error code] is returned.
3401 **
3402 ** The sqlcipher3_prepare_v2() and sqlcipher3_prepare16_v2() interfaces are
3403 ** recommended for all new programs. The two older interfaces are retained
3404 ** for backwards compatibility, but their use is discouraged.
3405 ** ^In the "v2" interfaces, the prepared statement
3406 ** that is returned (the [sqlcipher3_stmt] object) contains a copy of the
3407 ** original SQL text. This causes the [sqlcipher3_step()] interface to
3408 ** behave differently in three ways:
3409 **
3410 ** <ol>
3411 ** <li>
3412 ** ^If the database schema changes, instead of returning [SQLCIPHER_SCHEMA] as it
3413 ** always used to do, [sqlcipher3_step()] will automatically recompile the SQL
3414 ** statement and try to run it again.
3415 ** </li>
3416 **
3417 ** <li>
3418 ** ^When an error occurs, [sqlcipher3_step()] will return one of the detailed
3419 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3420 ** [sqlcipher3_step()] would only return a generic [SQLCIPHER_ERROR] result code
3421 ** and the application would have to make a second call to [sqlcipher3_reset()]
3422 ** in order to find the underlying cause of the problem. With the "v2" prepare
3423 ** interfaces, the underlying reason for the error is returned immediately.
3424 ** </li>
3425 **
3426 ** <li>
3427 ** ^If the specific value bound to [parameter | host parameter] in the 
3428 ** WHERE clause might influence the choice of query plan for a statement,
3429 ** then the statement will be automatically recompiled, as if there had been 
3430 ** a schema change, on the first  [sqlcipher3_step()] call following any change
3431 ** to the [sqlcipher3_bind_text | bindings] of that [parameter]. 
3432 ** ^The specific value of WHERE-clause [parameter] might influence the 
3433 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3434 ** or [GLOB] operator or if the parameter is compared to an indexed column
3435 ** and the [SQLCIPHER_ENABLE_STAT3] compile-time option is enabled.
3436 ** the 
3437 ** </li>
3438 ** </ol>
3439 */
3440 SQLCIPHER_API int sqlcipher3_prepare(
3441   sqlcipher3 *db,            /* Database handle */
3442   const char *zSql,       /* SQL statement, UTF-8 encoded */
3443   int nByte,              /* Maximum length of zSql in bytes. */
3444   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3445   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3446 );
3447 SQLCIPHER_API int sqlcipher3_prepare_v2(
3448   sqlcipher3 *db,            /* Database handle */
3449   const char *zSql,       /* SQL statement, UTF-8 encoded */
3450   int nByte,              /* Maximum length of zSql in bytes. */
3451   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3452   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3453 );
3454 SQLCIPHER_API int sqlcipher3_prepare16(
3455   sqlcipher3 *db,            /* Database handle */
3456   const void *zSql,       /* SQL statement, UTF-16 encoded */
3457   int nByte,              /* Maximum length of zSql in bytes. */
3458   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3459   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3460 );
3461 SQLCIPHER_API int sqlcipher3_prepare16_v2(
3462   sqlcipher3 *db,            /* Database handle */
3463   const void *zSql,       /* SQL statement, UTF-16 encoded */
3464   int nByte,              /* Maximum length of zSql in bytes. */
3465   sqlcipher3_stmt **ppStmt,  /* OUT: Statement handle */
3466   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3467 );
3468
3469 /*
3470 ** CAPI3REF: Retrieving Statement SQL
3471 **
3472 ** ^This interface can be used to retrieve a saved copy of the original
3473 ** SQL text used to create a [prepared statement] if that statement was
3474 ** compiled using either [sqlcipher3_prepare_v2()] or [sqlcipher3_prepare16_v2()].
3475 */
3476 SQLCIPHER_API const char *sqlcipher3_sql(sqlcipher3_stmt *pStmt);
3477
3478 /*
3479 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3480 **
3481 ** ^The sqlcipher3_stmt_readonly(X) interface returns true (non-zero) if
3482 ** and only if the [prepared statement] X makes no direct changes to
3483 ** the content of the database file.
3484 **
3485 ** Note that [application-defined SQL functions] or
3486 ** [virtual tables] might change the database indirectly as a side effect.  
3487 ** ^(For example, if an application defines a function "eval()" that 
3488 ** calls [sqlcipher3_exec()], then the following SQL statement would
3489 ** change the database file through side-effects:
3490 **
3491 ** <blockquote><pre>
3492 **    SELECT eval('DELETE FROM t1') FROM t2;
3493 ** </pre></blockquote>
3494 **
3495 ** But because the [SELECT] statement does not change the database file
3496 ** directly, sqlcipher3_stmt_readonly() would still return true.)^
3497 **
3498 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3499 ** [SAVEPOINT], and [RELEASE] cause sqlcipher3_stmt_readonly() to return true,
3500 ** since the statements themselves do not actually modify the database but
3501 ** rather they control the timing of when other statements modify the 
3502 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3503 ** sqlcipher3_stmt_readonly() to return true since, while those statements
3504 ** change the configuration of a database connection, they do not make 
3505 ** changes to the content of the database files on disk.
3506 */
3507 SQLCIPHER_API int sqlcipher3_stmt_readonly(sqlcipher3_stmt *pStmt);
3508
3509 /*
3510 ** CAPI3REF: Dynamically Typed Value Object
3511 ** KEYWORDS: {protected sqlcipher3_value} {unprotected sqlcipher3_value}
3512 **
3513 ** SQLite uses the sqlcipher3_value object to represent all values
3514 ** that can be stored in a database table. SQLite uses dynamic typing
3515 ** for the values it stores.  ^Values stored in sqlcipher3_value objects
3516 ** can be integers, floating point values, strings, BLOBs, or NULL.
3517 **
3518 ** An sqlcipher3_value object may be either "protected" or "unprotected".
3519 ** Some interfaces require a protected sqlcipher3_value.  Other interfaces
3520 ** will accept either a protected or an unprotected sqlcipher3_value.
3521 ** Every interface that accepts sqlcipher3_value arguments specifies
3522 ** whether or not it requires a protected sqlcipher3_value.
3523 **
3524 ** The terms "protected" and "unprotected" refer to whether or not
3525 ** a mutex is held.  An internal mutex is held for a protected
3526 ** sqlcipher3_value object but no mutex is held for an unprotected
3527 ** sqlcipher3_value object.  If SQLite is compiled to be single-threaded
3528 ** (with [SQLCIPHER_THREADSAFE=0] and with [sqlcipher3_threadsafe()] returning 0)
3529 ** or if SQLite is run in one of reduced mutex modes 
3530 ** [SQLCIPHER_CONFIG_SINGLETHREAD] or [SQLCIPHER_CONFIG_MULTITHREAD]
3531 ** then there is no distinction between protected and unprotected
3532 ** sqlcipher3_value objects and they can be used interchangeably.  However,
3533 ** for maximum code portability it is recommended that applications
3534 ** still make the distinction between protected and unprotected
3535 ** sqlcipher3_value objects even when not strictly required.
3536 **
3537 ** ^The sqlcipher3_value objects that are passed as parameters into the
3538 ** implementation of [application-defined SQL functions] are protected.
3539 ** ^The sqlcipher3_value object returned by
3540 ** [sqlcipher3_column_value()] is unprotected.
3541 ** Unprotected sqlcipher3_value objects may only be used with
3542 ** [sqlcipher3_result_value()] and [sqlcipher3_bind_value()].
3543 ** The [sqlcipher3_value_blob | sqlcipher3_value_type()] family of
3544 ** interfaces require protected sqlcipher3_value objects.
3545 */
3546 typedef struct Mem sqlcipher3_value;
3547
3548 /*
3549 ** CAPI3REF: SQL Function Context Object
3550 **
3551 ** The context in which an SQL function executes is stored in an
3552 ** sqlcipher3_context object.  ^A pointer to an sqlcipher3_context object
3553 ** is always first parameter to [application-defined SQL functions].
3554 ** The application-defined SQL function implementation will pass this
3555 ** pointer through into calls to [sqlcipher3_result_int | sqlcipher3_result()],
3556 ** [sqlcipher3_aggregate_context()], [sqlcipher3_user_data()],
3557 ** [sqlcipher3_context_db_handle()], [sqlcipher3_get_auxdata()],
3558 ** and/or [sqlcipher3_set_auxdata()].
3559 */
3560 typedef struct sqlcipher3_context sqlcipher3_context;
3561
3562 /*
3563 ** CAPI3REF: Binding Values To Prepared Statements
3564 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3565 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3566 **
3567 ** ^(In the SQL statement text input to [sqlcipher3_prepare_v2()] and its variants,
3568 ** literals may be replaced by a [parameter] that matches one of following
3569 ** templates:
3570 **
3571 ** <ul>
3572 ** <li>  ?
3573 ** <li>  ?NNN
3574 ** <li>  :VVV
3575 ** <li>  @VVV
3576 ** <li>  $VVV
3577 ** </ul>
3578 **
3579 ** In the templates above, NNN represents an integer literal,
3580 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3581 ** parameters (also called "host parameter names" or "SQL parameters")
3582 ** can be set using the sqlcipher3_bind_*() routines defined here.
3583 **
3584 ** ^The first argument to the sqlcipher3_bind_*() routines is always
3585 ** a pointer to the [sqlcipher3_stmt] object returned from
3586 ** [sqlcipher3_prepare_v2()] or its variants.
3587 **
3588 ** ^The second argument is the index of the SQL parameter to be set.
3589 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3590 ** SQL parameter is used more than once, second and subsequent
3591 ** occurrences have the same index as the first occurrence.
3592 ** ^The index for named parameters can be looked up using the
3593 ** [sqlcipher3_bind_parameter_index()] API if desired.  ^The index
3594 ** for "?NNN" parameters is the value of NNN.
3595 ** ^The NNN value must be between 1 and the [sqlcipher3_limit()]
3596 ** parameter [SQLCIPHER_LIMIT_VARIABLE_NUMBER] (default value: 999).
3597 **
3598 ** ^The third argument is the value to bind to the parameter.
3599 **
3600 ** ^(In those routines that have a fourth argument, its value is the
3601 ** number of bytes in the parameter.  To be clear: the value is the
3602 ** number of <u>bytes</u> in the value, not the number of characters.)^
3603 ** ^If the fourth parameter is negative, the length of the string is
3604 ** the number of bytes up to the first zero terminator.
3605 ** If a non-negative fourth parameter is provided to sqlcipher3_bind_text()
3606 ** or sqlcipher3_bind_text16() then that parameter must be the byte offset
3607 ** where the NUL terminator would occur assuming the string were NUL
3608 ** terminated.  If any NUL characters occur at byte offsets less than 
3609 ** the value of the fourth parameter then the resulting string value will
3610 ** contain embedded NULs.  The result of expressions involving strings
3611 ** with embedded NULs is undefined.
3612 **
3613 ** ^The fifth argument to sqlcipher3_bind_blob(), sqlcipher3_bind_text(), and
3614 ** sqlcipher3_bind_text16() is a destructor used to dispose of the BLOB or
3615 ** string after SQLite has finished with it.  ^The destructor is called
3616 ** to dispose of the BLOB or string even if the call to sqlcipher3_bind_blob(),
3617 ** sqlcipher3_bind_text(), or sqlcipher3_bind_text16() fails.  
3618 ** ^If the fifth argument is
3619 ** the special value [SQLCIPHER_STATIC], then SQLite assumes that the
3620 ** information is in static, unmanaged space and does not need to be freed.
3621 ** ^If the fifth argument has the value [SQLCIPHER_TRANSIENT], then
3622 ** SQLite makes its own private copy of the data immediately, before
3623 ** the sqlcipher3_bind_*() routine returns.
3624 **
3625 ** ^The sqlcipher3_bind_zeroblob() routine binds a BLOB of length N that
3626 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3627 ** (just an integer to hold its size) while it is being processed.
3628 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3629 ** content is later written using
3630 ** [sqlcipher3_blob_open | incremental BLOB I/O] routines.
3631 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3632 **
3633 ** ^If any of the sqlcipher3_bind_*() routines are called with a NULL pointer
3634 ** for the [prepared statement] or with a prepared statement for which
3635 ** [sqlcipher3_step()] has been called more recently than [sqlcipher3_reset()],
3636 ** then the call will return [SQLCIPHER_MISUSE].  If any sqlcipher3_bind_()
3637 ** routine is passed a [prepared statement] that has been finalized, the
3638 ** result is undefined and probably harmful.
3639 **
3640 ** ^Bindings are not cleared by the [sqlcipher3_reset()] routine.
3641 ** ^Unbound parameters are interpreted as NULL.
3642 **
3643 ** ^The sqlcipher3_bind_* routines return [SQLCIPHER_OK] on success or an
3644 ** [error code] if anything goes wrong.
3645 ** ^[SQLCIPHER_RANGE] is returned if the parameter
3646 ** index is out of range.  ^[SQLCIPHER_NOMEM] is returned if malloc() fails.
3647 **
3648 ** See also: [sqlcipher3_bind_parameter_count()],
3649 ** [sqlcipher3_bind_parameter_name()], and [sqlcipher3_bind_parameter_index()].
3650 */
3651 SQLCIPHER_API int sqlcipher3_bind_blob(sqlcipher3_stmt*, int, const void*, int n, void(*)(void*));
3652 SQLCIPHER_API int sqlcipher3_bind_double(sqlcipher3_stmt*, int, double);
3653 SQLCIPHER_API int sqlcipher3_bind_int(sqlcipher3_stmt*, int, int);
3654 SQLCIPHER_API int sqlcipher3_bind_int64(sqlcipher3_stmt*, int, sqlcipher3_int64);
3655 SQLCIPHER_API int sqlcipher3_bind_null(sqlcipher3_stmt*, int);
3656 SQLCIPHER_API int sqlcipher3_bind_text(sqlcipher3_stmt*, int, const char*, int n, void(*)(void*));
3657 SQLCIPHER_API int sqlcipher3_bind_text16(sqlcipher3_stmt*, int, const void*, int, void(*)(void*));
3658 SQLCIPHER_API int sqlcipher3_bind_value(sqlcipher3_stmt*, int, const sqlcipher3_value*);
3659 SQLCIPHER_API int sqlcipher3_bind_zeroblob(sqlcipher3_stmt*, int, int n);
3660
3661 /*
3662 ** CAPI3REF: Number Of SQL Parameters
3663 **
3664 ** ^This routine can be used to find the number of [SQL parameters]
3665 ** in a [prepared statement].  SQL parameters are tokens of the
3666 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3667 ** placeholders for values that are [sqlcipher3_bind_blob | bound]
3668 ** to the parameters at a later time.
3669 **
3670 ** ^(This routine actually returns the index of the largest (rightmost)
3671 ** parameter. For all forms except ?NNN, this will correspond to the
3672 ** number of unique parameters.  If parameters of the ?NNN form are used,
3673 ** there may be gaps in the list.)^
3674 **
3675 ** See also: [sqlcipher3_bind_blob|sqlcipher3_bind()],
3676 ** [sqlcipher3_bind_parameter_name()], and
3677 ** [sqlcipher3_bind_parameter_index()].
3678 */
3679 SQLCIPHER_API int sqlcipher3_bind_parameter_count(sqlcipher3_stmt*);
3680
3681 /*
3682 ** CAPI3REF: Name Of A Host Parameter
3683 **
3684 ** ^The sqlcipher3_bind_parameter_name(P,N) interface returns
3685 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3686 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3687 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3688 ** respectively.
3689 ** In other words, the initial ":" or "$" or "@" or "?"
3690 ** is included as part of the name.)^
3691 ** ^Parameters of the form "?" without a following integer have no name
3692 ** and are referred to as "nameless" or "anonymous parameters".
3693 **
3694 ** ^The first host parameter has an index of 1, not 0.
3695 **
3696 ** ^If the value N is out of range or if the N-th parameter is
3697 ** nameless, then NULL is returned.  ^The returned string is
3698 ** always in UTF-8 encoding even if the named parameter was
3699 ** originally specified as UTF-16 in [sqlcipher3_prepare16()] or
3700 ** [sqlcipher3_prepare16_v2()].
3701 **
3702 ** See also: [sqlcipher3_bind_blob|sqlcipher3_bind()],
3703 ** [sqlcipher3_bind_parameter_count()], and
3704 ** [sqlcipher3_bind_parameter_index()].
3705 */
3706 SQLCIPHER_API const char *sqlcipher3_bind_parameter_name(sqlcipher3_stmt*, int);
3707
3708 /*
3709 ** CAPI3REF: Index Of A Parameter With A Given Name
3710 **
3711 ** ^Return the index of an SQL parameter given its name.  ^The
3712 ** index value returned is suitable for use as the second
3713 ** parameter to [sqlcipher3_bind_blob|sqlcipher3_bind()].  ^A zero
3714 ** is returned if no matching parameter is found.  ^The parameter
3715 ** name must be given in UTF-8 even if the original statement
3716 ** was prepared from UTF-16 text using [sqlcipher3_prepare16_v2()].
3717 **
3718 ** See also: [sqlcipher3_bind_blob|sqlcipher3_bind()],
3719 ** [sqlcipher3_bind_parameter_count()], and
3720 ** [sqlcipher3_bind_parameter_index()].
3721 */
3722 SQLCIPHER_API int sqlcipher3_bind_parameter_index(sqlcipher3_stmt*, const char *zName);
3723
3724 /*
3725 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3726 **
3727 ** ^Contrary to the intuition of many, [sqlcipher3_reset()] does not reset
3728 ** the [sqlcipher3_bind_blob | bindings] on a [prepared statement].
3729 ** ^Use this routine to reset all host parameters to NULL.
3730 */
3731 SQLCIPHER_API int sqlcipher3_clear_bindings(sqlcipher3_stmt*);
3732
3733 /*
3734 ** CAPI3REF: Number Of Columns In A Result Set
3735 **
3736 ** ^Return the number of columns in the result set returned by the
3737 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3738 ** statement that does not return data (for example an [UPDATE]).
3739 **
3740 ** See also: [sqlcipher3_data_count()]
3741 */
3742 SQLCIPHER_API int sqlcipher3_column_count(sqlcipher3_stmt *pStmt);
3743
3744 /*
3745 ** CAPI3REF: Column Names In A Result Set
3746 **
3747 ** ^These routines return the name assigned to a particular column
3748 ** in the result set of a [SELECT] statement.  ^The sqlcipher3_column_name()
3749 ** interface returns a pointer to a zero-terminated UTF-8 string
3750 ** and sqlcipher3_column_name16() returns a pointer to a zero-terminated
3751 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3752 ** that implements the [SELECT] statement. ^The second parameter is the
3753 ** column number.  ^The leftmost column is number 0.
3754 **
3755 ** ^The returned string pointer is valid until either the [prepared statement]
3756 ** is destroyed by [sqlcipher3_finalize()] or until the statement is automatically
3757 ** reprepared by the first call to [sqlcipher3_step()] for a particular run
3758 ** or until the next call to
3759 ** sqlcipher3_column_name() or sqlcipher3_column_name16() on the same column.
3760 **
3761 ** ^If sqlcipher3_malloc() fails during the processing of either routine
3762 ** (for example during a conversion from UTF-8 to UTF-16) then a
3763 ** NULL pointer is returned.
3764 **
3765 ** ^The name of a result column is the value of the "AS" clause for
3766 ** that column, if there is an AS clause.  If there is no AS clause
3767 ** then the name of the column is unspecified and may change from
3768 ** one release of SQLite to the next.
3769 */
3770 SQLCIPHER_API const char *sqlcipher3_column_name(sqlcipher3_stmt*, int N);
3771 SQLCIPHER_API const void *sqlcipher3_column_name16(sqlcipher3_stmt*, int N);
3772
3773 /*
3774 ** CAPI3REF: Source Of Data In A Query Result
3775 **
3776 ** ^These routines provide a means to determine the database, table, and
3777 ** table column that is the origin of a particular result column in
3778 ** [SELECT] statement.
3779 ** ^The name of the database or table or column can be returned as
3780 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3781 ** the database name, the _table_ routines return the table name, and
3782 ** the origin_ routines return the column name.
3783 ** ^The returned string is valid until the [prepared statement] is destroyed
3784 ** using [sqlcipher3_finalize()] or until the statement is automatically
3785 ** reprepared by the first call to [sqlcipher3_step()] for a particular run
3786 ** or until the same information is requested
3787 ** again in a different encoding.
3788 **
3789 ** ^The names returned are the original un-aliased names of the
3790 ** database, table, and column.
3791 **
3792 ** ^The first argument to these interfaces is a [prepared statement].
3793 ** ^These functions return information about the Nth result column returned by
3794 ** the statement, where N is the second function argument.
3795 ** ^The left-most column is column 0 for these routines.
3796 **
3797 ** ^If the Nth column returned by the statement is an expression or
3798 ** subquery and is not a column value, then all of these functions return
3799 ** NULL.  ^These routine might also return NULL if a memory allocation error
3800 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3801 ** or column that query result column was extracted from.
3802 **
3803 ** ^As with all other SQLite APIs, those whose names end with "16" return
3804 ** UTF-16 encoded strings and the other functions return UTF-8.
3805 **
3806 ** ^These APIs are only available if the library was compiled with the
3807 ** [SQLCIPHER_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3808 **
3809 ** If two or more threads call one or more of these routines against the same
3810 ** prepared statement and column at the same time then the results are
3811 ** undefined.
3812 **
3813 ** If two or more threads call one or more
3814 ** [sqlcipher3_column_database_name | column metadata interfaces]
3815 ** for the same [prepared statement] and result column
3816 ** at the same time then the results are undefined.
3817 */
3818 SQLCIPHER_API const char *sqlcipher3_column_database_name(sqlcipher3_stmt*,int);
3819 SQLCIPHER_API const void *sqlcipher3_column_database_name16(sqlcipher3_stmt*,int);
3820 SQLCIPHER_API const char *sqlcipher3_column_table_name(sqlcipher3_stmt*,int);
3821 SQLCIPHER_API const void *sqlcipher3_column_table_name16(sqlcipher3_stmt*,int);
3822 SQLCIPHER_API const char *sqlcipher3_column_origin_name(sqlcipher3_stmt*,int);
3823 SQLCIPHER_API const void *sqlcipher3_column_origin_name16(sqlcipher3_stmt*,int);
3824
3825 /*
3826 ** CAPI3REF: Declared Datatype Of A Query Result
3827 **
3828 ** ^(The first parameter is a [prepared statement].
3829 ** If this statement is a [SELECT] statement and the Nth column of the
3830 ** returned result set of that [SELECT] is a table column (not an
3831 ** expression or subquery) then the declared type of the table
3832 ** column is returned.)^  ^If the Nth column of the result set is an
3833 ** expression or subquery, then a NULL pointer is returned.
3834 ** ^The returned string is always UTF-8 encoded.
3835 **
3836 ** ^(For example, given the database schema:
3837 **
3838 ** CREATE TABLE t1(c1 VARIANT);
3839 **
3840 ** and the following statement to be compiled:
3841 **
3842 ** SELECT c1 + 1, c1 FROM t1;
3843 **
3844 ** this routine would return the string "VARIANT" for the second result
3845 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3846 **
3847 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3848 ** is declared to contain a particular type does not mean that the
3849 ** data stored in that column is of the declared type.  SQLite is
3850 ** strongly typed, but the typing is dynamic not static.  ^Type
3851 ** is associated with individual values, not with the containers
3852 ** used to hold those values.
3853 */
3854 SQLCIPHER_API const char *sqlcipher3_column_decltype(sqlcipher3_stmt*,int);
3855 SQLCIPHER_API const void *sqlcipher3_column_decltype16(sqlcipher3_stmt*,int);
3856
3857 /*
3858 ** CAPI3REF: Evaluate An SQL Statement
3859 **
3860 ** After a [prepared statement] has been prepared using either
3861 ** [sqlcipher3_prepare_v2()] or [sqlcipher3_prepare16_v2()] or one of the legacy
3862 ** interfaces [sqlcipher3_prepare()] or [sqlcipher3_prepare16()], this function
3863 ** must be called one or more times to evaluate the statement.
3864 **
3865 ** The details of the behavior of the sqlcipher3_step() interface depend
3866 ** on whether the statement was prepared using the newer "v2" interface
3867 ** [sqlcipher3_prepare_v2()] and [sqlcipher3_prepare16_v2()] or the older legacy
3868 ** interface [sqlcipher3_prepare()] and [sqlcipher3_prepare16()].  The use of the
3869 ** new "v2" interface is recommended for new applications but the legacy
3870 ** interface will continue to be supported.
3871 **
3872 ** ^In the legacy interface, the return value will be either [SQLCIPHER_BUSY],
3873 ** [SQLCIPHER_DONE], [SQLCIPHER_ROW], [SQLCIPHER_ERROR], or [SQLCIPHER_MISUSE].
3874 ** ^With the "v2" interface, any of the other [result codes] or
3875 ** [extended result codes] might be returned as well.
3876 **
3877 ** ^[SQLCIPHER_BUSY] means that the database engine was unable to acquire the
3878 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3879 ** or occurs outside of an explicit transaction, then you can retry the
3880 ** statement.  If the statement is not a [COMMIT] and occurs within an
3881 ** explicit transaction then you should rollback the transaction before
3882 ** continuing.
3883 **
3884 ** ^[SQLCIPHER_DONE] means that the statement has finished executing
3885 ** successfully.  sqlcipher3_step() should not be called again on this virtual
3886 ** machine without first calling [sqlcipher3_reset()] to reset the virtual
3887 ** machine back to its initial state.
3888 **
3889 ** ^If the SQL statement being executed returns any data, then [SQLCIPHER_ROW]
3890 ** is returned each time a new row of data is ready for processing by the
3891 ** caller. The values may be accessed using the [column access functions].
3892 ** sqlcipher3_step() is called again to retrieve the next row of data.
3893 **
3894 ** ^[SQLCIPHER_ERROR] means that a run-time error (such as a constraint
3895 ** violation) has occurred.  sqlcipher3_step() should not be called again on
3896 ** the VM. More information may be found by calling [sqlcipher3_errmsg()].
3897 ** ^With the legacy interface, a more specific error code (for example,
3898 ** [SQLCIPHER_INTERRUPT], [SQLCIPHER_SCHEMA], [SQLCIPHER_CORRUPT], and so forth)
3899 ** can be obtained by calling [sqlcipher3_reset()] on the
3900 ** [prepared statement].  ^In the "v2" interface,
3901 ** the more specific error code is returned directly by sqlcipher3_step().
3902 **
3903 ** [SQLCIPHER_MISUSE] means that the this routine was called inappropriately.
3904 ** Perhaps it was called on a [prepared statement] that has
3905 ** already been [sqlcipher3_finalize | finalized] or on one that had
3906 ** previously returned [SQLCIPHER_ERROR] or [SQLCIPHER_DONE].  Or it could
3907 ** be the case that the same database connection is being used by two or
3908 ** more threads at the same moment in time.
3909 **
3910 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3911 ** [sqlcipher3_reset()] was required after sqlcipher3_step() returned anything
3912 ** other than [SQLCIPHER_ROW] before any subsequent invocation of
3913 ** sqlcipher3_step().  Failure to reset the prepared statement using 
3914 ** [sqlcipher3_reset()] would result in an [SQLCIPHER_MISUSE] return from
3915 ** sqlcipher3_step().  But after version 3.6.23.1, sqlcipher3_step() began
3916 ** calling [sqlcipher3_reset()] automatically in this circumstance rather
3917 ** than returning [SQLCIPHER_MISUSE].  This is not considered a compatibility
3918 ** break because any application that ever receives an SQLCIPHER_MISUSE error
3919 ** is broken by definition.  The [SQLCIPHER_OMIT_AUTORESET] compile-time option
3920 ** can be used to restore the legacy behavior.
3921 **
3922 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlcipher3_step()
3923 ** API always returns a generic error code, [SQLCIPHER_ERROR], following any
3924 ** error other than [SQLCIPHER_BUSY] and [SQLCIPHER_MISUSE].  You must call
3925 ** [sqlcipher3_reset()] or [sqlcipher3_finalize()] in order to find one of the
3926 ** specific [error codes] that better describes the error.
3927 ** We admit that this is a goofy design.  The problem has been fixed
3928 ** with the "v2" interface.  If you prepare all of your SQL statements
3929 ** using either [sqlcipher3_prepare_v2()] or [sqlcipher3_prepare16_v2()] instead
3930 ** of the legacy [sqlcipher3_prepare()] and [sqlcipher3_prepare16()] interfaces,
3931 ** then the more specific [error codes] are returned directly
3932 ** by sqlcipher3_step().  The use of the "v2" interface is recommended.
3933 */
3934 SQLCIPHER_API int sqlcipher3_step(sqlcipher3_stmt*);
3935
3936 /*
3937 ** CAPI3REF: Number of columns in a result set
3938 **
3939 ** ^The sqlcipher3_data_count(P) interface returns the number of columns in the
3940 ** current row of the result set of [prepared statement] P.
3941 ** ^If prepared statement P does not have results ready to return
3942 ** (via calls to the [sqlcipher3_column_int | sqlcipher3_column_*()] of
3943 ** interfaces) then sqlcipher3_data_count(P) returns 0.
3944 ** ^The sqlcipher3_data_count(P) routine also returns 0 if P is a NULL pointer.
3945 ** ^The sqlcipher3_data_count(P) routine returns 0 if the previous call to
3946 ** [sqlcipher3_step](P) returned [SQLCIPHER_DONE].  ^The sqlcipher3_data_count(P)
3947 ** will return non-zero if previous call to [sqlcipher3_step](P) returned
3948 ** [SQLCIPHER_ROW], except in the case of the [PRAGMA incremental_vacuum]
3949 ** where it always returns zero since each step of that multi-step
3950 ** pragma returns 0 columns of data.
3951 **
3952 ** See also: [sqlcipher3_column_count()]
3953 */
3954 SQLCIPHER_API int sqlcipher3_data_count(sqlcipher3_stmt *pStmt);
3955
3956 /*
3957 ** CAPI3REF: Fundamental Datatypes
3958 ** KEYWORDS: SQLCIPHER_TEXT
3959 **
3960 ** ^(Every value in SQLite has one of five fundamental datatypes:
3961 **
3962 ** <ul>
3963 ** <li> 64-bit signed integer
3964 ** <li> 64-bit IEEE floating point number
3965 ** <li> string
3966 ** <li> BLOB
3967 ** <li> NULL
3968 ** </ul>)^
3969 **
3970 ** These constants are codes for each of those types.
3971 **
3972 ** Note that the SQLCIPHER_TEXT constant was also used in SQLite version 2
3973 ** for a completely different meaning.  Software that links against both
3974 ** SQLite version 2 and SQLite version 3 should use SQLCIPHER3_TEXT, not
3975 ** SQLCIPHER_TEXT.
3976 */
3977 #define SQLCIPHER_INTEGER  1
3978 #define SQLCIPHER_FLOAT    2
3979 #define SQLCIPHER_BLOB     4
3980 #define SQLCIPHER_NULL     5
3981 #ifdef SQLCIPHER_TEXT
3982 # undef SQLCIPHER_TEXT
3983 #else
3984 # define SQLCIPHER_TEXT     3
3985 #endif
3986 #define SQLCIPHER3_TEXT     3
3987
3988 /*
3989 ** CAPI3REF: Result Values From A Query
3990 ** KEYWORDS: {column access functions}
3991 **
3992 ** These routines form the "result set" interface.
3993 **
3994 ** ^These routines return information about a single column of the current
3995 ** result row of a query.  ^In every case the first argument is a pointer
3996 ** to the [prepared statement] that is being evaluated (the [sqlcipher3_stmt*]
3997 ** that was returned from [sqlcipher3_prepare_v2()] or one of its variants)
3998 ** and the second argument is the index of the column for which information
3999 ** should be returned. ^The leftmost column of the result set has the index 0.
4000 ** ^The number of columns in the result can be determined using
4001 ** [sqlcipher3_column_count()].
4002 **
4003 ** If the SQL statement does not currently point to a valid row, or if the
4004 ** column index is out of range, the result is undefined.
4005 ** These routines may only be called when the most recent call to
4006 ** [sqlcipher3_step()] has returned [SQLCIPHER_ROW] and neither
4007 ** [sqlcipher3_reset()] nor [sqlcipher3_finalize()] have been called subsequently.
4008 ** If any of these routines are called after [sqlcipher3_reset()] or
4009 ** [sqlcipher3_finalize()] or after [sqlcipher3_step()] has returned
4010 ** something other than [SQLCIPHER_ROW], the results are undefined.
4011 ** If [sqlcipher3_step()] or [sqlcipher3_reset()] or [sqlcipher3_finalize()]
4012 ** are called from a different thread while any of these routines
4013 ** are pending, then the results are undefined.
4014 **
4015 ** ^The sqlcipher3_column_type() routine returns the
4016 ** [SQLCIPHER_INTEGER | datatype code] for the initial data type
4017 ** of the result column.  ^The returned value is one of [SQLCIPHER_INTEGER],
4018 ** [SQLCIPHER_FLOAT], [SQLCIPHER_TEXT], [SQLCIPHER_BLOB], or [SQLCIPHER_NULL].  The value
4019 ** returned by sqlcipher3_column_type() is only meaningful if no type
4020 ** conversions have occurred as described below.  After a type conversion,
4021 ** the value returned by sqlcipher3_column_type() is undefined.  Future
4022 ** versions of SQLite may change the behavior of sqlcipher3_column_type()
4023 ** following a type conversion.
4024 **
4025 ** ^If the result is a BLOB or UTF-8 string then the sqlcipher3_column_bytes()
4026 ** routine returns the number of bytes in that BLOB or string.
4027 ** ^If the result is a UTF-16 string, then sqlcipher3_column_bytes() converts
4028 ** the string to UTF-8 and then returns the number of bytes.
4029 ** ^If the result is a numeric value then sqlcipher3_column_bytes() uses
4030 ** [sqlcipher3_snprintf()] to convert that value to a UTF-8 string and returns
4031 ** the number of bytes in that string.
4032 ** ^If the result is NULL, then sqlcipher3_column_bytes() returns zero.
4033 **
4034 ** ^If the result is a BLOB or UTF-16 string then the sqlcipher3_column_bytes16()
4035 ** routine returns the number of bytes in that BLOB or string.
4036 ** ^If the result is a UTF-8 string, then sqlcipher3_column_bytes16() converts
4037 ** the string to UTF-16 and then returns the number of bytes.
4038 ** ^If the result is a numeric value then sqlcipher3_column_bytes16() uses
4039 ** [sqlcipher3_snprintf()] to convert that value to a UTF-16 string and returns
4040 ** the number of bytes in that string.
4041 ** ^If the result is NULL, then sqlcipher3_column_bytes16() returns zero.
4042 **
4043 ** ^The values returned by [sqlcipher3_column_bytes()] and 
4044 ** [sqlcipher3_column_bytes16()] do not include the zero terminators at the end
4045 ** of the string.  ^For clarity: the values returned by
4046 ** [sqlcipher3_column_bytes()] and [sqlcipher3_column_bytes16()] are the number of
4047 ** bytes in the string, not the number of characters.
4048 **
4049 ** ^Strings returned by sqlcipher3_column_text() and sqlcipher3_column_text16(),
4050 ** even empty strings, are always zero terminated.  ^The return
4051 ** value from sqlcipher3_column_blob() for a zero-length BLOB is a NULL pointer.
4052 **
4053 ** ^The object returned by [sqlcipher3_column_value()] is an
4054 ** [unprotected sqlcipher3_value] object.  An unprotected sqlcipher3_value object
4055 ** may only be used with [sqlcipher3_bind_value()] and [sqlcipher3_result_value()].
4056 ** If the [unprotected sqlcipher3_value] object returned by
4057 ** [sqlcipher3_column_value()] is used in any other way, including calls
4058 ** to routines like [sqlcipher3_value_int()], [sqlcipher3_value_text()],
4059 ** or [sqlcipher3_value_bytes()], then the behavior is undefined.
4060 **
4061 ** These routines attempt to convert the value where appropriate.  ^For
4062 ** example, if the internal representation is FLOAT and a text result
4063 ** is requested, [sqlcipher3_snprintf()] is used internally to perform the
4064 ** conversion automatically.  ^(The following table details the conversions
4065 ** that are applied:
4066 **
4067 ** <blockquote>
4068 ** <table border="1">
4069 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4070 **
4071 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4072 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4073 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4074 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4075 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4076 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4077 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4078 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4079 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4080 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4081 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4082 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4083 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4084 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4085 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4086 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4087 ** </table>
4088 ** </blockquote>)^
4089 **
4090 ** The table above makes reference to standard C library functions atoi()
4091 ** and atof().  SQLite does not really use these functions.  It has its
4092 ** own equivalent internal routines.  The atoi() and atof() names are
4093 ** used in the table for brevity and because they are familiar to most
4094 ** C programmers.
4095 **
4096 ** Note that when type conversions occur, pointers returned by prior
4097 ** calls to sqlcipher3_column_blob(), sqlcipher3_column_text(), and/or
4098 ** sqlcipher3_column_text16() may be invalidated.
4099 ** Type conversions and pointer invalidations might occur
4100 ** in the following cases:
4101 **
4102 ** <ul>
4103 ** <li> The initial content is a BLOB and sqlcipher3_column_text() or
4104 **      sqlcipher3_column_text16() is called.  A zero-terminator might
4105 **      need to be added to the string.</li>
4106 ** <li> The initial content is UTF-8 text and sqlcipher3_column_bytes16() or
4107 **      sqlcipher3_column_text16() is called.  The content must be converted
4108 **      to UTF-16.</li>
4109 ** <li> The initial content is UTF-16 text and sqlcipher3_column_bytes() or
4110 **      sqlcipher3_column_text() is called.  The content must be converted
4111 **      to UTF-8.</li>
4112 ** </ul>
4113 **
4114 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4115 ** not invalidate a prior pointer, though of course the content of the buffer
4116 ** that the prior pointer references will have been modified.  Other kinds
4117 ** of conversion are done in place when it is possible, but sometimes they
4118 ** are not possible and in those cases prior pointers are invalidated.
4119 **
4120 ** The safest and easiest to remember policy is to invoke these routines
4121 ** in one of the following ways:
4122 **
4123 ** <ul>
4124 **  <li>sqlcipher3_column_text() followed by sqlcipher3_column_bytes()</li>
4125 **  <li>sqlcipher3_column_blob() followed by sqlcipher3_column_bytes()</li>
4126 **  <li>sqlcipher3_column_text16() followed by sqlcipher3_column_bytes16()</li>
4127 ** </ul>
4128 **
4129 ** In other words, you should call sqlcipher3_column_text(),
4130 ** sqlcipher3_column_blob(), or sqlcipher3_column_text16() first to force the result
4131 ** into the desired format, then invoke sqlcipher3_column_bytes() or
4132 ** sqlcipher3_column_bytes16() to find the size of the result.  Do not mix calls
4133 ** to sqlcipher3_column_text() or sqlcipher3_column_blob() with calls to
4134 ** sqlcipher3_column_bytes16(), and do not mix calls to sqlcipher3_column_text16()
4135 ** with calls to sqlcipher3_column_bytes().
4136 **
4137 ** ^The pointers returned are valid until a type conversion occurs as
4138 ** described above, or until [sqlcipher3_step()] or [sqlcipher3_reset()] or
4139 ** [sqlcipher3_finalize()] is called.  ^The memory space used to hold strings
4140 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4141 ** [sqlcipher3_column_blob()], [sqlcipher3_column_text()], etc. into
4142 ** [sqlcipher3_free()].
4143 **
4144 ** ^(If a memory allocation error occurs during the evaluation of any
4145 ** of these routines, a default value is returned.  The default value
4146 ** is either the integer 0, the floating point number 0.0, or a NULL
4147 ** pointer.  Subsequent calls to [sqlcipher3_errcode()] will return
4148 ** [SQLCIPHER_NOMEM].)^
4149 */
4150 SQLCIPHER_API const void *sqlcipher3_column_blob(sqlcipher3_stmt*, int iCol);
4151 SQLCIPHER_API int sqlcipher3_column_bytes(sqlcipher3_stmt*, int iCol);
4152 SQLCIPHER_API int sqlcipher3_column_bytes16(sqlcipher3_stmt*, int iCol);
4153 SQLCIPHER_API double sqlcipher3_column_double(sqlcipher3_stmt*, int iCol);
4154 SQLCIPHER_API int sqlcipher3_column_int(sqlcipher3_stmt*, int iCol);
4155 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_column_int64(sqlcipher3_stmt*, int iCol);
4156 SQLCIPHER_API const unsigned char *sqlcipher3_column_text(sqlcipher3_stmt*, int iCol);
4157 SQLCIPHER_API const void *sqlcipher3_column_text16(sqlcipher3_stmt*, int iCol);
4158 SQLCIPHER_API int sqlcipher3_column_type(sqlcipher3_stmt*, int iCol);
4159 SQLCIPHER_API sqlcipher3_value *sqlcipher3_column_value(sqlcipher3_stmt*, int iCol);
4160
4161 /*
4162 ** CAPI3REF: Destroy A Prepared Statement Object
4163 **
4164 ** ^The sqlcipher3_finalize() function is called to delete a [prepared statement].
4165 ** ^If the most recent evaluation of the statement encountered no errors
4166 ** or if the statement is never been evaluated, then sqlcipher3_finalize() returns
4167 ** SQLCIPHER_OK.  ^If the most recent evaluation of statement S failed, then
4168 ** sqlcipher3_finalize(S) returns the appropriate [error code] or
4169 ** [extended error code].
4170 **
4171 ** ^The sqlcipher3_finalize(S) routine can be called at any point during
4172 ** the life cycle of [prepared statement] S:
4173 ** before statement S is ever evaluated, after
4174 ** one or more calls to [sqlcipher3_reset()], or after any call
4175 ** to [sqlcipher3_step()] regardless of whether or not the statement has
4176 ** completed execution.
4177 **
4178 ** ^Invoking sqlcipher3_finalize() on a NULL pointer is a harmless no-op.
4179 **
4180 ** The application must finalize every [prepared statement] in order to avoid
4181 ** resource leaks.  It is a grievous error for the application to try to use
4182 ** a prepared statement after it has been finalized.  Any use of a prepared
4183 ** statement after it has been finalized can result in undefined and
4184 ** undesirable behavior such as segfaults and heap corruption.
4185 */
4186 SQLCIPHER_API int sqlcipher3_finalize(sqlcipher3_stmt *pStmt);
4187
4188 /*
4189 ** CAPI3REF: Reset A Prepared Statement Object
4190 **
4191 ** The sqlcipher3_reset() function is called to reset a [prepared statement]
4192 ** object back to its initial state, ready to be re-executed.
4193 ** ^Any SQL statement variables that had values bound to them using
4194 ** the [sqlcipher3_bind_blob | sqlcipher3_bind_*() API] retain their values.
4195 ** Use [sqlcipher3_clear_bindings()] to reset the bindings.
4196 **
4197 ** ^The [sqlcipher3_reset(S)] interface resets the [prepared statement] S
4198 ** back to the beginning of its program.
4199 **
4200 ** ^If the most recent call to [sqlcipher3_step(S)] for the
4201 ** [prepared statement] S returned [SQLCIPHER_ROW] or [SQLCIPHER_DONE],
4202 ** or if [sqlcipher3_step(S)] has never before been called on S,
4203 ** then [sqlcipher3_reset(S)] returns [SQLCIPHER_OK].
4204 **
4205 ** ^If the most recent call to [sqlcipher3_step(S)] for the
4206 ** [prepared statement] S indicated an error, then
4207 ** [sqlcipher3_reset(S)] returns an appropriate [error code].
4208 **
4209 ** ^The [sqlcipher3_reset(S)] interface does not change the values
4210 ** of any [sqlcipher3_bind_blob|bindings] on the [prepared statement] S.
4211 */
4212 SQLCIPHER_API int sqlcipher3_reset(sqlcipher3_stmt *pStmt);
4213
4214 /*
4215 ** CAPI3REF: Create Or Redefine SQL Functions
4216 ** KEYWORDS: {function creation routines}
4217 ** KEYWORDS: {application-defined SQL function}
4218 ** KEYWORDS: {application-defined SQL functions}
4219 **
4220 ** ^These functions (collectively known as "function creation routines")
4221 ** are used to add SQL functions or aggregates or to redefine the behavior
4222 ** of existing SQL functions or aggregates.  The only differences between
4223 ** these routines are the text encoding expected for
4224 ** the second parameter (the name of the function being created)
4225 ** and the presence or absence of a destructor callback for
4226 ** the application data pointer.
4227 **
4228 ** ^The first parameter is the [database connection] to which the SQL
4229 ** function is to be added.  ^If an application uses more than one database
4230 ** connection then application-defined SQL functions must be added
4231 ** to each database connection separately.
4232 **
4233 ** ^The second parameter is the name of the SQL function to be created or
4234 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4235 ** representation, exclusive of the zero-terminator.  ^Note that the name
4236 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4237 ** ^Any attempt to create a function with a longer name
4238 ** will result in [SQLCIPHER_MISUSE] being returned.
4239 **
4240 ** ^The third parameter (nArg)
4241 ** is the number of arguments that the SQL function or
4242 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4243 ** aggregate may take any number of arguments between 0 and the limit
4244 ** set by [sqlcipher3_limit]([SQLCIPHER_LIMIT_FUNCTION_ARG]).  If the third
4245 ** parameter is less than -1 or greater than 127 then the behavior is
4246 ** undefined.
4247 **
4248 ** ^The fourth parameter, eTextRep, specifies what
4249 ** [SQLCIPHER_UTF8 | text encoding] this SQL function prefers for
4250 ** its parameters.  Every SQL function implementation must be able to work
4251 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4252 ** more efficient with one encoding than another.  ^An application may
4253 ** invoke sqlcipher3_create_function() or sqlcipher3_create_function16() multiple
4254 ** times with the same function but with different values of eTextRep.
4255 ** ^When multiple implementations of the same function are available, SQLite
4256 ** will pick the one that involves the least amount of data conversion.
4257 ** If there is only a single implementation which does not care what text
4258 ** encoding is used, then the fourth argument should be [SQLCIPHER_ANY].
4259 **
4260 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4261 ** function can gain access to this pointer using [sqlcipher3_user_data()].)^
4262 **
4263 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4264 ** pointers to C-language functions that implement the SQL function or
4265 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4266 ** callback only; NULL pointers must be passed as the xStep and xFinal
4267 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4268 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4269 ** SQL function or aggregate, pass NULL pointers for all three function
4270 ** callbacks.
4271 **
4272 ** ^(If the ninth parameter to sqlcipher3_create_function_v2() is not NULL,
4273 ** then it is destructor for the application data pointer. 
4274 ** The destructor is invoked when the function is deleted, either by being
4275 ** overloaded or when the database connection closes.)^
4276 ** ^The destructor is also invoked if the call to
4277 ** sqlcipher3_create_function_v2() fails.
4278 ** ^When the destructor callback of the tenth parameter is invoked, it
4279 ** is passed a single argument which is a copy of the application data 
4280 ** pointer which was the fifth parameter to sqlcipher3_create_function_v2().
4281 **
4282 ** ^It is permitted to register multiple implementations of the same
4283 ** functions with the same name but with either differing numbers of
4284 ** arguments or differing preferred text encodings.  ^SQLite will use
4285 ** the implementation that most closely matches the way in which the
4286 ** SQL function is used.  ^A function implementation with a non-negative
4287 ** nArg parameter is a better match than a function implementation with
4288 ** a negative nArg.  ^A function where the preferred text encoding
4289 ** matches the database encoding is a better
4290 ** match than a function where the encoding is different.  
4291 ** ^A function where the encoding difference is between UTF16le and UTF16be
4292 ** is a closer match than a function where the encoding difference is
4293 ** between UTF8 and UTF16.
4294 **
4295 ** ^Built-in functions may be overloaded by new application-defined functions.
4296 **
4297 ** ^An application-defined function is permitted to call other
4298 ** SQLite interfaces.  However, such calls must not
4299 ** close the database connection nor finalize or reset the prepared
4300 ** statement in which the function is running.
4301 */
4302 SQLCIPHER_API int sqlcipher3_create_function(
4303   sqlcipher3 *db,
4304   const char *zFunctionName,
4305   int nArg,
4306   int eTextRep,
4307   void *pApp,
4308   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
4309   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
4310   void (*xFinal)(sqlcipher3_context*)
4311 );
4312 SQLCIPHER_API int sqlcipher3_create_function16(
4313   sqlcipher3 *db,
4314   const void *zFunctionName,
4315   int nArg,
4316   int eTextRep,
4317   void *pApp,
4318   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
4319   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
4320   void (*xFinal)(sqlcipher3_context*)
4321 );
4322 SQLCIPHER_API int sqlcipher3_create_function_v2(
4323   sqlcipher3 *db,
4324   const char *zFunctionName,
4325   int nArg,
4326   int eTextRep,
4327   void *pApp,
4328   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
4329   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
4330   void (*xFinal)(sqlcipher3_context*),
4331   void(*xDestroy)(void*)
4332 );
4333
4334 /*
4335 ** CAPI3REF: Text Encodings
4336 **
4337 ** These constant define integer codes that represent the various
4338 ** text encodings supported by SQLite.
4339 */
4340 #define SQLCIPHER_UTF8           1
4341 #define SQLCIPHER_UTF16LE        2
4342 #define SQLCIPHER_UTF16BE        3
4343 #define SQLCIPHER_UTF16          4    /* Use native byte order */
4344 #define SQLCIPHER_ANY            5    /* sqlcipher3_create_function only */
4345 #define SQLCIPHER_UTF16_ALIGNED  8    /* sqlcipher3_create_collation only */
4346
4347 /*
4348 ** CAPI3REF: Deprecated Functions
4349 ** DEPRECATED
4350 **
4351 ** These functions are [deprecated].  In order to maintain
4352 ** backwards compatibility with older code, these functions continue 
4353 ** to be supported.  However, new applications should avoid
4354 ** the use of these functions.  To help encourage people to avoid
4355 ** using these functions, we are not going to tell you what they do.
4356 */
4357 #ifndef SQLCIPHER_OMIT_DEPRECATED
4358 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_aggregate_count(sqlcipher3_context*);
4359 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_expired(sqlcipher3_stmt*);
4360 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_transfer_bindings(sqlcipher3_stmt*, sqlcipher3_stmt*);
4361 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_global_recover(void);
4362 SQLCIPHER_API SQLCIPHER_DEPRECATED void sqlcipher3_thread_cleanup(void);
4363 SQLCIPHER_API SQLCIPHER_DEPRECATED int sqlcipher3_memory_alarm(void(*)(void*,sqlcipher3_int64,int),void*,sqlcipher3_int64);
4364 #endif
4365
4366 /*
4367 ** CAPI3REF: Obtaining SQL Function Parameter Values
4368 **
4369 ** The C-language implementation of SQL functions and aggregates uses
4370 ** this set of interface routines to access the parameter values on
4371 ** the function or aggregate.
4372 **
4373 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4374 ** to [sqlcipher3_create_function()] and [sqlcipher3_create_function16()]
4375 ** define callbacks that implement the SQL functions and aggregates.
4376 ** The 3rd parameter to these callbacks is an array of pointers to
4377 ** [protected sqlcipher3_value] objects.  There is one [sqlcipher3_value] object for
4378 ** each parameter to the SQL function.  These routines are used to
4379 ** extract values from the [sqlcipher3_value] objects.
4380 **
4381 ** These routines work only with [protected sqlcipher3_value] objects.
4382 ** Any attempt to use these routines on an [unprotected sqlcipher3_value]
4383 ** object results in undefined behavior.
4384 **
4385 ** ^These routines work just like the corresponding [column access functions]
4386 ** except that  these routines take a single [protected sqlcipher3_value] object
4387 ** pointer instead of a [sqlcipher3_stmt*] pointer and an integer column number.
4388 **
4389 ** ^The sqlcipher3_value_text16() interface extracts a UTF-16 string
4390 ** in the native byte-order of the host machine.  ^The
4391 ** sqlcipher3_value_text16be() and sqlcipher3_value_text16le() interfaces
4392 ** extract UTF-16 strings as big-endian and little-endian respectively.
4393 **
4394 ** ^(The sqlcipher3_value_numeric_type() interface attempts to apply
4395 ** numeric affinity to the value.  This means that an attempt is
4396 ** made to convert the value to an integer or floating point.  If
4397 ** such a conversion is possible without loss of information (in other
4398 ** words, if the value is a string that looks like a number)
4399 ** then the conversion is performed.  Otherwise no conversion occurs.
4400 ** The [SQLCIPHER_INTEGER | datatype] after conversion is returned.)^
4401 **
4402 ** Please pay particular attention to the fact that the pointer returned
4403 ** from [sqlcipher3_value_blob()], [sqlcipher3_value_text()], or
4404 ** [sqlcipher3_value_text16()] can be invalidated by a subsequent call to
4405 ** [sqlcipher3_value_bytes()], [sqlcipher3_value_bytes16()], [sqlcipher3_value_text()],
4406 ** or [sqlcipher3_value_text16()].
4407 **
4408 ** These routines must be called from the same thread as
4409 ** the SQL function that supplied the [sqlcipher3_value*] parameters.
4410 */
4411 SQLCIPHER_API const void *sqlcipher3_value_blob(sqlcipher3_value*);
4412 SQLCIPHER_API int sqlcipher3_value_bytes(sqlcipher3_value*);
4413 SQLCIPHER_API int sqlcipher3_value_bytes16(sqlcipher3_value*);
4414 SQLCIPHER_API double sqlcipher3_value_double(sqlcipher3_value*);
4415 SQLCIPHER_API int sqlcipher3_value_int(sqlcipher3_value*);
4416 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_value_int64(sqlcipher3_value*);
4417 SQLCIPHER_API const unsigned char *sqlcipher3_value_text(sqlcipher3_value*);
4418 SQLCIPHER_API const void *sqlcipher3_value_text16(sqlcipher3_value*);
4419 SQLCIPHER_API const void *sqlcipher3_value_text16le(sqlcipher3_value*);
4420 SQLCIPHER_API const void *sqlcipher3_value_text16be(sqlcipher3_value*);
4421 SQLCIPHER_API int sqlcipher3_value_type(sqlcipher3_value*);
4422 SQLCIPHER_API int sqlcipher3_value_numeric_type(sqlcipher3_value*);
4423
4424 /*
4425 ** CAPI3REF: Obtain Aggregate Function Context
4426 **
4427 ** Implementations of aggregate SQL functions use this
4428 ** routine to allocate memory for storing their state.
4429 **
4430 ** ^The first time the sqlcipher3_aggregate_context(C,N) routine is called 
4431 ** for a particular aggregate function, SQLite
4432 ** allocates N of memory, zeroes out that memory, and returns a pointer
4433 ** to the new memory. ^On second and subsequent calls to
4434 ** sqlcipher3_aggregate_context() for the same aggregate function instance,
4435 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4436 ** called once for each invocation of the xStep callback and then one
4437 ** last time when the xFinal callback is invoked.  ^(When no rows match
4438 ** an aggregate query, the xStep() callback of the aggregate function
4439 ** implementation is never called and xFinal() is called exactly once.
4440 ** In those cases, sqlcipher3_aggregate_context() might be called for the
4441 ** first time from within xFinal().)^
4442 **
4443 ** ^The sqlcipher3_aggregate_context(C,N) routine returns a NULL pointer if N is
4444 ** less than or equal to zero or if a memory allocate error occurs.
4445 **
4446 ** ^(The amount of space allocated by sqlcipher3_aggregate_context(C,N) is
4447 ** determined by the N parameter on first successful call.  Changing the
4448 ** value of N in subsequent call to sqlcipher3_aggregate_context() within
4449 ** the same aggregate function instance will not resize the memory
4450 ** allocation.)^
4451 **
4452 ** ^SQLite automatically frees the memory allocated by 
4453 ** sqlcipher3_aggregate_context() when the aggregate query concludes.
4454 **
4455 ** The first parameter must be a copy of the
4456 ** [sqlcipher3_context | SQL function context] that is the first parameter
4457 ** to the xStep or xFinal callback routine that implements the aggregate
4458 ** function.
4459 **
4460 ** This routine must be called from the same thread in which
4461 ** the aggregate SQL function is running.
4462 */
4463 SQLCIPHER_API void *sqlcipher3_aggregate_context(sqlcipher3_context*, int nBytes);
4464
4465 /*
4466 ** CAPI3REF: User Data For Functions
4467 **
4468 ** ^The sqlcipher3_user_data() interface returns a copy of
4469 ** the pointer that was the pUserData parameter (the 5th parameter)
4470 ** of the [sqlcipher3_create_function()]
4471 ** and [sqlcipher3_create_function16()] routines that originally
4472 ** registered the application defined function.
4473 **
4474 ** This routine must be called from the same thread in which
4475 ** the application-defined function is running.
4476 */
4477 SQLCIPHER_API void *sqlcipher3_user_data(sqlcipher3_context*);
4478
4479 /*
4480 ** CAPI3REF: Database Connection For Functions
4481 **
4482 ** ^The sqlcipher3_context_db_handle() interface returns a copy of
4483 ** the pointer to the [database connection] (the 1st parameter)
4484 ** of the [sqlcipher3_create_function()]
4485 ** and [sqlcipher3_create_function16()] routines that originally
4486 ** registered the application defined function.
4487 */
4488 SQLCIPHER_API sqlcipher3 *sqlcipher3_context_db_handle(sqlcipher3_context*);
4489
4490 /*
4491 ** CAPI3REF: Function Auxiliary Data
4492 **
4493 ** The following two functions may be used by scalar SQL functions to
4494 ** associate metadata with argument values. If the same value is passed to
4495 ** multiple invocations of the same SQL function during query execution, under
4496 ** some circumstances the associated metadata may be preserved. This may
4497 ** be used, for example, to add a regular-expression matching scalar
4498 ** function. The compiled version of the regular expression is stored as
4499 ** metadata associated with the SQL value passed as the regular expression
4500 ** pattern.  The compiled regular expression can be reused on multiple
4501 ** invocations of the same function so that the original pattern string
4502 ** does not need to be recompiled on each invocation.
4503 **
4504 ** ^The sqlcipher3_get_auxdata() interface returns a pointer to the metadata
4505 ** associated by the sqlcipher3_set_auxdata() function with the Nth argument
4506 ** value to the application-defined function. ^If no metadata has been ever
4507 ** been set for the Nth argument of the function, or if the corresponding
4508 ** function parameter has changed since the meta-data was set,
4509 ** then sqlcipher3_get_auxdata() returns a NULL pointer.
4510 **
4511 ** ^The sqlcipher3_set_auxdata() interface saves the metadata
4512 ** pointed to by its 3rd parameter as the metadata for the N-th
4513 ** argument of the application-defined function.  Subsequent
4514 ** calls to sqlcipher3_get_auxdata() might return this data, if it has
4515 ** not been destroyed.
4516 ** ^If it is not NULL, SQLite will invoke the destructor
4517 ** function given by the 4th parameter to sqlcipher3_set_auxdata() on
4518 ** the metadata when the corresponding function parameter changes
4519 ** or when the SQL statement completes, whichever comes first.
4520 **
4521 ** SQLite is free to call the destructor and drop metadata on any
4522 ** parameter of any function at any time.  ^The only guarantee is that
4523 ** the destructor will be called before the metadata is dropped.
4524 **
4525 ** ^(In practice, metadata is preserved between function calls for
4526 ** expressions that are constant at compile time. This includes literal
4527 ** values and [parameters].)^
4528 **
4529 ** These routines must be called from the same thread in which
4530 ** the SQL function is running.
4531 */
4532 SQLCIPHER_API void *sqlcipher3_get_auxdata(sqlcipher3_context*, int N);
4533 SQLCIPHER_API void sqlcipher3_set_auxdata(sqlcipher3_context*, int N, void*, void (*)(void*));
4534
4535
4536 /*
4537 ** CAPI3REF: Constants Defining Special Destructor Behavior
4538 **
4539 ** These are special values for the destructor that is passed in as the
4540 ** final argument to routines like [sqlcipher3_result_blob()].  ^If the destructor
4541 ** argument is SQLCIPHER_STATIC, it means that the content pointer is constant
4542 ** and will never change.  It does not need to be destroyed.  ^The
4543 ** SQLCIPHER_TRANSIENT value means that the content will likely change in
4544 ** the near future and that SQLite should make its own private copy of
4545 ** the content before returning.
4546 **
4547 ** The typedef is necessary to work around problems in certain
4548 ** C++ compilers.  See ticket #2191.
4549 */
4550 typedef void (*sqlcipher3_destructor_type)(void*);
4551 #define SQLCIPHER_STATIC      ((sqlcipher3_destructor_type)0)
4552 #define SQLCIPHER_TRANSIENT   ((sqlcipher3_destructor_type)-1)
4553
4554 /*
4555 ** CAPI3REF: Setting The Result Of An SQL Function
4556 **
4557 ** These routines are used by the xFunc or xFinal callbacks that
4558 ** implement SQL functions and aggregates.  See
4559 ** [sqlcipher3_create_function()] and [sqlcipher3_create_function16()]
4560 ** for additional information.
4561 **
4562 ** These functions work very much like the [parameter binding] family of
4563 ** functions used to bind values to host parameters in prepared statements.
4564 ** Refer to the [SQL parameter] documentation for additional information.
4565 **
4566 ** ^The sqlcipher3_result_blob() interface sets the result from
4567 ** an application-defined function to be the BLOB whose content is pointed
4568 ** to by the second parameter and which is N bytes long where N is the
4569 ** third parameter.
4570 **
4571 ** ^The sqlcipher3_result_zeroblob() interfaces set the result of
4572 ** the application-defined function to be a BLOB containing all zero
4573 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4574 **
4575 ** ^The sqlcipher3_result_double() interface sets the result from
4576 ** an application-defined function to be a floating point value specified
4577 ** by its 2nd argument.
4578 **
4579 ** ^The sqlcipher3_result_error() and sqlcipher3_result_error16() functions
4580 ** cause the implemented SQL function to throw an exception.
4581 ** ^SQLite uses the string pointed to by the
4582 ** 2nd parameter of sqlcipher3_result_error() or sqlcipher3_result_error16()
4583 ** as the text of an error message.  ^SQLite interprets the error
4584 ** message string from sqlcipher3_result_error() as UTF-8. ^SQLite
4585 ** interprets the string from sqlcipher3_result_error16() as UTF-16 in native
4586 ** byte order.  ^If the third parameter to sqlcipher3_result_error()
4587 ** or sqlcipher3_result_error16() is negative then SQLite takes as the error
4588 ** message all text up through the first zero character.
4589 ** ^If the third parameter to sqlcipher3_result_error() or
4590 ** sqlcipher3_result_error16() is non-negative then SQLite takes that many
4591 ** bytes (not characters) from the 2nd parameter as the error message.
4592 ** ^The sqlcipher3_result_error() and sqlcipher3_result_error16()
4593 ** routines make a private copy of the error message text before
4594 ** they return.  Hence, the calling function can deallocate or
4595 ** modify the text after they return without harm.
4596 ** ^The sqlcipher3_result_error_code() function changes the error code
4597 ** returned by SQLite as a result of an error in a function.  ^By default,
4598 ** the error code is SQLCIPHER_ERROR.  ^A subsequent call to sqlcipher3_result_error()
4599 ** or sqlcipher3_result_error16() resets the error code to SQLCIPHER_ERROR.
4600 **
4601 ** ^The sqlcipher3_result_toobig() interface causes SQLite to throw an error
4602 ** indicating that a string or BLOB is too long to represent.
4603 **
4604 ** ^The sqlcipher3_result_nomem() interface causes SQLite to throw an error
4605 ** indicating that a memory allocation failed.
4606 **
4607 ** ^The sqlcipher3_result_int() interface sets the return value
4608 ** of the application-defined function to be the 32-bit signed integer
4609 ** value given in the 2nd argument.
4610 ** ^The sqlcipher3_result_int64() interface sets the return value
4611 ** of the application-defined function to be the 64-bit signed integer
4612 ** value given in the 2nd argument.
4613 **
4614 ** ^The sqlcipher3_result_null() interface sets the return value
4615 ** of the application-defined function to be NULL.
4616 **
4617 ** ^The sqlcipher3_result_text(), sqlcipher3_result_text16(),
4618 ** sqlcipher3_result_text16le(), and sqlcipher3_result_text16be() interfaces
4619 ** set the return value of the application-defined function to be
4620 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4621 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4622 ** ^SQLite takes the text result from the application from
4623 ** the 2nd parameter of the sqlcipher3_result_text* interfaces.
4624 ** ^If the 3rd parameter to the sqlcipher3_result_text* interfaces
4625 ** is negative, then SQLite takes result text from the 2nd parameter
4626 ** through the first zero character.
4627 ** ^If the 3rd parameter to the sqlcipher3_result_text* interfaces
4628 ** is non-negative, then as many bytes (not characters) of the text
4629 ** pointed to by the 2nd parameter are taken as the application-defined
4630 ** function result.  If the 3rd parameter is non-negative, then it
4631 ** must be the byte offset into the string where the NUL terminator would
4632 ** appear if the string where NUL terminated.  If any NUL characters occur
4633 ** in the string at a byte offset that is less than the value of the 3rd
4634 ** parameter, then the resulting string will contain embedded NULs and the
4635 ** result of expressions operating on strings with embedded NULs is undefined.
4636 ** ^If the 4th parameter to the sqlcipher3_result_text* interfaces
4637 ** or sqlcipher3_result_blob is a non-NULL pointer, then SQLite calls that
4638 ** function as the destructor on the text or BLOB result when it has
4639 ** finished using that result.
4640 ** ^If the 4th parameter to the sqlcipher3_result_text* interfaces or to
4641 ** sqlcipher3_result_blob is the special constant SQLCIPHER_STATIC, then SQLite
4642 ** assumes that the text or BLOB result is in constant space and does not
4643 ** copy the content of the parameter nor call a destructor on the content
4644 ** when it has finished using that result.
4645 ** ^If the 4th parameter to the sqlcipher3_result_text* interfaces
4646 ** or sqlcipher3_result_blob is the special constant SQLCIPHER_TRANSIENT
4647 ** then SQLite makes a copy of the result into space obtained from
4648 ** from [sqlcipher3_malloc()] before it returns.
4649 **
4650 ** ^The sqlcipher3_result_value() interface sets the result of
4651 ** the application-defined function to be a copy the
4652 ** [unprotected sqlcipher3_value] object specified by the 2nd parameter.  ^The
4653 ** sqlcipher3_result_value() interface makes a copy of the [sqlcipher3_value]
4654 ** so that the [sqlcipher3_value] specified in the parameter may change or
4655 ** be deallocated after sqlcipher3_result_value() returns without harm.
4656 ** ^A [protected sqlcipher3_value] object may always be used where an
4657 ** [unprotected sqlcipher3_value] object is required, so either
4658 ** kind of [sqlcipher3_value] object can be used with this interface.
4659 **
4660 ** If these routines are called from within the different thread
4661 ** than the one containing the application-defined function that received
4662 ** the [sqlcipher3_context] pointer, the results are undefined.
4663 */
4664 SQLCIPHER_API void sqlcipher3_result_blob(sqlcipher3_context*, const void*, int, void(*)(void*));
4665 SQLCIPHER_API void sqlcipher3_result_double(sqlcipher3_context*, double);
4666 SQLCIPHER_API void sqlcipher3_result_error(sqlcipher3_context*, const char*, int);
4667 SQLCIPHER_API void sqlcipher3_result_error16(sqlcipher3_context*, const void*, int);
4668 SQLCIPHER_API void sqlcipher3_result_error_toobig(sqlcipher3_context*);
4669 SQLCIPHER_API void sqlcipher3_result_error_nomem(sqlcipher3_context*);
4670 SQLCIPHER_API void sqlcipher3_result_error_code(sqlcipher3_context*, int);
4671 SQLCIPHER_API void sqlcipher3_result_int(sqlcipher3_context*, int);
4672 SQLCIPHER_API void sqlcipher3_result_int64(sqlcipher3_context*, sqlcipher3_int64);
4673 SQLCIPHER_API void sqlcipher3_result_null(sqlcipher3_context*);
4674 SQLCIPHER_API void sqlcipher3_result_text(sqlcipher3_context*, const char*, int, void(*)(void*));
4675 SQLCIPHER_API void sqlcipher3_result_text16(sqlcipher3_context*, const void*, int, void(*)(void*));
4676 SQLCIPHER_API void sqlcipher3_result_text16le(sqlcipher3_context*, const void*, int,void(*)(void*));
4677 SQLCIPHER_API void sqlcipher3_result_text16be(sqlcipher3_context*, const void*, int,void(*)(void*));
4678 SQLCIPHER_API void sqlcipher3_result_value(sqlcipher3_context*, sqlcipher3_value*);
4679 SQLCIPHER_API void sqlcipher3_result_zeroblob(sqlcipher3_context*, int n);
4680
4681 /*
4682 ** CAPI3REF: Define New Collating Sequences
4683 **
4684 ** ^These functions add, remove, or modify a [collation] associated
4685 ** with the [database connection] specified as the first argument.
4686 **
4687 ** ^The name of the collation is a UTF-8 string
4688 ** for sqlcipher3_create_collation() and sqlcipher3_create_collation_v2()
4689 ** and a UTF-16 string in native byte order for sqlcipher3_create_collation16().
4690 ** ^Collation names that compare equal according to [sqlcipher3_strnicmp()] are
4691 ** considered to be the same name.
4692 **
4693 ** ^(The third argument (eTextRep) must be one of the constants:
4694 ** <ul>
4695 ** <li> [SQLCIPHER_UTF8],
4696 ** <li> [SQLCIPHER_UTF16LE],
4697 ** <li> [SQLCIPHER_UTF16BE],
4698 ** <li> [SQLCIPHER_UTF16], or
4699 ** <li> [SQLCIPHER_UTF16_ALIGNED].
4700 ** </ul>)^
4701 ** ^The eTextRep argument determines the encoding of strings passed
4702 ** to the collating function callback, xCallback.
4703 ** ^The [SQLCIPHER_UTF16] and [SQLCIPHER_UTF16_ALIGNED] values for eTextRep
4704 ** force strings to be UTF16 with native byte order.
4705 ** ^The [SQLCIPHER_UTF16_ALIGNED] value for eTextRep forces strings to begin
4706 ** on an even byte address.
4707 **
4708 ** ^The fourth argument, pArg, is an application data pointer that is passed
4709 ** through as the first argument to the collating function callback.
4710 **
4711 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4712 ** ^Multiple collating functions can be registered using the same name but
4713 ** with different eTextRep parameters and SQLite will use whichever
4714 ** function requires the least amount of data transformation.
4715 ** ^If the xCallback argument is NULL then the collating function is
4716 ** deleted.  ^When all collating functions having the same name are deleted,
4717 ** that collation is no longer usable.
4718 **
4719 ** ^The collating function callback is invoked with a copy of the pArg 
4720 ** application data pointer and with two strings in the encoding specified
4721 ** by the eTextRep argument.  The collating function must return an
4722 ** integer that is negative, zero, or positive
4723 ** if the first string is less than, equal to, or greater than the second,
4724 ** respectively.  A collating function must always return the same answer
4725 ** given the same inputs.  If two or more collating functions are registered
4726 ** to the same collation name (using different eTextRep values) then all
4727 ** must give an equivalent answer when invoked with equivalent strings.
4728 ** The collating function must obey the following properties for all
4729 ** strings A, B, and C:
4730 **
4731 ** <ol>
4732 ** <li> If A==B then B==A.
4733 ** <li> If A==B and B==C then A==C.
4734 ** <li> If A&lt;B THEN B&gt;A.
4735 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4736 ** </ol>
4737 **
4738 ** If a collating function fails any of the above constraints and that
4739 ** collating function is  registered and used, then the behavior of SQLite
4740 ** is undefined.
4741 **
4742 ** ^The sqlcipher3_create_collation_v2() works like sqlcipher3_create_collation()
4743 ** with the addition that the xDestroy callback is invoked on pArg when
4744 ** the collating function is deleted.
4745 ** ^Collating functions are deleted when they are overridden by later
4746 ** calls to the collation creation functions or when the
4747 ** [database connection] is closed using [sqlcipher3_close()].
4748 **
4749 ** ^The xDestroy callback is <u>not</u> called if the 
4750 ** sqlcipher3_create_collation_v2() function fails.  Applications that invoke
4751 ** sqlcipher3_create_collation_v2() with a non-NULL xDestroy argument should 
4752 ** check the return code and dispose of the application data pointer
4753 ** themselves rather than expecting SQLite to deal with it for them.
4754 ** This is different from every other SQLite interface.  The inconsistency 
4755 ** is unfortunate but cannot be changed without breaking backwards 
4756 ** compatibility.
4757 **
4758 ** See also:  [sqlcipher3_collation_needed()] and [sqlcipher3_collation_needed16()].
4759 */
4760 SQLCIPHER_API int sqlcipher3_create_collation(
4761   sqlcipher3*, 
4762   const char *zName, 
4763   int eTextRep, 
4764   void *pArg,
4765   int(*xCompare)(void*,int,const void*,int,const void*)
4766 );
4767 SQLCIPHER_API int sqlcipher3_create_collation_v2(
4768   sqlcipher3*, 
4769   const char *zName, 
4770   int eTextRep, 
4771   void *pArg,
4772   int(*xCompare)(void*,int,const void*,int,const void*),
4773   void(*xDestroy)(void*)
4774 );
4775 SQLCIPHER_API int sqlcipher3_create_collation16(
4776   sqlcipher3*, 
4777   const void *zName,
4778   int eTextRep, 
4779   void *pArg,
4780   int(*xCompare)(void*,int,const void*,int,const void*)
4781 );
4782
4783 /*
4784 ** CAPI3REF: Collation Needed Callbacks
4785 **
4786 ** ^To avoid having to register all collation sequences before a database
4787 ** can be used, a single callback function may be registered with the
4788 ** [database connection] to be invoked whenever an undefined collation
4789 ** sequence is required.
4790 **
4791 ** ^If the function is registered using the sqlcipher3_collation_needed() API,
4792 ** then it is passed the names of undefined collation sequences as strings
4793 ** encoded in UTF-8. ^If sqlcipher3_collation_needed16() is used,
4794 ** the names are passed as UTF-16 in machine native byte order.
4795 ** ^A call to either function replaces the existing collation-needed callback.
4796 **
4797 ** ^(When the callback is invoked, the first argument passed is a copy
4798 ** of the second argument to sqlcipher3_collation_needed() or
4799 ** sqlcipher3_collation_needed16().  The second argument is the database
4800 ** connection.  The third argument is one of [SQLCIPHER_UTF8], [SQLCIPHER_UTF16BE],
4801 ** or [SQLCIPHER_UTF16LE], indicating the most desirable form of the collation
4802 ** sequence function required.  The fourth parameter is the name of the
4803 ** required collation sequence.)^
4804 **
4805 ** The callback function should register the desired collation using
4806 ** [sqlcipher3_create_collation()], [sqlcipher3_create_collation16()], or
4807 ** [sqlcipher3_create_collation_v2()].
4808 */
4809 SQLCIPHER_API int sqlcipher3_collation_needed(
4810   sqlcipher3*, 
4811   void*, 
4812   void(*)(void*,sqlcipher3*,int eTextRep,const char*)
4813 );
4814 SQLCIPHER_API int sqlcipher3_collation_needed16(
4815   sqlcipher3*, 
4816   void*,
4817   void(*)(void*,sqlcipher3*,int eTextRep,const void*)
4818 );
4819
4820 #ifdef SQLCIPHER_HAS_CODEC
4821 /*
4822 ** Specify the key for an encrypted database.  This routine should be
4823 ** called right after sqlcipher3_open().
4824 **
4825 ** The code to implement this API is not available in the public release
4826 ** of SQLite.
4827 */
4828 SQLCIPHER_API int sqlcipher3_key(
4829   sqlcipher3 *db,                   /* Database to be rekeyed */
4830   const void *pKey, int nKey     /* The key */
4831 );
4832
4833 /*
4834 ** Change the key on an open database.  If the current database is not
4835 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4836 ** database is decrypted.
4837 **
4838 ** The code to implement this API is not available in the public release
4839 ** of SQLite.
4840 */
4841 SQLCIPHER_API int sqlcipher3_rekey(
4842   sqlcipher3 *db,                   /* Database to be rekeyed */
4843   const void *pKey, int nKey     /* The new key */
4844 );
4845
4846 /*
4847 ** Specify the activation key for a SEE database.  Unless 
4848 ** activated, none of the SEE routines will work.
4849 */
4850 SQLCIPHER_API void sqlcipher3_activate_see(
4851   const char *zPassPhrase        /* Activation phrase */
4852 );
4853 #endif
4854
4855 #ifdef SQLCIPHER_ENABLE_CEROD
4856 /*
4857 ** Specify the activation key for a CEROD database.  Unless 
4858 ** activated, none of the CEROD routines will work.
4859 */
4860 SQLCIPHER_API void sqlcipher3_activate_cerod(
4861   const char *zPassPhrase        /* Activation phrase */
4862 );
4863 #endif
4864
4865 /*
4866 ** CAPI3REF: Suspend Execution For A Short Time
4867 **
4868 ** The sqlcipher3_sleep() function causes the current thread to suspend execution
4869 ** for at least a number of milliseconds specified in its parameter.
4870 **
4871 ** If the operating system does not support sleep requests with
4872 ** millisecond time resolution, then the time will be rounded up to
4873 ** the nearest second. The number of milliseconds of sleep actually
4874 ** requested from the operating system is returned.
4875 **
4876 ** ^SQLite implements this interface by calling the xSleep()
4877 ** method of the default [sqlcipher3_vfs] object.  If the xSleep() method
4878 ** of the default VFS is not implemented correctly, or not implemented at
4879 ** all, then the behavior of sqlcipher3_sleep() may deviate from the description
4880 ** in the previous paragraphs.
4881 */
4882 SQLCIPHER_API int sqlcipher3_sleep(int);
4883
4884 /*
4885 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4886 **
4887 ** ^(If this global variable is made to point to a string which is
4888 ** the name of a folder (a.k.a. directory), then all temporary files
4889 ** created by SQLite when using a built-in [sqlcipher3_vfs | VFS]
4890 ** will be placed in that directory.)^  ^If this variable
4891 ** is a NULL pointer, then SQLite performs a search for an appropriate
4892 ** temporary file directory.
4893 **
4894 ** It is not safe to read or modify this variable in more than one
4895 ** thread at a time.  It is not safe to read or modify this variable
4896 ** if a [database connection] is being used at the same time in a separate
4897 ** thread.
4898 ** It is intended that this variable be set once
4899 ** as part of process initialization and before any SQLite interface
4900 ** routines have been called and that this variable remain unchanged
4901 ** thereafter.
4902 **
4903 ** ^The [temp_store_directory pragma] may modify this variable and cause
4904 ** it to point to memory obtained from [sqlcipher3_malloc].  ^Furthermore,
4905 ** the [temp_store_directory pragma] always assumes that any string
4906 ** that this variable points to is held in memory obtained from 
4907 ** [sqlcipher3_malloc] and the pragma may attempt to free that memory
4908 ** using [sqlcipher3_free].
4909 ** Hence, if this variable is modified directly, either it should be
4910 ** made NULL or made to point to memory obtained from [sqlcipher3_malloc]
4911 ** or else the use of the [temp_store_directory pragma] should be avoided.
4912 */
4913 SQLCIPHER_API char *sqlcipher3_temp_directory;
4914
4915 /*
4916 ** CAPI3REF: Test For Auto-Commit Mode
4917 ** KEYWORDS: {autocommit mode}
4918 **
4919 ** ^The sqlcipher3_get_autocommit() interface returns non-zero or
4920 ** zero if the given database connection is or is not in autocommit mode,
4921 ** respectively.  ^Autocommit mode is on by default.
4922 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4923 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4924 **
4925 ** If certain kinds of errors occur on a statement within a multi-statement
4926 ** transaction (errors including [SQLCIPHER_FULL], [SQLCIPHER_IOERR],
4927 ** [SQLCIPHER_NOMEM], [SQLCIPHER_BUSY], and [SQLCIPHER_INTERRUPT]) then the
4928 ** transaction might be rolled back automatically.  The only way to
4929 ** find out whether SQLite automatically rolled back the transaction after
4930 ** an error is to use this function.
4931 **
4932 ** If another thread changes the autocommit status of the database
4933 ** connection while this routine is running, then the return value
4934 ** is undefined.
4935 */
4936 SQLCIPHER_API int sqlcipher3_get_autocommit(sqlcipher3*);
4937
4938 /*
4939 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4940 **
4941 ** ^The sqlcipher3_db_handle interface returns the [database connection] handle
4942 ** to which a [prepared statement] belongs.  ^The [database connection]
4943 ** returned by sqlcipher3_db_handle is the same [database connection]
4944 ** that was the first argument
4945 ** to the [sqlcipher3_prepare_v2()] call (or its variants) that was used to
4946 ** create the statement in the first place.
4947 */
4948 SQLCIPHER_API sqlcipher3 *sqlcipher3_db_handle(sqlcipher3_stmt*);
4949
4950 /*
4951 ** CAPI3REF: Find the next prepared statement
4952 **
4953 ** ^This interface returns a pointer to the next [prepared statement] after
4954 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4955 ** then this interface returns a pointer to the first prepared statement
4956 ** associated with the database connection pDb.  ^If no prepared statement
4957 ** satisfies the conditions of this routine, it returns NULL.
4958 **
4959 ** The [database connection] pointer D in a call to
4960 ** [sqlcipher3_next_stmt(D,S)] must refer to an open database
4961 ** connection and in particular must not be a NULL pointer.
4962 */
4963 SQLCIPHER_API sqlcipher3_stmt *sqlcipher3_next_stmt(sqlcipher3 *pDb, sqlcipher3_stmt *pStmt);
4964
4965 /*
4966 ** CAPI3REF: Commit And Rollback Notification Callbacks
4967 **
4968 ** ^The sqlcipher3_commit_hook() interface registers a callback
4969 ** function to be invoked whenever a transaction is [COMMIT | committed].
4970 ** ^Any callback set by a previous call to sqlcipher3_commit_hook()
4971 ** for the same database connection is overridden.
4972 ** ^The sqlcipher3_rollback_hook() interface registers a callback
4973 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4974 ** ^Any callback set by a previous call to sqlcipher3_rollback_hook()
4975 ** for the same database connection is overridden.
4976 ** ^The pArg argument is passed through to the callback.
4977 ** ^If the callback on a commit hook function returns non-zero,
4978 ** then the commit is converted into a rollback.
4979 **
4980 ** ^The sqlcipher3_commit_hook(D,C,P) and sqlcipher3_rollback_hook(D,C,P) functions
4981 ** return the P argument from the previous call of the same function
4982 ** on the same [database connection] D, or NULL for
4983 ** the first call for each function on D.
4984 **
4985 ** The callback implementation must not do anything that will modify
4986 ** the database connection that invoked the callback.  Any actions
4987 ** to modify the database connection must be deferred until after the
4988 ** completion of the [sqlcipher3_step()] call that triggered the commit
4989 ** or rollback hook in the first place.
4990 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
4991 ** database connections for the meaning of "modify" in this paragraph.
4992 **
4993 ** ^Registering a NULL function disables the callback.
4994 **
4995 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4996 ** operation is allowed to continue normally.  ^If the commit hook
4997 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4998 ** ^The rollback hook is invoked on a rollback that results from a commit
4999 ** hook returning non-zero, just as it would be with any other rollback.
5000 **
5001 ** ^For the purposes of this API, a transaction is said to have been
5002 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5003 ** an error or constraint causes an implicit rollback to occur.
5004 ** ^The rollback callback is not invoked if a transaction is
5005 ** automatically rolled back because the database connection is closed.
5006 **
5007 ** See also the [sqlcipher3_update_hook()] interface.
5008 */
5009 SQLCIPHER_API void *sqlcipher3_commit_hook(sqlcipher3*, int(*)(void*), void*);
5010 SQLCIPHER_API void *sqlcipher3_rollback_hook(sqlcipher3*, void(*)(void *), void*);
5011
5012 /*
5013 ** CAPI3REF: Data Change Notification Callbacks
5014 **
5015 ** ^The sqlcipher3_update_hook() interface registers a callback function
5016 ** with the [database connection] identified by the first argument
5017 ** to be invoked whenever a row is updated, inserted or deleted.
5018 ** ^Any callback set by a previous call to this function
5019 ** for the same database connection is overridden.
5020 **
5021 ** ^The second argument is a pointer to the function to invoke when a
5022 ** row is updated, inserted or deleted.
5023 ** ^The first argument to the callback is a copy of the third argument
5024 ** to sqlcipher3_update_hook().
5025 ** ^The second callback argument is one of [SQLCIPHER_INSERT], [SQLCIPHER_DELETE],
5026 ** or [SQLCIPHER_UPDATE], depending on the operation that caused the callback
5027 ** to be invoked.
5028 ** ^The third and fourth arguments to the callback contain pointers to the
5029 ** database and table name containing the affected row.
5030 ** ^The final callback parameter is the [rowid] of the row.
5031 ** ^In the case of an update, this is the [rowid] after the update takes place.
5032 **
5033 ** ^(The update hook is not invoked when internal system tables are
5034 ** modified (i.e. sqlcipher_master and sqlcipher_sequence).)^
5035 **
5036 ** ^In the current implementation, the update hook
5037 ** is not invoked when duplication rows are deleted because of an
5038 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5039 ** invoked when rows are deleted using the [truncate optimization].
5040 ** The exceptions defined in this paragraph might change in a future
5041 ** release of SQLite.
5042 **
5043 ** The update hook implementation must not do anything that will modify
5044 ** the database connection that invoked the update hook.  Any actions
5045 ** to modify the database connection must be deferred until after the
5046 ** completion of the [sqlcipher3_step()] call that triggered the update hook.
5047 ** Note that [sqlcipher3_prepare_v2()] and [sqlcipher3_step()] both modify their
5048 ** database connections for the meaning of "modify" in this paragraph.
5049 **
5050 ** ^The sqlcipher3_update_hook(D,C,P) function
5051 ** returns the P argument from the previous call
5052 ** on the same [database connection] D, or NULL for
5053 ** the first call on D.
5054 **
5055 ** See also the [sqlcipher3_commit_hook()] and [sqlcipher3_rollback_hook()]
5056 ** interfaces.
5057 */
5058 SQLCIPHER_API void *sqlcipher3_update_hook(
5059   sqlcipher3*, 
5060   void(*)(void *,int ,char const *,char const *,sqlcipher3_int64),
5061   void*
5062 );
5063
5064 /*
5065 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5066 ** KEYWORDS: {shared cache}
5067 **
5068 ** ^(This routine enables or disables the sharing of the database cache
5069 ** and schema data structures between [database connection | connections]
5070 ** to the same database. Sharing is enabled if the argument is true
5071 ** and disabled if the argument is false.)^
5072 **
5073 ** ^Cache sharing is enabled and disabled for an entire process.
5074 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5075 ** sharing was enabled or disabled for each thread separately.
5076 **
5077 ** ^(The cache sharing mode set by this interface effects all subsequent
5078 ** calls to [sqlcipher3_open()], [sqlcipher3_open_v2()], and [sqlcipher3_open16()].
5079 ** Existing database connections continue use the sharing mode
5080 ** that was in effect at the time they were opened.)^
5081 **
5082 ** ^(This routine returns [SQLCIPHER_OK] if shared cache was enabled or disabled
5083 ** successfully.  An [error code] is returned otherwise.)^
5084 **
5085 ** ^Shared cache is disabled by default. But this might change in
5086 ** future releases of SQLite.  Applications that care about shared
5087 ** cache setting should set it explicitly.
5088 **
5089 ** See Also:  [SQLite Shared-Cache Mode]
5090 */
5091 SQLCIPHER_API int sqlcipher3_enable_shared_cache(int);
5092
5093 /*
5094 ** CAPI3REF: Attempt To Free Heap Memory
5095 **
5096 ** ^The sqlcipher3_release_memory() interface attempts to free N bytes
5097 ** of heap memory by deallocating non-essential memory allocations
5098 ** held by the database library.   Memory used to cache database
5099 ** pages to improve performance is an example of non-essential memory.
5100 ** ^sqlcipher3_release_memory() returns the number of bytes actually freed,
5101 ** which might be more or less than the amount requested.
5102 ** ^The sqlcipher3_release_memory() routine is a no-op returning zero
5103 ** if SQLite is not compiled with [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT].
5104 */
5105 SQLCIPHER_API int sqlcipher3_release_memory(int);
5106
5107 /*
5108 ** CAPI3REF: Impose A Limit On Heap Size
5109 **
5110 ** ^The sqlcipher3_soft_heap_limit64() interface sets and/or queries the
5111 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5112 ** ^SQLite strives to keep heap memory utilization below the soft heap
5113 ** limit by reducing the number of pages held in the page cache
5114 ** as heap memory usages approaches the limit.
5115 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5116 ** below the limit, it will exceed the limit rather than generate
5117 ** an [SQLCIPHER_NOMEM] error.  In other words, the soft heap limit 
5118 ** is advisory only.
5119 **
5120 ** ^The return value from sqlcipher3_soft_heap_limit64() is the size of
5121 ** the soft heap limit prior to the call.  ^If the argument N is negative
5122 ** then no change is made to the soft heap limit.  Hence, the current
5123 ** size of the soft heap limit can be determined by invoking
5124 ** sqlcipher3_soft_heap_limit64() with a negative argument.
5125 **
5126 ** ^If the argument N is zero then the soft heap limit is disabled.
5127 **
5128 ** ^(The soft heap limit is not enforced in the current implementation
5129 ** if one or more of following conditions are true:
5130 **
5131 ** <ul>
5132 ** <li> The soft heap limit is set to zero.
5133 ** <li> Memory accounting is disabled using a combination of the
5134 **      [sqlcipher3_config]([SQLCIPHER_CONFIG_MEMSTATUS],...) start-time option and
5135 **      the [SQLCIPHER_DEFAULT_MEMSTATUS] compile-time option.
5136 ** <li> An alternative page cache implementation is specified using
5137 **      [sqlcipher3_config]([SQLCIPHER_CONFIG_PCACHE],...).
5138 ** <li> The page cache allocates from its own memory pool supplied
5139 **      by [sqlcipher3_config]([SQLCIPHER_CONFIG_PAGECACHE],...) rather than
5140 **      from the heap.
5141 ** </ul>)^
5142 **
5143 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5144 ** regardless of whether or not the [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT]
5145 ** compile-time option is invoked.  With [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT],
5146 ** the soft heap limit is enforced on every memory allocation.  Without
5147 ** [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5148 ** when memory is allocated by the page cache.  Testing suggests that because
5149 ** the page cache is the predominate memory user in SQLite, most
5150 ** applications will achieve adequate soft heap limit enforcement without
5151 ** the use of [SQLCIPHER_ENABLE_MEMORY_MANAGEMENT].
5152 **
5153 ** The circumstances under which SQLite will enforce the soft heap limit may
5154 ** changes in future releases of SQLite.
5155 */
5156 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_soft_heap_limit64(sqlcipher3_int64 N);
5157
5158 /*
5159 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5160 ** DEPRECATED
5161 **
5162 ** This is a deprecated version of the [sqlcipher3_soft_heap_limit64()]
5163 ** interface.  This routine is provided for historical compatibility
5164 ** only.  All new applications should use the
5165 ** [sqlcipher3_soft_heap_limit64()] interface rather than this one.
5166 */
5167 SQLCIPHER_API SQLCIPHER_DEPRECATED void sqlcipher3_soft_heap_limit(int N);
5168
5169
5170 /*
5171 ** CAPI3REF: Extract Metadata About A Column Of A Table
5172 **
5173 ** ^This routine returns metadata about a specific column of a specific
5174 ** database table accessible using the [database connection] handle
5175 ** passed as the first function argument.
5176 **
5177 ** ^The column is identified by the second, third and fourth parameters to
5178 ** this function. ^The second parameter is either the name of the database
5179 ** (i.e. "main", "temp", or an attached database) containing the specified
5180 ** table or NULL. ^If it is NULL, then all attached databases are searched
5181 ** for the table using the same algorithm used by the database engine to
5182 ** resolve unqualified table references.
5183 **
5184 ** ^The third and fourth parameters to this function are the table and column
5185 ** name of the desired column, respectively. Neither of these parameters
5186 ** may be NULL.
5187 **
5188 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5189 ** and subsequent parameters to this function. ^Any of these arguments may be
5190 ** NULL, in which case the corresponding element of metadata is omitted.
5191 **
5192 ** ^(<blockquote>
5193 ** <table border="1">
5194 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5195 **
5196 ** <tr><td> 5th <td> const char* <td> Data type
5197 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5198 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5199 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5200 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5201 ** </table>
5202 ** </blockquote>)^
5203 **
5204 ** ^The memory pointed to by the character pointers returned for the
5205 ** declaration type and collation sequence is valid only until the next
5206 ** call to any SQLite API function.
5207 **
5208 ** ^If the specified table is actually a view, an [error code] is returned.
5209 **
5210 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5211 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5212 ** parameters are set for the explicitly declared column. ^(If there is no
5213 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5214 ** parameters are set as follows:
5215 **
5216 ** <pre>
5217 **     data type: "INTEGER"
5218 **     collation sequence: "BINARY"
5219 **     not null: 0
5220 **     primary key: 1
5221 **     auto increment: 0
5222 ** </pre>)^
5223 **
5224 ** ^(This function may load one or more schemas from database files. If an
5225 ** error occurs during this process, or if the requested table or column
5226 ** cannot be found, an [error code] is returned and an error message left
5227 ** in the [database connection] (to be retrieved using sqlcipher3_errmsg()).)^
5228 **
5229 ** ^This API is only available if the library was compiled with the
5230 ** [SQLCIPHER_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5231 */
5232 SQLCIPHER_API int sqlcipher3_table_column_metadata(
5233   sqlcipher3 *db,                /* Connection handle */
5234   const char *zDbName,        /* Database name or NULL */
5235   const char *zTableName,     /* Table name */
5236   const char *zColumnName,    /* Column name */
5237   char const **pzDataType,    /* OUTPUT: Declared data type */
5238   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5239   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5240   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5241   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5242 );
5243
5244 /*
5245 ** CAPI3REF: Load An Extension
5246 **
5247 ** ^This interface loads an SQLite extension library from the named file.
5248 **
5249 ** ^The sqlcipher3_load_extension() interface attempts to load an
5250 ** SQLite extension library contained in the file zFile.
5251 **
5252 ** ^The entry point is zProc.
5253 ** ^zProc may be 0, in which case the name of the entry point
5254 ** defaults to "sqlcipher3_extension_init".
5255 ** ^The sqlcipher3_load_extension() interface returns
5256 ** [SQLCIPHER_OK] on success and [SQLCIPHER_ERROR] if something goes wrong.
5257 ** ^If an error occurs and pzErrMsg is not 0, then the
5258 ** [sqlcipher3_load_extension()] interface shall attempt to
5259 ** fill *pzErrMsg with error message text stored in memory
5260 ** obtained from [sqlcipher3_malloc()]. The calling function
5261 ** should free this memory by calling [sqlcipher3_free()].
5262 **
5263 ** ^Extension loading must be enabled using
5264 ** [sqlcipher3_enable_load_extension()] prior to calling this API,
5265 ** otherwise an error will be returned.
5266 **
5267 ** See also the [load_extension() SQL function].
5268 */
5269 SQLCIPHER_API int sqlcipher3_load_extension(
5270   sqlcipher3 *db,          /* Load the extension into this database connection */
5271   const char *zFile,    /* Name of the shared library containing extension */
5272   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5273   char **pzErrMsg       /* Put error message here if not 0 */
5274 );
5275
5276 /*
5277 ** CAPI3REF: Enable Or Disable Extension Loading
5278 **
5279 ** ^So as not to open security holes in older applications that are
5280 ** unprepared to deal with extension loading, and as a means of disabling
5281 ** extension loading while evaluating user-entered SQL, the following API
5282 ** is provided to turn the [sqlcipher3_load_extension()] mechanism on and off.
5283 **
5284 ** ^Extension loading is off by default. See ticket #1863.
5285 ** ^Call the sqlcipher3_enable_load_extension() routine with onoff==1
5286 ** to turn extension loading on and call it with onoff==0 to turn
5287 ** it back off again.
5288 */
5289 SQLCIPHER_API int sqlcipher3_enable_load_extension(sqlcipher3 *db, int onoff);
5290
5291 /*
5292 ** CAPI3REF: Automatically Load Statically Linked Extensions
5293 **
5294 ** ^This interface causes the xEntryPoint() function to be invoked for
5295 ** each new [database connection] that is created.  The idea here is that
5296 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5297 ** that is to be automatically loaded into all new database connections.
5298 **
5299 ** ^(Even though the function prototype shows that xEntryPoint() takes
5300 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5301 ** arguments and expects and integer result as if the signature of the
5302 ** entry point where as follows:
5303 **
5304 ** <blockquote><pre>
5305 ** &nbsp;  int xEntryPoint(
5306 ** &nbsp;    sqlcipher3 *db,
5307 ** &nbsp;    const char **pzErrMsg,
5308 ** &nbsp;    const struct sqlcipher3_api_routines *pThunk
5309 ** &nbsp;  );
5310 ** </pre></blockquote>)^
5311 **
5312 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5313 ** point to an appropriate error message (obtained from [sqlcipher3_mprintf()])
5314 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5315 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5316 ** [sqlcipher3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5317 ** xEntryPoint() returns an error, the [sqlcipher3_open()], [sqlcipher3_open16()],
5318 ** or [sqlcipher3_open_v2()] call that provoked the xEntryPoint() will fail.
5319 **
5320 ** ^Calling sqlcipher3_auto_extension(X) with an entry point X that is already
5321 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5322 ** will be called more than once for each database connection that is opened.
5323 **
5324 ** See also: [sqlcipher3_reset_auto_extension()].
5325 */
5326 SQLCIPHER_API int sqlcipher3_auto_extension(void (*xEntryPoint)(void));
5327
5328 /*
5329 ** CAPI3REF: Reset Automatic Extension Loading
5330 **
5331 ** ^This interface disables all automatic extensions previously
5332 ** registered using [sqlcipher3_auto_extension()].
5333 */
5334 SQLCIPHER_API void sqlcipher3_reset_auto_extension(void);
5335
5336 /*
5337 ** The interface to the virtual-table mechanism is currently considered
5338 ** to be experimental.  The interface might change in incompatible ways.
5339 ** If this is a problem for you, do not use the interface at this time.
5340 **
5341 ** When the virtual-table mechanism stabilizes, we will declare the
5342 ** interface fixed, support it indefinitely, and remove this comment.
5343 */
5344
5345 /*
5346 ** Structures used by the virtual table interface
5347 */
5348 typedef struct sqlcipher3_vtab sqlcipher3_vtab;
5349 typedef struct sqlcipher3_index_info sqlcipher3_index_info;
5350 typedef struct sqlcipher3_vtab_cursor sqlcipher3_vtab_cursor;
5351 typedef struct sqlcipher3_module sqlcipher3_module;
5352
5353 /*
5354 ** CAPI3REF: Virtual Table Object
5355 ** KEYWORDS: sqlcipher3_module {virtual table module}
5356 **
5357 ** This structure, sometimes called a "virtual table module", 
5358 ** defines the implementation of a [virtual tables].  
5359 ** This structure consists mostly of methods for the module.
5360 **
5361 ** ^A virtual table module is created by filling in a persistent
5362 ** instance of this structure and passing a pointer to that instance
5363 ** to [sqlcipher3_create_module()] or [sqlcipher3_create_module_v2()].
5364 ** ^The registration remains valid until it is replaced by a different
5365 ** module or until the [database connection] closes.  The content
5366 ** of this structure must not change while it is registered with
5367 ** any database connection.
5368 */
5369 struct sqlcipher3_module {
5370   int iVersion;
5371   int (*xCreate)(sqlcipher3*, void *pAux,
5372                int argc, const char *const*argv,
5373                sqlcipher3_vtab **ppVTab, char**);
5374   int (*xConnect)(sqlcipher3*, void *pAux,
5375                int argc, const char *const*argv,
5376                sqlcipher3_vtab **ppVTab, char**);
5377   int (*xBestIndex)(sqlcipher3_vtab *pVTab, sqlcipher3_index_info*);
5378   int (*xDisconnect)(sqlcipher3_vtab *pVTab);
5379   int (*xDestroy)(sqlcipher3_vtab *pVTab);
5380   int (*xOpen)(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCursor);
5381   int (*xClose)(sqlcipher3_vtab_cursor*);
5382   int (*xFilter)(sqlcipher3_vtab_cursor*, int idxNum, const char *idxStr,
5383                 int argc, sqlcipher3_value **argv);
5384   int (*xNext)(sqlcipher3_vtab_cursor*);
5385   int (*xEof)(sqlcipher3_vtab_cursor*);
5386   int (*xColumn)(sqlcipher3_vtab_cursor*, sqlcipher3_context*, int);
5387   int (*xRowid)(sqlcipher3_vtab_cursor*, sqlcipher3_int64 *pRowid);
5388   int (*xUpdate)(sqlcipher3_vtab *, int, sqlcipher3_value **, sqlcipher3_int64 *);
5389   int (*xBegin)(sqlcipher3_vtab *pVTab);
5390   int (*xSync)(sqlcipher3_vtab *pVTab);
5391   int (*xCommit)(sqlcipher3_vtab *pVTab);
5392   int (*xRollback)(sqlcipher3_vtab *pVTab);
5393   int (*xFindFunction)(sqlcipher3_vtab *pVtab, int nArg, const char *zName,
5394                        void (**pxFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
5395                        void **ppArg);
5396   int (*xRename)(sqlcipher3_vtab *pVtab, const char *zNew);
5397   /* The methods above are in version 1 of the sqlcipher_module object. Those 
5398   ** below are for version 2 and greater. */
5399   int (*xSavepoint)(sqlcipher3_vtab *pVTab, int);
5400   int (*xRelease)(sqlcipher3_vtab *pVTab, int);
5401   int (*xRollbackTo)(sqlcipher3_vtab *pVTab, int);
5402 };
5403
5404 /*
5405 ** CAPI3REF: Virtual Table Indexing Information
5406 ** KEYWORDS: sqlcipher3_index_info
5407 **
5408 ** The sqlcipher3_index_info structure and its substructures is used as part
5409 ** of the [virtual table] interface to
5410 ** pass information into and receive the reply from the [xBestIndex]
5411 ** method of a [virtual table module].  The fields under **Inputs** are the
5412 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5413 ** results into the **Outputs** fields.
5414 **
5415 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5416 **
5417 ** <blockquote>column OP expr</blockquote>
5418 **
5419 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5420 ** stored in aConstraint[].op using one of the
5421 ** [SQLCIPHER_INDEX_CONSTRAINT_EQ | SQLCIPHER_INDEX_CONSTRAINT_ values].)^
5422 ** ^(The index of the column is stored in
5423 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5424 ** expr on the right-hand side can be evaluated (and thus the constraint
5425 ** is usable) and false if it cannot.)^
5426 **
5427 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5428 ** and makes other simplifications to the WHERE clause in an attempt to
5429 ** get as many WHERE clause terms into the form shown above as possible.
5430 ** ^The aConstraint[] array only reports WHERE clause terms that are
5431 ** relevant to the particular virtual table being queried.
5432 **
5433 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5434 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5435 **
5436 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5437 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5438 ** the right-hand side of the corresponding aConstraint[] is evaluated
5439 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5440 ** is true, then the constraint is assumed to be fully handled by the
5441 ** virtual table and is not checked again by SQLite.)^
5442 **
5443 ** ^The idxNum and idxPtr values are recorded and passed into the
5444 ** [xFilter] method.
5445 ** ^[sqlcipher3_free()] is used to free idxPtr if and only if
5446 ** needToFreeIdxPtr is true.
5447 **
5448 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5449 ** the correct order to satisfy the ORDER BY clause so that no separate
5450 ** sorting step is required.
5451 **
5452 ** ^The estimatedCost value is an estimate of the cost of doing the
5453 ** particular lookup.  A full scan of a table with N entries should have
5454 ** a cost of N.  A binary search of a table of N entries should have a
5455 ** cost of approximately log(N).
5456 */
5457 struct sqlcipher3_index_info {
5458   /* Inputs */
5459   int nConstraint;           /* Number of entries in aConstraint */
5460   struct sqlcipher3_index_constraint {
5461      int iColumn;              /* Column on left-hand side of constraint */
5462      unsigned char op;         /* Constraint operator */
5463      unsigned char usable;     /* True if this constraint is usable */
5464      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5465   } *aConstraint;            /* Table of WHERE clause constraints */
5466   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5467   struct sqlcipher3_index_orderby {
5468      int iColumn;              /* Column number */
5469      unsigned char desc;       /* True for DESC.  False for ASC. */
5470   } *aOrderBy;               /* The ORDER BY clause */
5471   /* Outputs */
5472   struct sqlcipher3_index_constraint_usage {
5473     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5474     unsigned char omit;      /* Do not code a test for this constraint */
5475   } *aConstraintUsage;
5476   int idxNum;                /* Number used to identify the index */
5477   char *idxStr;              /* String, possibly obtained from sqlcipher3_malloc */
5478   int needToFreeIdxStr;      /* Free idxStr using sqlcipher3_free() if true */
5479   int orderByConsumed;       /* True if output is already ordered */
5480   double estimatedCost;      /* Estimated cost of using this index */
5481 };
5482
5483 /*
5484 ** CAPI3REF: Virtual Table Constraint Operator Codes
5485 **
5486 ** These macros defined the allowed values for the
5487 ** [sqlcipher3_index_info].aConstraint[].op field.  Each value represents
5488 ** an operator that is part of a constraint term in the wHERE clause of
5489 ** a query that uses a [virtual table].
5490 */
5491 #define SQLCIPHER_INDEX_CONSTRAINT_EQ    2
5492 #define SQLCIPHER_INDEX_CONSTRAINT_GT    4
5493 #define SQLCIPHER_INDEX_CONSTRAINT_LE    8
5494 #define SQLCIPHER_INDEX_CONSTRAINT_LT    16
5495 #define SQLCIPHER_INDEX_CONSTRAINT_GE    32
5496 #define SQLCIPHER_INDEX_CONSTRAINT_MATCH 64
5497
5498 /*
5499 ** CAPI3REF: Register A Virtual Table Implementation
5500 **
5501 ** ^These routines are used to register a new [virtual table module] name.
5502 ** ^Module names must be registered before
5503 ** creating a new [virtual table] using the module and before using a
5504 ** preexisting [virtual table] for the module.
5505 **
5506 ** ^The module name is registered on the [database connection] specified
5507 ** by the first parameter.  ^The name of the module is given by the 
5508 ** second parameter.  ^The third parameter is a pointer to
5509 ** the implementation of the [virtual table module].   ^The fourth
5510 ** parameter is an arbitrary client data pointer that is passed through
5511 ** into the [xCreate] and [xConnect] methods of the virtual table module
5512 ** when a new virtual table is be being created or reinitialized.
5513 **
5514 ** ^The sqlcipher3_create_module_v2() interface has a fifth parameter which
5515 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5516 ** invoke the destructor function (if it is not NULL) when SQLite
5517 ** no longer needs the pClientData pointer.  ^The destructor will also
5518 ** be invoked if the call to sqlcipher3_create_module_v2() fails.
5519 ** ^The sqlcipher3_create_module()
5520 ** interface is equivalent to sqlcipher3_create_module_v2() with a NULL
5521 ** destructor.
5522 */
5523 SQLCIPHER_API int sqlcipher3_create_module(
5524   sqlcipher3 *db,               /* SQLite connection to register module with */
5525   const char *zName,         /* Name of the module */
5526   const sqlcipher3_module *p,   /* Methods for the module */
5527   void *pClientData          /* Client data for xCreate/xConnect */
5528 );
5529 SQLCIPHER_API int sqlcipher3_create_module_v2(
5530   sqlcipher3 *db,               /* SQLite connection to register module with */
5531   const char *zName,         /* Name of the module */
5532   const sqlcipher3_module *p,   /* Methods for the module */
5533   void *pClientData,         /* Client data for xCreate/xConnect */
5534   void(*xDestroy)(void*)     /* Module destructor function */
5535 );
5536
5537 /*
5538 ** CAPI3REF: Virtual Table Instance Object
5539 ** KEYWORDS: sqlcipher3_vtab
5540 **
5541 ** Every [virtual table module] implementation uses a subclass
5542 ** of this object to describe a particular instance
5543 ** of the [virtual table].  Each subclass will
5544 ** be tailored to the specific needs of the module implementation.
5545 ** The purpose of this superclass is to define certain fields that are
5546 ** common to all module implementations.
5547 **
5548 ** ^Virtual tables methods can set an error message by assigning a
5549 ** string obtained from [sqlcipher3_mprintf()] to zErrMsg.  The method should
5550 ** take care that any prior string is freed by a call to [sqlcipher3_free()]
5551 ** prior to assigning a new string to zErrMsg.  ^After the error message
5552 ** is delivered up to the client application, the string will be automatically
5553 ** freed by sqlcipher3_free() and the zErrMsg field will be zeroed.
5554 */
5555 struct sqlcipher3_vtab {
5556   const sqlcipher3_module *pModule;  /* The module for this virtual table */
5557   int nRef;                       /* NO LONGER USED */
5558   char *zErrMsg;                  /* Error message from sqlcipher3_mprintf() */
5559   /* Virtual table implementations will typically add additional fields */
5560 };
5561
5562 /*
5563 ** CAPI3REF: Virtual Table Cursor Object
5564 ** KEYWORDS: sqlcipher3_vtab_cursor {virtual table cursor}
5565 **
5566 ** Every [virtual table module] implementation uses a subclass of the
5567 ** following structure to describe cursors that point into the
5568 ** [virtual table] and are used
5569 ** to loop through the virtual table.  Cursors are created using the
5570 ** [sqlcipher3_module.xOpen | xOpen] method of the module and are destroyed
5571 ** by the [sqlcipher3_module.xClose | xClose] method.  Cursors are used
5572 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5573 ** of the module.  Each module implementation will define
5574 ** the content of a cursor structure to suit its own needs.
5575 **
5576 ** This superclass exists in order to define fields of the cursor that
5577 ** are common to all implementations.
5578 */
5579 struct sqlcipher3_vtab_cursor {
5580   sqlcipher3_vtab *pVtab;      /* Virtual table of this cursor */
5581   /* Virtual table implementations will typically add additional fields */
5582 };
5583
5584 /*
5585 ** CAPI3REF: Declare The Schema Of A Virtual Table
5586 **
5587 ** ^The [xCreate] and [xConnect] methods of a
5588 ** [virtual table module] call this interface
5589 ** to declare the format (the names and datatypes of the columns) of
5590 ** the virtual tables they implement.
5591 */
5592 SQLCIPHER_API int sqlcipher3_declare_vtab(sqlcipher3*, const char *zSQL);
5593
5594 /*
5595 ** CAPI3REF: Overload A Function For A Virtual Table
5596 **
5597 ** ^(Virtual tables can provide alternative implementations of functions
5598 ** using the [xFindFunction] method of the [virtual table module].  
5599 ** But global versions of those functions
5600 ** must exist in order to be overloaded.)^
5601 **
5602 ** ^(This API makes sure a global version of a function with a particular
5603 ** name and number of parameters exists.  If no such function exists
5604 ** before this API is called, a new function is created.)^  ^The implementation
5605 ** of the new function always causes an exception to be thrown.  So
5606 ** the new function is not good for anything by itself.  Its only
5607 ** purpose is to be a placeholder function that can be overloaded
5608 ** by a [virtual table].
5609 */
5610 SQLCIPHER_API int sqlcipher3_overload_function(sqlcipher3*, const char *zFuncName, int nArg);
5611
5612 /*
5613 ** The interface to the virtual-table mechanism defined above (back up
5614 ** to a comment remarkably similar to this one) is currently considered
5615 ** to be experimental.  The interface might change in incompatible ways.
5616 ** If this is a problem for you, do not use the interface at this time.
5617 **
5618 ** When the virtual-table mechanism stabilizes, we will declare the
5619 ** interface fixed, support it indefinitely, and remove this comment.
5620 */
5621
5622 /*
5623 ** CAPI3REF: A Handle To An Open BLOB
5624 ** KEYWORDS: {BLOB handle} {BLOB handles}
5625 **
5626 ** An instance of this object represents an open BLOB on which
5627 ** [sqlcipher3_blob_open | incremental BLOB I/O] can be performed.
5628 ** ^Objects of this type are created by [sqlcipher3_blob_open()]
5629 ** and destroyed by [sqlcipher3_blob_close()].
5630 ** ^The [sqlcipher3_blob_read()] and [sqlcipher3_blob_write()] interfaces
5631 ** can be used to read or write small subsections of the BLOB.
5632 ** ^The [sqlcipher3_blob_bytes()] interface returns the size of the BLOB in bytes.
5633 */
5634 typedef struct sqlcipher3_blob sqlcipher3_blob;
5635
5636 /*
5637 ** CAPI3REF: Open A BLOB For Incremental I/O
5638 **
5639 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5640 ** in row iRow, column zColumn, table zTable in database zDb;
5641 ** in other words, the same BLOB that would be selected by:
5642 **
5643 ** <pre>
5644 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5645 ** </pre>)^
5646 **
5647 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5648 ** and write access. ^If it is zero, the BLOB is opened for read access.
5649 ** ^It is not possible to open a column that is part of an index or primary 
5650 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5651 ** not possible to open a column that is part of a [child key] for writing.
5652 **
5653 ** ^Note that the database name is not the filename that contains
5654 ** the database but rather the symbolic name of the database that
5655 ** appears after the AS keyword when the database is connected using [ATTACH].
5656 ** ^For the main database file, the database name is "main".
5657 ** ^For TEMP tables, the database name is "temp".
5658 **
5659 ** ^(On success, [SQLCIPHER_OK] is returned and the new [BLOB handle] is written
5660 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5661 ** to be a null pointer.)^
5662 ** ^This function sets the [database connection] error code and message
5663 ** accessible via [sqlcipher3_errcode()] and [sqlcipher3_errmsg()] and related
5664 ** functions. ^Note that the *ppBlob variable is always initialized in a
5665 ** way that makes it safe to invoke [sqlcipher3_blob_close()] on *ppBlob
5666 ** regardless of the success or failure of this routine.
5667 **
5668 ** ^(If the row that a BLOB handle points to is modified by an
5669 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5670 ** then the BLOB handle is marked as "expired".
5671 ** This is true if any column of the row is changed, even a column
5672 ** other than the one the BLOB handle is open on.)^
5673 ** ^Calls to [sqlcipher3_blob_read()] and [sqlcipher3_blob_write()] for
5674 ** an expired BLOB handle fail with a return code of [SQLCIPHER_ABORT].
5675 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5676 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5677 ** commit if the transaction continues to completion.)^
5678 **
5679 ** ^Use the [sqlcipher3_blob_bytes()] interface to determine the size of
5680 ** the opened blob.  ^The size of a blob may not be changed by this
5681 ** interface.  Use the [UPDATE] SQL command to change the size of a
5682 ** blob.
5683 **
5684 ** ^The [sqlcipher3_bind_zeroblob()] and [sqlcipher3_result_zeroblob()] interfaces
5685 ** and the built-in [zeroblob] SQL function can be used, if desired,
5686 ** to create an empty, zero-filled blob in which to read or write using
5687 ** this interface.
5688 **
5689 ** To avoid a resource leak, every open [BLOB handle] should eventually
5690 ** be released by a call to [sqlcipher3_blob_close()].
5691 */
5692 SQLCIPHER_API int sqlcipher3_blob_open(
5693   sqlcipher3*,
5694   const char *zDb,
5695   const char *zTable,
5696   const char *zColumn,
5697   sqlcipher3_int64 iRow,
5698   int flags,
5699   sqlcipher3_blob **ppBlob
5700 );
5701
5702 /*
5703 ** CAPI3REF: Move a BLOB Handle to a New Row
5704 **
5705 ** ^This function is used to move an existing blob handle so that it points
5706 ** to a different row of the same database table. ^The new row is identified
5707 ** by the rowid value passed as the second argument. Only the row can be
5708 ** changed. ^The database, table and column on which the blob handle is open
5709 ** remain the same. Moving an existing blob handle to a new row can be
5710 ** faster than closing the existing handle and opening a new one.
5711 **
5712 ** ^(The new row must meet the same criteria as for [sqlcipher3_blob_open()] -
5713 ** it must exist and there must be either a blob or text value stored in
5714 ** the nominated column.)^ ^If the new row is not present in the table, or if
5715 ** it does not contain a blob or text value, or if another error occurs, an
5716 ** SQLite error code is returned and the blob handle is considered aborted.
5717 ** ^All subsequent calls to [sqlcipher3_blob_read()], [sqlcipher3_blob_write()] or
5718 ** [sqlcipher3_blob_reopen()] on an aborted blob handle immediately return
5719 ** SQLCIPHER_ABORT. ^Calling [sqlcipher3_blob_bytes()] on an aborted blob handle
5720 ** always returns zero.
5721 **
5722 ** ^This function sets the database handle error code and message.
5723 */
5724 SQLCIPHER_API SQLCIPHER_EXPERIMENTAL int sqlcipher3_blob_reopen(sqlcipher3_blob *, sqlcipher3_int64);
5725
5726 /*
5727 ** CAPI3REF: Close A BLOB Handle
5728 **
5729 ** ^Closes an open [BLOB handle].
5730 **
5731 ** ^Closing a BLOB shall cause the current transaction to commit
5732 ** if there are no other BLOBs, no pending prepared statements, and the
5733 ** database connection is in [autocommit mode].
5734 ** ^If any writes were made to the BLOB, they might be held in cache
5735 ** until the close operation if they will fit.
5736 **
5737 ** ^(Closing the BLOB often forces the changes
5738 ** out to disk and so if any I/O errors occur, they will likely occur
5739 ** at the time when the BLOB is closed.  Any errors that occur during
5740 ** closing are reported as a non-zero return value.)^
5741 **
5742 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5743 ** an error code, the BLOB is still closed.)^
5744 **
5745 ** ^Calling this routine with a null pointer (such as would be returned
5746 ** by a failed call to [sqlcipher3_blob_open()]) is a harmless no-op.
5747 */
5748 SQLCIPHER_API int sqlcipher3_blob_close(sqlcipher3_blob *);
5749
5750 /*
5751 ** CAPI3REF: Return The Size Of An Open BLOB
5752 **
5753 ** ^Returns the size in bytes of the BLOB accessible via the 
5754 ** successfully opened [BLOB handle] in its only argument.  ^The
5755 ** incremental blob I/O routines can only read or overwriting existing
5756 ** blob content; they cannot change the size of a blob.
5757 **
5758 ** This routine only works on a [BLOB handle] which has been created
5759 ** by a prior successful call to [sqlcipher3_blob_open()] and which has not
5760 ** been closed by [sqlcipher3_blob_close()].  Passing any other pointer in
5761 ** to this routine results in undefined and probably undesirable behavior.
5762 */
5763 SQLCIPHER_API int sqlcipher3_blob_bytes(sqlcipher3_blob *);
5764
5765 /*
5766 ** CAPI3REF: Read Data From A BLOB Incrementally
5767 **
5768 ** ^(This function is used to read data from an open [BLOB handle] into a
5769 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5770 ** from the open BLOB, starting at offset iOffset.)^
5771 **
5772 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5773 ** [SQLCIPHER_ERROR] is returned and no data is read.  ^If N or iOffset is
5774 ** less than zero, [SQLCIPHER_ERROR] is returned and no data is read.
5775 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5776 ** can be determined using the [sqlcipher3_blob_bytes()] interface.
5777 **
5778 ** ^An attempt to read from an expired [BLOB handle] fails with an
5779 ** error code of [SQLCIPHER_ABORT].
5780 **
5781 ** ^(On success, sqlcipher3_blob_read() returns SQLCIPHER_OK.
5782 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5783 **
5784 ** This routine only works on a [BLOB handle] which has been created
5785 ** by a prior successful call to [sqlcipher3_blob_open()] and which has not
5786 ** been closed by [sqlcipher3_blob_close()].  Passing any other pointer in
5787 ** to this routine results in undefined and probably undesirable behavior.
5788 **
5789 ** See also: [sqlcipher3_blob_write()].
5790 */
5791 SQLCIPHER_API int sqlcipher3_blob_read(sqlcipher3_blob *, void *Z, int N, int iOffset);
5792
5793 /*
5794 ** CAPI3REF: Write Data Into A BLOB Incrementally
5795 **
5796 ** ^This function is used to write data into an open [BLOB handle] from a
5797 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5798 ** into the open BLOB, starting at offset iOffset.
5799 **
5800 ** ^If the [BLOB handle] passed as the first argument was not opened for
5801 ** writing (the flags parameter to [sqlcipher3_blob_open()] was zero),
5802 ** this function returns [SQLCIPHER_READONLY].
5803 **
5804 ** ^This function may only modify the contents of the BLOB; it is
5805 ** not possible to increase the size of a BLOB using this API.
5806 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5807 ** [SQLCIPHER_ERROR] is returned and no data is written.  ^If N is
5808 ** less than zero [SQLCIPHER_ERROR] is returned and no data is written.
5809 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5810 ** can be determined using the [sqlcipher3_blob_bytes()] interface.
5811 **
5812 ** ^An attempt to write to an expired [BLOB handle] fails with an
5813 ** error code of [SQLCIPHER_ABORT].  ^Writes to the BLOB that occurred
5814 ** before the [BLOB handle] expired are not rolled back by the
5815 ** expiration of the handle, though of course those changes might
5816 ** have been overwritten by the statement that expired the BLOB handle
5817 ** or by other independent statements.
5818 **
5819 ** ^(On success, sqlcipher3_blob_write() returns SQLCIPHER_OK.
5820 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5821 **
5822 ** This routine only works on a [BLOB handle] which has been created
5823 ** by a prior successful call to [sqlcipher3_blob_open()] and which has not
5824 ** been closed by [sqlcipher3_blob_close()].  Passing any other pointer in
5825 ** to this routine results in undefined and probably undesirable behavior.
5826 **
5827 ** See also: [sqlcipher3_blob_read()].
5828 */
5829 SQLCIPHER_API int sqlcipher3_blob_write(sqlcipher3_blob *, const void *z, int n, int iOffset);
5830
5831 /*
5832 ** CAPI3REF: Virtual File System Objects
5833 **
5834 ** A virtual filesystem (VFS) is an [sqlcipher3_vfs] object
5835 ** that SQLite uses to interact
5836 ** with the underlying operating system.  Most SQLite builds come with a
5837 ** single default VFS that is appropriate for the host computer.
5838 ** New VFSes can be registered and existing VFSes can be unregistered.
5839 ** The following interfaces are provided.
5840 **
5841 ** ^The sqlcipher3_vfs_find() interface returns a pointer to a VFS given its name.
5842 ** ^Names are case sensitive.
5843 ** ^Names are zero-terminated UTF-8 strings.
5844 ** ^If there is no match, a NULL pointer is returned.
5845 ** ^If zVfsName is NULL then the default VFS is returned.
5846 **
5847 ** ^New VFSes are registered with sqlcipher3_vfs_register().
5848 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5849 ** ^The same VFS can be registered multiple times without injury.
5850 ** ^To make an existing VFS into the default VFS, register it again
5851 ** with the makeDflt flag set.  If two different VFSes with the
5852 ** same name are registered, the behavior is undefined.  If a
5853 ** VFS is registered with a name that is NULL or an empty string,
5854 ** then the behavior is undefined.
5855 **
5856 ** ^Unregister a VFS with the sqlcipher3_vfs_unregister() interface.
5857 ** ^(If the default VFS is unregistered, another VFS is chosen as
5858 ** the default.  The choice for the new VFS is arbitrary.)^
5859 */
5860 SQLCIPHER_API sqlcipher3_vfs *sqlcipher3_vfs_find(const char *zVfsName);
5861 SQLCIPHER_API int sqlcipher3_vfs_register(sqlcipher3_vfs*, int makeDflt);
5862 SQLCIPHER_API int sqlcipher3_vfs_unregister(sqlcipher3_vfs*);
5863
5864 /*
5865 ** CAPI3REF: Mutexes
5866 **
5867 ** The SQLite core uses these routines for thread
5868 ** synchronization. Though they are intended for internal
5869 ** use by SQLite, code that links against SQLite is
5870 ** permitted to use any of these routines.
5871 **
5872 ** The SQLite source code contains multiple implementations
5873 ** of these mutex routines.  An appropriate implementation
5874 ** is selected automatically at compile-time.  ^(The following
5875 ** implementations are available in the SQLite core:
5876 **
5877 ** <ul>
5878 ** <li>   SQLCIPHER_MUTEX_OS2
5879 ** <li>   SQLCIPHER_MUTEX_PTHREAD
5880 ** <li>   SQLCIPHER_MUTEX_W32
5881 ** <li>   SQLCIPHER_MUTEX_NOOP
5882 ** </ul>)^
5883 **
5884 ** ^The SQLCIPHER_MUTEX_NOOP implementation is a set of routines
5885 ** that does no real locking and is appropriate for use in
5886 ** a single-threaded application.  ^The SQLCIPHER_MUTEX_OS2,
5887 ** SQLCIPHER_MUTEX_PTHREAD, and SQLCIPHER_MUTEX_W32 implementations
5888 ** are appropriate for use on OS/2, Unix, and Windows.
5889 **
5890 ** ^(If SQLite is compiled with the SQLCIPHER_MUTEX_APPDEF preprocessor
5891 ** macro defined (with "-DSQLCIPHER_MUTEX_APPDEF=1"), then no mutex
5892 ** implementation is included with the library. In this case the
5893 ** application must supply a custom mutex implementation using the
5894 ** [SQLCIPHER_CONFIG_MUTEX] option of the sqlcipher3_config() function
5895 ** before calling sqlcipher3_initialize() or any other public sqlcipher3_
5896 ** function that calls sqlcipher3_initialize().)^
5897 **
5898 ** ^The sqlcipher3_mutex_alloc() routine allocates a new
5899 ** mutex and returns a pointer to it. ^If it returns NULL
5900 ** that means that a mutex could not be allocated.  ^SQLite
5901 ** will unwind its stack and return an error.  ^(The argument
5902 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
5903 **
5904 ** <ul>
5905 ** <li>  SQLCIPHER_MUTEX_FAST
5906 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
5907 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
5908 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
5909 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
5910 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
5911 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
5912 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU2
5913 ** </ul>)^
5914 **
5915 ** ^The first two constants (SQLCIPHER_MUTEX_FAST and SQLCIPHER_MUTEX_RECURSIVE)
5916 ** cause sqlcipher3_mutex_alloc() to create
5917 ** a new mutex.  ^The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
5918 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
5919 ** The mutex implementation does not need to make a distinction
5920 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
5921 ** not want to.  ^SQLite will only request a recursive mutex in
5922 ** cases where it really needs one.  ^If a faster non-recursive mutex
5923 ** implementation is available on the host platform, the mutex subsystem
5924 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
5925 **
5926 ** ^The other allowed parameters to sqlcipher3_mutex_alloc() (anything other
5927 ** than SQLCIPHER_MUTEX_FAST and SQLCIPHER_MUTEX_RECURSIVE) each return
5928 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5929 ** used by the current version of SQLite.  Future versions of SQLite
5930 ** may add additional static mutexes.  Static mutexes are for internal
5931 ** use by SQLite only.  Applications that use SQLite mutexes should
5932 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
5933 ** SQLCIPHER_MUTEX_RECURSIVE.
5934 **
5935 ** ^Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
5936 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
5937 ** returns a different mutex on every call.  ^But for the static
5938 ** mutex types, the same mutex is returned on every call that has
5939 ** the same type number.
5940 **
5941 ** ^The sqlcipher3_mutex_free() routine deallocates a previously
5942 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5943 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5944 ** use when they are deallocated.  Attempting to deallocate a static
5945 ** mutex results in undefined behavior.  ^SQLite never deallocates
5946 ** a static mutex.
5947 **
5948 ** ^The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
5949 ** to enter a mutex.  ^If another thread is already within the mutex,
5950 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
5951 ** SQLCIPHER_BUSY.  ^The sqlcipher3_mutex_try() interface returns [SQLCIPHER_OK]
5952 ** upon successful entry.  ^(Mutexes created using
5953 ** SQLCIPHER_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5954 ** In such cases the,
5955 ** mutex must be exited an equal number of times before another thread
5956 ** can enter.)^  ^(If the same thread tries to enter any other
5957 ** kind of mutex more than once, the behavior is undefined.
5958 ** SQLite will never exhibit
5959 ** such behavior in its own use of mutexes.)^
5960 **
5961 ** ^(Some systems (for example, Windows 95) do not support the operation
5962 ** implemented by sqlcipher3_mutex_try().  On those systems, sqlcipher3_mutex_try()
5963 ** will always return SQLCIPHER_BUSY.  The SQLite core only ever uses
5964 ** sqlcipher3_mutex_try() as an optimization so this is acceptable behavior.)^
5965 **
5966 ** ^The sqlcipher3_mutex_leave() routine exits a mutex that was
5967 ** previously entered by the same thread.   ^(The behavior
5968 ** is undefined if the mutex is not currently entered by the
5969 ** calling thread or is not currently allocated.  SQLite will
5970 ** never do either.)^
5971 **
5972 ** ^If the argument to sqlcipher3_mutex_enter(), sqlcipher3_mutex_try(), or
5973 ** sqlcipher3_mutex_leave() is a NULL pointer, then all three routines
5974 ** behave as no-ops.
5975 **
5976 ** See also: [sqlcipher3_mutex_held()] and [sqlcipher3_mutex_notheld()].
5977 */
5978 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_mutex_alloc(int);
5979 SQLCIPHER_API void sqlcipher3_mutex_free(sqlcipher3_mutex*);
5980 SQLCIPHER_API void sqlcipher3_mutex_enter(sqlcipher3_mutex*);
5981 SQLCIPHER_API int sqlcipher3_mutex_try(sqlcipher3_mutex*);
5982 SQLCIPHER_API void sqlcipher3_mutex_leave(sqlcipher3_mutex*);
5983
5984 /*
5985 ** CAPI3REF: Mutex Methods Object
5986 **
5987 ** An instance of this structure defines the low-level routines
5988 ** used to allocate and use mutexes.
5989 **
5990 ** Usually, the default mutex implementations provided by SQLite are
5991 ** sufficient, however the user has the option of substituting a custom
5992 ** implementation for specialized deployments or systems for which SQLite
5993 ** does not provide a suitable implementation. In this case, the user
5994 ** creates and populates an instance of this structure to pass
5995 ** to sqlcipher3_config() along with the [SQLCIPHER_CONFIG_MUTEX] option.
5996 ** Additionally, an instance of this structure can be used as an
5997 ** output variable when querying the system for the current mutex
5998 ** implementation, using the [SQLCIPHER_CONFIG_GETMUTEX] option.
5999 **
6000 ** ^The xMutexInit method defined by this structure is invoked as
6001 ** part of system initialization by the sqlcipher3_initialize() function.
6002 ** ^The xMutexInit routine is called by SQLite exactly once for each
6003 ** effective call to [sqlcipher3_initialize()].
6004 **
6005 ** ^The xMutexEnd method defined by this structure is invoked as
6006 ** part of system shutdown by the sqlcipher3_shutdown() function. The
6007 ** implementation of this method is expected to release all outstanding
6008 ** resources obtained by the mutex methods implementation, especially
6009 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6010 ** interface is invoked exactly once for each call to [sqlcipher3_shutdown()].
6011 **
6012 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6013 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6014 ** xMutexNotheld) implement the following interfaces (respectively):
6015 **
6016 ** <ul>
6017 **   <li>  [sqlcipher3_mutex_alloc()] </li>
6018 **   <li>  [sqlcipher3_mutex_free()] </li>
6019 **   <li>  [sqlcipher3_mutex_enter()] </li>
6020 **   <li>  [sqlcipher3_mutex_try()] </li>
6021 **   <li>  [sqlcipher3_mutex_leave()] </li>
6022 **   <li>  [sqlcipher3_mutex_held()] </li>
6023 **   <li>  [sqlcipher3_mutex_notheld()] </li>
6024 ** </ul>)^
6025 **
6026 ** The only difference is that the public sqlcipher3_XXX functions enumerated
6027 ** above silently ignore any invocations that pass a NULL pointer instead
6028 ** of a valid mutex handle. The implementations of the methods defined
6029 ** by this structure are not required to handle this case, the results
6030 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6031 ** (i.e. it is acceptable to provide an implementation that segfaults if
6032 ** it is passed a NULL pointer).
6033 **
6034 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6035 ** invoke xMutexInit() multiple times within the same process and without
6036 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6037 ** xMutexInit() must be no-ops.
6038 **
6039 ** ^xMutexInit() must not use SQLite memory allocation ([sqlcipher3_malloc()]
6040 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6041 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6042 ** memory allocation for a fast or recursive mutex.
6043 **
6044 ** ^SQLite will invoke the xMutexEnd() method when [sqlcipher3_shutdown()] is
6045 ** called, but only if the prior call to xMutexInit returned SQLCIPHER_OK.
6046 ** If xMutexInit fails in any way, it is expected to clean up after itself
6047 ** prior to returning.
6048 */
6049 typedef struct sqlcipher3_mutex_methods sqlcipher3_mutex_methods;
6050 struct sqlcipher3_mutex_methods {
6051   int (*xMutexInit)(void);
6052   int (*xMutexEnd)(void);
6053   sqlcipher3_mutex *(*xMutexAlloc)(int);
6054   void (*xMutexFree)(sqlcipher3_mutex *);
6055   void (*xMutexEnter)(sqlcipher3_mutex *);
6056   int (*xMutexTry)(sqlcipher3_mutex *);
6057   void (*xMutexLeave)(sqlcipher3_mutex *);
6058   int (*xMutexHeld)(sqlcipher3_mutex *);
6059   int (*xMutexNotheld)(sqlcipher3_mutex *);
6060 };
6061
6062 /*
6063 ** CAPI3REF: Mutex Verification Routines
6064 **
6065 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routines
6066 ** are intended for use inside assert() statements.  ^The SQLite core
6067 ** never uses these routines except inside an assert() and applications
6068 ** are advised to follow the lead of the core.  ^The SQLite core only
6069 ** provides implementations for these routines when it is compiled
6070 ** with the SQLCIPHER_DEBUG flag.  ^External mutex implementations
6071 ** are only required to provide these routines if SQLCIPHER_DEBUG is
6072 ** defined and if NDEBUG is not defined.
6073 **
6074 ** ^These routines should return true if the mutex in their argument
6075 ** is held or not held, respectively, by the calling thread.
6076 **
6077 ** ^The implementation is not required to provided versions of these
6078 ** routines that actually work. If the implementation does not provide working
6079 ** versions of these routines, it should at least provide stubs that always
6080 ** return true so that one does not get spurious assertion failures.
6081 **
6082 ** ^If the argument to sqlcipher3_mutex_held() is a NULL pointer then
6083 ** the routine should return 1.   This seems counter-intuitive since
6084 ** clearly the mutex cannot be held if it does not exist.  But
6085 ** the reason the mutex does not exist is because the build is not
6086 ** using mutexes.  And we do not want the assert() containing the
6087 ** call to sqlcipher3_mutex_held() to fail, so a non-zero return is
6088 ** the appropriate thing to do.  ^The sqlcipher3_mutex_notheld()
6089 ** interface should also return 1 when given a NULL pointer.
6090 */
6091 #ifndef NDEBUG
6092 SQLCIPHER_API int sqlcipher3_mutex_held(sqlcipher3_mutex*);
6093 SQLCIPHER_API int sqlcipher3_mutex_notheld(sqlcipher3_mutex*);
6094 #endif
6095
6096 /*
6097 ** CAPI3REF: Mutex Types
6098 **
6099 ** The [sqlcipher3_mutex_alloc()] interface takes a single argument
6100 ** which is one of these integer constants.
6101 **
6102 ** The set of static mutexes may change from one SQLite release to the
6103 ** next.  Applications that override the built-in mutex logic must be
6104 ** prepared to accommodate additional static mutexes.
6105 */
6106 #define SQLCIPHER_MUTEX_FAST             0
6107 #define SQLCIPHER_MUTEX_RECURSIVE        1
6108 #define SQLCIPHER_MUTEX_STATIC_MASTER    2
6109 #define SQLCIPHER_MUTEX_STATIC_MEM       3  /* sqlcipher3_malloc() */
6110 #define SQLCIPHER_MUTEX_STATIC_MEM2      4  /* NOT USED */
6111 #define SQLCIPHER_MUTEX_STATIC_OPEN      4  /* sqlcipher3BtreeOpen() */
6112 #define SQLCIPHER_MUTEX_STATIC_PRNG      5  /* sqlcipher3_random() */
6113 #define SQLCIPHER_MUTEX_STATIC_LRU       6  /* lru page list */
6114 #define SQLCIPHER_MUTEX_STATIC_LRU2      7  /* NOT USED */
6115 #define SQLCIPHER_MUTEX_STATIC_PMEM      7  /* sqlcipher3PageMalloc() */
6116
6117 /*
6118 ** CAPI3REF: Retrieve the mutex for a database connection
6119 **
6120 ** ^This interface returns a pointer the [sqlcipher3_mutex] object that 
6121 ** serializes access to the [database connection] given in the argument
6122 ** when the [threading mode] is Serialized.
6123 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6124 ** routine returns a NULL pointer.
6125 */
6126 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_db_mutex(sqlcipher3*);
6127
6128 /*
6129 ** CAPI3REF: Low-Level Control Of Database Files
6130 **
6131 ** ^The [sqlcipher3_file_control()] interface makes a direct call to the
6132 ** xFileControl method for the [sqlcipher3_io_methods] object associated
6133 ** with a particular database identified by the second argument. ^The
6134 ** name of the database is "main" for the main database or "temp" for the
6135 ** TEMP database, or the name that appears after the AS keyword for
6136 ** databases that are added using the [ATTACH] SQL command.
6137 ** ^A NULL pointer can be used in place of "main" to refer to the
6138 ** main database file.
6139 ** ^The third and fourth parameters to this routine
6140 ** are passed directly through to the second and third parameters of
6141 ** the xFileControl method.  ^The return value of the xFileControl
6142 ** method becomes the return value of this routine.
6143 **
6144 ** ^The SQLCIPHER_FCNTL_FILE_POINTER value for the op parameter causes
6145 ** a pointer to the underlying [sqlcipher3_file] object to be written into
6146 ** the space pointed to by the 4th parameter.  ^The SQLCIPHER_FCNTL_FILE_POINTER
6147 ** case is a short-circuit path which does not actually invoke the
6148 ** underlying sqlcipher3_io_methods.xFileControl method.
6149 **
6150 ** ^If the second parameter (zDbName) does not match the name of any
6151 ** open database file, then SQLCIPHER_ERROR is returned.  ^This error
6152 ** code is not remembered and will not be recalled by [sqlcipher3_errcode()]
6153 ** or [sqlcipher3_errmsg()].  The underlying xFileControl method might
6154 ** also return SQLCIPHER_ERROR.  There is no way to distinguish between
6155 ** an incorrect zDbName and an SQLCIPHER_ERROR return from the underlying
6156 ** xFileControl method.
6157 **
6158 ** See also: [SQLCIPHER_FCNTL_LOCKSTATE]
6159 */
6160 SQLCIPHER_API int sqlcipher3_file_control(sqlcipher3*, const char *zDbName, int op, void*);
6161
6162 /*
6163 ** CAPI3REF: Testing Interface
6164 **
6165 ** ^The sqlcipher3_test_control() interface is used to read out internal
6166 ** state of SQLite and to inject faults into SQLite for testing
6167 ** purposes.  ^The first parameter is an operation code that determines
6168 ** the number, meaning, and operation of all subsequent parameters.
6169 **
6170 ** This interface is not for use by applications.  It exists solely
6171 ** for verifying the correct operation of the SQLite library.  Depending
6172 ** on how the SQLite library is compiled, this interface might not exist.
6173 **
6174 ** The details of the operation codes, their meanings, the parameters
6175 ** they take, and what they do are all subject to change without notice.
6176 ** Unlike most of the SQLite API, this function is not guaranteed to
6177 ** operate consistently from one release to the next.
6178 */
6179 SQLCIPHER_API int sqlcipher3_test_control(int op, ...);
6180
6181 /*
6182 ** CAPI3REF: Testing Interface Operation Codes
6183 **
6184 ** These constants are the valid operation code parameters used
6185 ** as the first argument to [sqlcipher3_test_control()].
6186 **
6187 ** These parameters and their meanings are subject to change
6188 ** without notice.  These values are for testing purposes only.
6189 ** Applications should not use any of these parameters or the
6190 ** [sqlcipher3_test_control()] interface.
6191 */
6192 #define SQLCIPHER_TESTCTRL_FIRST                    5
6193 #define SQLCIPHER_TESTCTRL_PRNG_SAVE                5
6194 #define SQLCIPHER_TESTCTRL_PRNG_RESTORE             6
6195 #define SQLCIPHER_TESTCTRL_PRNG_RESET               7
6196 #define SQLCIPHER_TESTCTRL_BITVEC_TEST              8
6197 #define SQLCIPHER_TESTCTRL_FAULT_INSTALL            9
6198 #define SQLCIPHER_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6199 #define SQLCIPHER_TESTCTRL_PENDING_BYTE            11
6200 #define SQLCIPHER_TESTCTRL_ASSERT                  12
6201 #define SQLCIPHER_TESTCTRL_ALWAYS                  13
6202 #define SQLCIPHER_TESTCTRL_RESERVE                 14
6203 #define SQLCIPHER_TESTCTRL_OPTIMIZATIONS           15
6204 #define SQLCIPHER_TESTCTRL_ISKEYWORD               16
6205 #define SQLCIPHER_TESTCTRL_PGHDRSZ                 17
6206 #define SQLCIPHER_TESTCTRL_SCRATCHMALLOC           18
6207 #define SQLCIPHER_TESTCTRL_LOCALTIME_FAULT         19
6208 #define SQLCIPHER_TESTCTRL_LAST                    19
6209
6210 /*
6211 ** CAPI3REF: SQLite Runtime Status
6212 **
6213 ** ^This interface is used to retrieve runtime status information
6214 ** about the performance of SQLite, and optionally to reset various
6215 ** highwater marks.  ^The first argument is an integer code for
6216 ** the specific parameter to measure.  ^(Recognized integer codes
6217 ** are of the form [status parameters | SQLCIPHER_STATUS_...].)^
6218 ** ^The current value of the parameter is returned into *pCurrent.
6219 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6220 ** resetFlag is true, then the highest record value is reset after
6221 ** *pHighwater is written.  ^(Some parameters do not record the highest
6222 ** value.  For those parameters
6223 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6224 ** ^(Other parameters record only the highwater mark and not the current
6225 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6226 **
6227 ** ^The sqlcipher3_status() routine returns SQLCIPHER_OK on success and a
6228 ** non-zero [error code] on failure.
6229 **
6230 ** This routine is threadsafe but is not atomic.  This routine can be
6231 ** called while other threads are running the same or different SQLite
6232 ** interfaces.  However the values returned in *pCurrent and
6233 ** *pHighwater reflect the status of SQLite at different points in time
6234 ** and it is possible that another thread might change the parameter
6235 ** in between the times when *pCurrent and *pHighwater are written.
6236 **
6237 ** See also: [sqlcipher3_db_status()]
6238 */
6239 SQLCIPHER_API int sqlcipher3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6240
6241
6242 /*
6243 ** CAPI3REF: Status Parameters
6244 ** KEYWORDS: {status parameters}
6245 **
6246 ** These integer constants designate various run-time status parameters
6247 ** that can be returned by [sqlcipher3_status()].
6248 **
6249 ** <dl>
6250 ** [[SQLCIPHER_STATUS_MEMORY_USED]] ^(<dt>SQLCIPHER_STATUS_MEMORY_USED</dt>
6251 ** <dd>This parameter is the current amount of memory checked out
6252 ** using [sqlcipher3_malloc()], either directly or indirectly.  The
6253 ** figure includes calls made to [sqlcipher3_malloc()] by the application
6254 ** and internal memory usage by the SQLite library.  Scratch memory
6255 ** controlled by [SQLCIPHER_CONFIG_SCRATCH] and auxiliary page-cache
6256 ** memory controlled by [SQLCIPHER_CONFIG_PAGECACHE] is not included in
6257 ** this parameter.  The amount returned is the sum of the allocation
6258 ** sizes as reported by the xSize method in [sqlcipher3_mem_methods].</dd>)^
6259 **
6260 ** [[SQLCIPHER_STATUS_MALLOC_SIZE]] ^(<dt>SQLCIPHER_STATUS_MALLOC_SIZE</dt>
6261 ** <dd>This parameter records the largest memory allocation request
6262 ** handed to [sqlcipher3_malloc()] or [sqlcipher3_realloc()] (or their
6263 ** internal equivalents).  Only the value returned in the
6264 ** *pHighwater parameter to [sqlcipher3_status()] is of interest.  
6265 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6266 **
6267 ** [[SQLCIPHER_STATUS_MALLOC_COUNT]] ^(<dt>SQLCIPHER_STATUS_MALLOC_COUNT</dt>
6268 ** <dd>This parameter records the number of separate memory allocations
6269 ** currently checked out.</dd>)^
6270 **
6271 ** [[SQLCIPHER_STATUS_PAGECACHE_USED]] ^(<dt>SQLCIPHER_STATUS_PAGECACHE_USED</dt>
6272 ** <dd>This parameter returns the number of pages used out of the
6273 ** [pagecache memory allocator] that was configured using 
6274 ** [SQLCIPHER_CONFIG_PAGECACHE].  The
6275 ** value returned is in pages, not in bytes.</dd>)^
6276 **
6277 ** [[SQLCIPHER_STATUS_PAGECACHE_OVERFLOW]] 
6278 ** ^(<dt>SQLCIPHER_STATUS_PAGECACHE_OVERFLOW</dt>
6279 ** <dd>This parameter returns the number of bytes of page cache
6280 ** allocation which could not be satisfied by the [SQLCIPHER_CONFIG_PAGECACHE]
6281 ** buffer and where forced to overflow to [sqlcipher3_malloc()].  The
6282 ** returned value includes allocations that overflowed because they
6283 ** where too large (they were larger than the "sz" parameter to
6284 ** [SQLCIPHER_CONFIG_PAGECACHE]) and allocations that overflowed because
6285 ** no space was left in the page cache.</dd>)^
6286 **
6287 ** [[SQLCIPHER_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLCIPHER_STATUS_PAGECACHE_SIZE</dt>
6288 ** <dd>This parameter records the largest memory allocation request
6289 ** handed to [pagecache memory allocator].  Only the value returned in the
6290 ** *pHighwater parameter to [sqlcipher3_status()] is of interest.  
6291 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6292 **
6293 ** [[SQLCIPHER_STATUS_SCRATCH_USED]] ^(<dt>SQLCIPHER_STATUS_SCRATCH_USED</dt>
6294 ** <dd>This parameter returns the number of allocations used out of the
6295 ** [scratch memory allocator] configured using
6296 ** [SQLCIPHER_CONFIG_SCRATCH].  The value returned is in allocations, not
6297 ** in bytes.  Since a single thread may only have one scratch allocation
6298 ** outstanding at time, this parameter also reports the number of threads
6299 ** using scratch memory at the same time.</dd>)^
6300 **
6301 ** [[SQLCIPHER_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLCIPHER_STATUS_SCRATCH_OVERFLOW</dt>
6302 ** <dd>This parameter returns the number of bytes of scratch memory
6303 ** allocation which could not be satisfied by the [SQLCIPHER_CONFIG_SCRATCH]
6304 ** buffer and where forced to overflow to [sqlcipher3_malloc()].  The values
6305 ** returned include overflows because the requested allocation was too
6306 ** larger (that is, because the requested allocation was larger than the
6307 ** "sz" parameter to [SQLCIPHER_CONFIG_SCRATCH]) and because no scratch buffer
6308 ** slots were available.
6309 ** </dd>)^
6310 **
6311 ** [[SQLCIPHER_STATUS_SCRATCH_SIZE]] ^(<dt>SQLCIPHER_STATUS_SCRATCH_SIZE</dt>
6312 ** <dd>This parameter records the largest memory allocation request
6313 ** handed to [scratch memory allocator].  Only the value returned in the
6314 ** *pHighwater parameter to [sqlcipher3_status()] is of interest.  
6315 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6316 **
6317 ** [[SQLCIPHER_STATUS_PARSER_STACK]] ^(<dt>SQLCIPHER_STATUS_PARSER_STACK</dt>
6318 ** <dd>This parameter records the deepest parser stack.  It is only
6319 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6320 ** </dl>
6321 **
6322 ** New status parameters may be added from time to time.
6323 */
6324 #define SQLCIPHER_STATUS_MEMORY_USED          0
6325 #define SQLCIPHER_STATUS_PAGECACHE_USED       1
6326 #define SQLCIPHER_STATUS_PAGECACHE_OVERFLOW   2
6327 #define SQLCIPHER_STATUS_SCRATCH_USED         3
6328 #define SQLCIPHER_STATUS_SCRATCH_OVERFLOW     4
6329 #define SQLCIPHER_STATUS_MALLOC_SIZE          5
6330 #define SQLCIPHER_STATUS_PARSER_STACK         6
6331 #define SQLCIPHER_STATUS_PAGECACHE_SIZE       7
6332 #define SQLCIPHER_STATUS_SCRATCH_SIZE         8
6333 #define SQLCIPHER_STATUS_MALLOC_COUNT         9
6334
6335 /*
6336 ** CAPI3REF: Database Connection Status
6337 **
6338 ** ^This interface is used to retrieve runtime status information 
6339 ** about a single [database connection].  ^The first argument is the
6340 ** database connection object to be interrogated.  ^The second argument
6341 ** is an integer constant, taken from the set of
6342 ** [SQLCIPHER_DBSTATUS options], that
6343 ** determines the parameter to interrogate.  The set of 
6344 ** [SQLCIPHER_DBSTATUS options] is likely
6345 ** to grow in future releases of SQLite.
6346 **
6347 ** ^The current value of the requested parameter is written into *pCur
6348 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6349 ** the resetFlg is true, then the highest instantaneous value is
6350 ** reset back down to the current value.
6351 **
6352 ** ^The sqlcipher3_db_status() routine returns SQLCIPHER_OK on success and a
6353 ** non-zero [error code] on failure.
6354 **
6355 ** See also: [sqlcipher3_status()] and [sqlcipher3_stmt_status()].
6356 */
6357 SQLCIPHER_API int sqlcipher3_db_status(sqlcipher3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6358
6359 /*
6360 ** CAPI3REF: Status Parameters for database connections
6361 ** KEYWORDS: {SQLCIPHER_DBSTATUS options}
6362 **
6363 ** These constants are the available integer "verbs" that can be passed as
6364 ** the second argument to the [sqlcipher3_db_status()] interface.
6365 **
6366 ** New verbs may be added in future releases of SQLite. Existing verbs
6367 ** might be discontinued. Applications should check the return code from
6368 ** [sqlcipher3_db_status()] to make sure that the call worked.
6369 ** The [sqlcipher3_db_status()] interface will return a non-zero error code
6370 ** if a discontinued or unsupported verb is invoked.
6371 **
6372 ** <dl>
6373 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_USED</dt>
6374 ** <dd>This parameter returns the number of lookaside memory slots currently
6375 ** checked out.</dd>)^
6376 **
6377 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_HIT</dt>
6378 ** <dd>This parameter returns the number malloc attempts that were 
6379 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6380 ** the current value is always zero.)^
6381 **
6382 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6383 ** ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6384 ** <dd>This parameter returns the number malloc attempts that might have
6385 ** been satisfied using lookaside memory but failed due to the amount of
6386 ** memory requested being larger than the lookaside slot size.
6387 ** Only the high-water value is meaningful;
6388 ** the current value is always zero.)^
6389 **
6390 ** [[SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL]]
6391 ** ^(<dt>SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6392 ** <dd>This parameter returns the number malloc attempts that might have
6393 ** been satisfied using lookaside memory but failed due to all lookaside
6394 ** memory already being in use.
6395 ** Only the high-water value is meaningful;
6396 ** the current value is always zero.)^
6397 **
6398 ** [[SQLCIPHER_DBSTATUS_CACHE_USED]] ^(<dt>SQLCIPHER_DBSTATUS_CACHE_USED</dt>
6399 ** <dd>This parameter returns the approximate number of of bytes of heap
6400 ** memory used by all pager caches associated with the database connection.)^
6401 ** ^The highwater mark associated with SQLCIPHER_DBSTATUS_CACHE_USED is always 0.
6402 **
6403 ** [[SQLCIPHER_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLCIPHER_DBSTATUS_SCHEMA_USED</dt>
6404 ** <dd>This parameter returns the approximate number of of bytes of heap
6405 ** memory used to store the schema for all databases associated
6406 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6407 ** ^The full amount of memory used by the schemas is reported, even if the
6408 ** schema memory is shared with other database connections due to
6409 ** [shared cache mode] being enabled.
6410 ** ^The highwater mark associated with SQLCIPHER_DBSTATUS_SCHEMA_USED is always 0.
6411 **
6412 ** [[SQLCIPHER_DBSTATUS_STMT_USED]] ^(<dt>SQLCIPHER_DBSTATUS_STMT_USED</dt>
6413 ** <dd>This parameter returns the approximate number of of bytes of heap
6414 ** and lookaside memory used by all prepared statements associated with
6415 ** the database connection.)^
6416 ** ^The highwater mark associated with SQLCIPHER_DBSTATUS_STMT_USED is always 0.
6417 ** </dd>
6418 **
6419 ** [[SQLCIPHER_DBSTATUS_CACHE_HIT]] ^(<dt>SQLCIPHER_DBSTATUS_CACHE_HIT</dt>
6420 ** <dd>This parameter returns the number of pager cache hits that have
6421 ** occurred.)^ ^The highwater mark associated with SQLCIPHER_DBSTATUS_CACHE_HIT 
6422 ** is always 0.
6423 ** </dd>
6424 **
6425 ** [[SQLCIPHER_DBSTATUS_CACHE_MISS]] ^(<dt>SQLCIPHER_DBSTATUS_CACHE_MISS</dt>
6426 ** <dd>This parameter returns the number of pager cache misses that have
6427 ** occurred.)^ ^The highwater mark associated with SQLCIPHER_DBSTATUS_CACHE_MISS 
6428 ** is always 0.
6429 ** </dd>
6430 ** </dl>
6431 */
6432 #define SQLCIPHER_DBSTATUS_LOOKASIDE_USED       0
6433 #define SQLCIPHER_DBSTATUS_CACHE_USED           1
6434 #define SQLCIPHER_DBSTATUS_SCHEMA_USED          2
6435 #define SQLCIPHER_DBSTATUS_STMT_USED            3
6436 #define SQLCIPHER_DBSTATUS_LOOKASIDE_HIT        4
6437 #define SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6438 #define SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL  6
6439 #define SQLCIPHER_DBSTATUS_CACHE_HIT            7
6440 #define SQLCIPHER_DBSTATUS_CACHE_MISS           8
6441 #define SQLCIPHER_DBSTATUS_MAX                  8   /* Largest defined DBSTATUS */
6442
6443
6444 /*
6445 ** CAPI3REF: Prepared Statement Status
6446 **
6447 ** ^(Each prepared statement maintains various
6448 ** [SQLCIPHER_STMTSTATUS counters] that measure the number
6449 ** of times it has performed specific operations.)^  These counters can
6450 ** be used to monitor the performance characteristics of the prepared
6451 ** statements.  For example, if the number of table steps greatly exceeds
6452 ** the number of table searches or result rows, that would tend to indicate
6453 ** that the prepared statement is using a full table scan rather than
6454 ** an index.  
6455 **
6456 ** ^(This interface is used to retrieve and reset counter values from
6457 ** a [prepared statement].  The first argument is the prepared statement
6458 ** object to be interrogated.  The second argument
6459 ** is an integer code for a specific [SQLCIPHER_STMTSTATUS counter]
6460 ** to be interrogated.)^
6461 ** ^The current value of the requested counter is returned.
6462 ** ^If the resetFlg is true, then the counter is reset to zero after this
6463 ** interface call returns.
6464 **
6465 ** See also: [sqlcipher3_status()] and [sqlcipher3_db_status()].
6466 */
6467 SQLCIPHER_API int sqlcipher3_stmt_status(sqlcipher3_stmt*, int op,int resetFlg);
6468
6469 /*
6470 ** CAPI3REF: Status Parameters for prepared statements
6471 ** KEYWORDS: {SQLCIPHER_STMTSTATUS counter} {SQLCIPHER_STMTSTATUS counters}
6472 **
6473 ** These preprocessor macros define integer codes that name counter
6474 ** values associated with the [sqlcipher3_stmt_status()] interface.
6475 ** The meanings of the various counters are as follows:
6476 **
6477 ** <dl>
6478 ** [[SQLCIPHER_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLCIPHER_STMTSTATUS_FULLSCAN_STEP</dt>
6479 ** <dd>^This is the number of times that SQLite has stepped forward in
6480 ** a table as part of a full table scan.  Large numbers for this counter
6481 ** may indicate opportunities for performance improvement through 
6482 ** careful use of indices.</dd>
6483 **
6484 ** [[SQLCIPHER_STMTSTATUS_SORT]] <dt>SQLCIPHER_STMTSTATUS_SORT</dt>
6485 ** <dd>^This is the number of sort operations that have occurred.
6486 ** A non-zero value in this counter may indicate an opportunity to
6487 ** improvement performance through careful use of indices.</dd>
6488 **
6489 ** [[SQLCIPHER_STMTSTATUS_AUTOINDEX]] <dt>SQLCIPHER_STMTSTATUS_AUTOINDEX</dt>
6490 ** <dd>^This is the number of rows inserted into transient indices that
6491 ** were created automatically in order to help joins run faster.
6492 ** A non-zero value in this counter may indicate an opportunity to
6493 ** improvement performance by adding permanent indices that do not
6494 ** need to be reinitialized each time the statement is run.</dd>
6495 ** </dl>
6496 */
6497 #define SQLCIPHER_STMTSTATUS_FULLSCAN_STEP     1
6498 #define SQLCIPHER_STMTSTATUS_SORT              2
6499 #define SQLCIPHER_STMTSTATUS_AUTOINDEX         3
6500
6501 /*
6502 ** CAPI3REF: Custom Page Cache Object
6503 **
6504 ** The sqlcipher3_pcache type is opaque.  It is implemented by
6505 ** the pluggable module.  The SQLite core has no knowledge of
6506 ** its size or internal structure and never deals with the
6507 ** sqlcipher3_pcache object except by holding and passing pointers
6508 ** to the object.
6509 **
6510 ** See [sqlcipher3_pcache_methods] for additional information.
6511 */
6512 typedef struct sqlcipher3_pcache sqlcipher3_pcache;
6513
6514 /*
6515 ** CAPI3REF: Application Defined Page Cache.
6516 ** KEYWORDS: {page cache}
6517 **
6518 ** ^(The [sqlcipher3_config]([SQLCIPHER_CONFIG_PCACHE], ...) interface can
6519 ** register an alternative page cache implementation by passing in an 
6520 ** instance of the sqlcipher3_pcache_methods structure.)^
6521 ** In many applications, most of the heap memory allocated by 
6522 ** SQLite is used for the page cache.
6523 ** By implementing a 
6524 ** custom page cache using this API, an application can better control
6525 ** the amount of memory consumed by SQLite, the way in which 
6526 ** that memory is allocated and released, and the policies used to 
6527 ** determine exactly which parts of a database file are cached and for 
6528 ** how long.
6529 **
6530 ** The alternative page cache mechanism is an
6531 ** extreme measure that is only needed by the most demanding applications.
6532 ** The built-in page cache is recommended for most uses.
6533 **
6534 ** ^(The contents of the sqlcipher3_pcache_methods structure are copied to an
6535 ** internal buffer by SQLite within the call to [sqlcipher3_config].  Hence
6536 ** the application may discard the parameter after the call to
6537 ** [sqlcipher3_config()] returns.)^
6538 **
6539 ** [[the xInit() page cache method]]
6540 ** ^(The xInit() method is called once for each effective 
6541 ** call to [sqlcipher3_initialize()])^
6542 ** (usually only once during the lifetime of the process). ^(The xInit()
6543 ** method is passed a copy of the sqlcipher3_pcache_methods.pArg value.)^
6544 ** The intent of the xInit() method is to set up global data structures 
6545 ** required by the custom page cache implementation. 
6546 ** ^(If the xInit() method is NULL, then the 
6547 ** built-in default page cache is used instead of the application defined
6548 ** page cache.)^
6549 **
6550 ** [[the xShutdown() page cache method]]
6551 ** ^The xShutdown() method is called by [sqlcipher3_shutdown()].
6552 ** It can be used to clean up 
6553 ** any outstanding resources before process shutdown, if required.
6554 ** ^The xShutdown() method may be NULL.
6555 **
6556 ** ^SQLite automatically serializes calls to the xInit method,
6557 ** so the xInit method need not be threadsafe.  ^The
6558 ** xShutdown method is only called from [sqlcipher3_shutdown()] so it does
6559 ** not need to be threadsafe either.  All other methods must be threadsafe
6560 ** in multithreaded applications.
6561 **
6562 ** ^SQLite will never invoke xInit() more than once without an intervening
6563 ** call to xShutdown().
6564 **
6565 ** [[the xCreate() page cache methods]]
6566 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6567 ** SQLite will typically create one cache instance for each open database file,
6568 ** though this is not guaranteed. ^The
6569 ** first parameter, szPage, is the size in bytes of the pages that must
6570 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6571 ** will the page size of the database file that is to be cached plus an
6572 ** increment (here called "R") of less than 250.  SQLite will use the
6573 ** extra R bytes on each page to store metadata about the underlying
6574 ** database page on disk.  The value of R depends
6575 ** on the SQLite version, the target platform, and how SQLite was compiled.
6576 ** ^(R is constant for a particular build of SQLite. Except, there are two
6577 ** distinct values of R when SQLite is compiled with the proprietary
6578 ** ZIPVFS extension.)^  ^The second argument to
6579 ** xCreate(), bPurgeable, is true if the cache being created will
6580 ** be used to cache database pages of a file stored on disk, or
6581 ** false if it is used for an in-memory database. The cache implementation
6582 ** does not have to do anything special based with the value of bPurgeable;
6583 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6584 ** never invoke xUnpin() except to deliberately delete a page.
6585 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6586 ** false will always have the "discard" flag set to true.  
6587 ** ^Hence, a cache created with bPurgeable false will
6588 ** never contain any unpinned pages.
6589 **
6590 ** [[the xCachesize() page cache method]]
6591 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6592 ** suggested maximum cache-size (number of pages stored by) the cache
6593 ** instance passed as the first argument. This is the value configured using
6594 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6595 ** parameter, the implementation is not required to do anything with this
6596 ** value; it is advisory only.
6597 **
6598 ** [[the xPagecount() page cache methods]]
6599 ** The xPagecount() method must return the number of pages currently
6600 ** stored in the cache, both pinned and unpinned.
6601 ** 
6602 ** [[the xFetch() page cache methods]]
6603 ** The xFetch() method locates a page in the cache and returns a pointer to 
6604 ** the page, or a NULL pointer.
6605 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6606 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6607 ** minimum key value is 1.  After it has been retrieved using xFetch, the page 
6608 ** is considered to be "pinned".
6609 **
6610 ** If the requested page is already in the page cache, then the page cache
6611 ** implementation must return a pointer to the page buffer with its content
6612 ** intact.  If the requested page is not already in the cache, then the
6613 ** cache implementation should use the value of the createFlag
6614 ** parameter to help it determined what action to take:
6615 **
6616 ** <table border=1 width=85% align=center>
6617 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6618 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6619 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6620 **                 Otherwise return NULL.
6621 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6622 **                 NULL if allocating a new page is effectively impossible.
6623 ** </table>
6624 **
6625 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6626 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6627 ** failed.)^  In between the to xFetch() calls, SQLite may
6628 ** attempt to unpin one or more cache pages by spilling the content of
6629 ** pinned pages to disk and synching the operating system disk cache.
6630 **
6631 ** [[the xUnpin() page cache method]]
6632 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6633 ** as its second argument.  If the third parameter, discard, is non-zero,
6634 ** then the page must be evicted from the cache.
6635 ** ^If the discard parameter is
6636 ** zero, then the page may be discarded or retained at the discretion of
6637 ** page cache implementation. ^The page cache implementation
6638 ** may choose to evict unpinned pages at any time.
6639 **
6640 ** The cache must not perform any reference counting. A single 
6641 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6642 ** to xFetch().
6643 **
6644 ** [[the xRekey() page cache methods]]
6645 ** The xRekey() method is used to change the key value associated with the
6646 ** page passed as the second argument. If the cache
6647 ** previously contains an entry associated with newKey, it must be
6648 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6649 ** to be pinned.
6650 **
6651 ** When SQLite calls the xTruncate() method, the cache must discard all
6652 ** existing cache entries with page numbers (keys) greater than or equal
6653 ** to the value of the iLimit parameter passed to xTruncate(). If any
6654 ** of these pages are pinned, they are implicitly unpinned, meaning that
6655 ** they can be safely discarded.
6656 **
6657 ** [[the xDestroy() page cache method]]
6658 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6659 ** All resources associated with the specified cache should be freed. ^After
6660 ** calling the xDestroy() method, SQLite considers the [sqlcipher3_pcache*]
6661 ** handle invalid, and will not use it with any other sqlcipher3_pcache_methods
6662 ** functions.
6663 */
6664 typedef struct sqlcipher3_pcache_methods sqlcipher3_pcache_methods;
6665 struct sqlcipher3_pcache_methods {
6666   void *pArg;
6667   int (*xInit)(void*);
6668   void (*xShutdown)(void*);
6669   sqlcipher3_pcache *(*xCreate)(int szPage, int bPurgeable);
6670   void (*xCachesize)(sqlcipher3_pcache*, int nCachesize);
6671   int (*xPagecount)(sqlcipher3_pcache*);
6672   void *(*xFetch)(sqlcipher3_pcache*, unsigned key, int createFlag);
6673   void (*xUnpin)(sqlcipher3_pcache*, void*, int discard);
6674   void (*xRekey)(sqlcipher3_pcache*, void*, unsigned oldKey, unsigned newKey);
6675   void (*xTruncate)(sqlcipher3_pcache*, unsigned iLimit);
6676   void (*xDestroy)(sqlcipher3_pcache*);
6677 };
6678
6679 /*
6680 ** CAPI3REF: Online Backup Object
6681 **
6682 ** The sqlcipher3_backup object records state information about an ongoing
6683 ** online backup operation.  ^The sqlcipher3_backup object is created by
6684 ** a call to [sqlcipher3_backup_init()] and is destroyed by a call to
6685 ** [sqlcipher3_backup_finish()].
6686 **
6687 ** See Also: [Using the SQLite Online Backup API]
6688 */
6689 typedef struct sqlcipher3_backup sqlcipher3_backup;
6690
6691 /*
6692 ** CAPI3REF: Online Backup API.
6693 **
6694 ** The backup API copies the content of one database into another.
6695 ** It is useful either for creating backups of databases or
6696 ** for copying in-memory databases to or from persistent files. 
6697 **
6698 ** See Also: [Using the SQLite Online Backup API]
6699 **
6700 ** ^SQLite holds a write transaction open on the destination database file
6701 ** for the duration of the backup operation.
6702 ** ^The source database is read-locked only while it is being read;
6703 ** it is not locked continuously for the entire backup operation.
6704 ** ^Thus, the backup may be performed on a live source database without
6705 ** preventing other database connections from
6706 ** reading or writing to the source database while the backup is underway.
6707 ** 
6708 ** ^(To perform a backup operation: 
6709 **   <ol>
6710 **     <li><b>sqlcipher3_backup_init()</b> is called once to initialize the
6711 **         backup, 
6712 **     <li><b>sqlcipher3_backup_step()</b> is called one or more times to transfer 
6713 **         the data between the two databases, and finally
6714 **     <li><b>sqlcipher3_backup_finish()</b> is called to release all resources 
6715 **         associated with the backup operation. 
6716 **   </ol>)^
6717 ** There should be exactly one call to sqlcipher3_backup_finish() for each
6718 ** successful call to sqlcipher3_backup_init().
6719 **
6720 ** [[sqlcipher3_backup_init()]] <b>sqlcipher3_backup_init()</b>
6721 **
6722 ** ^The D and N arguments to sqlcipher3_backup_init(D,N,S,M) are the 
6723 ** [database connection] associated with the destination database 
6724 ** and the database name, respectively.
6725 ** ^The database name is "main" for the main database, "temp" for the
6726 ** temporary database, or the name specified after the AS keyword in
6727 ** an [ATTACH] statement for an attached database.
6728 ** ^The S and M arguments passed to 
6729 ** sqlcipher3_backup_init(D,N,S,M) identify the [database connection]
6730 ** and database name of the source database, respectively.
6731 ** ^The source and destination [database connections] (parameters S and D)
6732 ** must be different or else sqlcipher3_backup_init(D,N,S,M) will fail with
6733 ** an error.
6734 **
6735 ** ^If an error occurs within sqlcipher3_backup_init(D,N,S,M), then NULL is
6736 ** returned and an error code and error message are stored in the
6737 ** destination [database connection] D.
6738 ** ^The error code and message for the failed call to sqlcipher3_backup_init()
6739 ** can be retrieved using the [sqlcipher3_errcode()], [sqlcipher3_errmsg()], and/or
6740 ** [sqlcipher3_errmsg16()] functions.
6741 ** ^A successful call to sqlcipher3_backup_init() returns a pointer to an
6742 ** [sqlcipher3_backup] object.
6743 ** ^The [sqlcipher3_backup] object may be used with the sqlcipher3_backup_step() and
6744 ** sqlcipher3_backup_finish() functions to perform the specified backup 
6745 ** operation.
6746 **
6747 ** [[sqlcipher3_backup_step()]] <b>sqlcipher3_backup_step()</b>
6748 **
6749 ** ^Function sqlcipher3_backup_step(B,N) will copy up to N pages between 
6750 ** the source and destination databases specified by [sqlcipher3_backup] object B.
6751 ** ^If N is negative, all remaining source pages are copied. 
6752 ** ^If sqlcipher3_backup_step(B,N) successfully copies N pages and there
6753 ** are still more pages to be copied, then the function returns [SQLCIPHER_OK].
6754 ** ^If sqlcipher3_backup_step(B,N) successfully finishes copying all pages
6755 ** from source to destination, then it returns [SQLCIPHER_DONE].
6756 ** ^If an error occurs while running sqlcipher3_backup_step(B,N),
6757 ** then an [error code] is returned. ^As well as [SQLCIPHER_OK] and
6758 ** [SQLCIPHER_DONE], a call to sqlcipher3_backup_step() may return [SQLCIPHER_READONLY],
6759 ** [SQLCIPHER_NOMEM], [SQLCIPHER_BUSY], [SQLCIPHER_LOCKED], or an
6760 ** [SQLCIPHER_IOERR_ACCESS | SQLCIPHER_IOERR_XXX] extended error code.
6761 **
6762 ** ^(The sqlcipher3_backup_step() might return [SQLCIPHER_READONLY] if
6763 ** <ol>
6764 ** <li> the destination database was opened read-only, or
6765 ** <li> the destination database is using write-ahead-log journaling
6766 ** and the destination and source page sizes differ, or
6767 ** <li> the destination database is an in-memory database and the
6768 ** destination and source page sizes differ.
6769 ** </ol>)^
6770 **
6771 ** ^If sqlcipher3_backup_step() cannot obtain a required file-system lock, then
6772 ** the [sqlcipher3_busy_handler | busy-handler function]
6773 ** is invoked (if one is specified). ^If the 
6774 ** busy-handler returns non-zero before the lock is available, then 
6775 ** [SQLCIPHER_BUSY] is returned to the caller. ^In this case the call to
6776 ** sqlcipher3_backup_step() can be retried later. ^If the source
6777 ** [database connection]
6778 ** is being used to write to the source database when sqlcipher3_backup_step()
6779 ** is called, then [SQLCIPHER_LOCKED] is returned immediately. ^Again, in this
6780 ** case the call to sqlcipher3_backup_step() can be retried later on. ^(If
6781 ** [SQLCIPHER_IOERR_ACCESS | SQLCIPHER_IOERR_XXX], [SQLCIPHER_NOMEM], or
6782 ** [SQLCIPHER_READONLY] is returned, then 
6783 ** there is no point in retrying the call to sqlcipher3_backup_step(). These 
6784 ** errors are considered fatal.)^  The application must accept 
6785 ** that the backup operation has failed and pass the backup operation handle 
6786 ** to the sqlcipher3_backup_finish() to release associated resources.
6787 **
6788 ** ^The first call to sqlcipher3_backup_step() obtains an exclusive lock
6789 ** on the destination file. ^The exclusive lock is not released until either 
6790 ** sqlcipher3_backup_finish() is called or the backup operation is complete 
6791 ** and sqlcipher3_backup_step() returns [SQLCIPHER_DONE].  ^Every call to
6792 ** sqlcipher3_backup_step() obtains a [shared lock] on the source database that
6793 ** lasts for the duration of the sqlcipher3_backup_step() call.
6794 ** ^Because the source database is not locked between calls to
6795 ** sqlcipher3_backup_step(), the source database may be modified mid-way
6796 ** through the backup process.  ^If the source database is modified by an
6797 ** external process or via a database connection other than the one being
6798 ** used by the backup operation, then the backup will be automatically
6799 ** restarted by the next call to sqlcipher3_backup_step(). ^If the source 
6800 ** database is modified by the using the same database connection as is used
6801 ** by the backup operation, then the backup database is automatically
6802 ** updated at the same time.
6803 **
6804 ** [[sqlcipher3_backup_finish()]] <b>sqlcipher3_backup_finish()</b>
6805 **
6806 ** When sqlcipher3_backup_step() has returned [SQLCIPHER_DONE], or when the 
6807 ** application wishes to abandon the backup operation, the application
6808 ** should destroy the [sqlcipher3_backup] by passing it to sqlcipher3_backup_finish().
6809 ** ^The sqlcipher3_backup_finish() interfaces releases all
6810 ** resources associated with the [sqlcipher3_backup] object. 
6811 ** ^If sqlcipher3_backup_step() has not yet returned [SQLCIPHER_DONE], then any
6812 ** active write-transaction on the destination database is rolled back.
6813 ** The [sqlcipher3_backup] object is invalid
6814 ** and may not be used following a call to sqlcipher3_backup_finish().
6815 **
6816 ** ^The value returned by sqlcipher3_backup_finish is [SQLCIPHER_OK] if no
6817 ** sqlcipher3_backup_step() errors occurred, regardless or whether or not
6818 ** sqlcipher3_backup_step() completed.
6819 ** ^If an out-of-memory condition or IO error occurred during any prior
6820 ** sqlcipher3_backup_step() call on the same [sqlcipher3_backup] object, then
6821 ** sqlcipher3_backup_finish() returns the corresponding [error code].
6822 **
6823 ** ^A return of [SQLCIPHER_BUSY] or [SQLCIPHER_LOCKED] from sqlcipher3_backup_step()
6824 ** is not a permanent error and does not affect the return value of
6825 ** sqlcipher3_backup_finish().
6826 **
6827 ** [[sqlcipher3_backup__remaining()]] [[sqlcipher3_backup_pagecount()]]
6828 ** <b>sqlcipher3_backup_remaining() and sqlcipher3_backup_pagecount()</b>
6829 **
6830 ** ^Each call to sqlcipher3_backup_step() sets two values inside
6831 ** the [sqlcipher3_backup] object: the number of pages still to be backed
6832 ** up and the total number of pages in the source database file.
6833 ** The sqlcipher3_backup_remaining() and sqlcipher3_backup_pagecount() interfaces
6834 ** retrieve these two values, respectively.
6835 **
6836 ** ^The values returned by these functions are only updated by
6837 ** sqlcipher3_backup_step(). ^If the source database is modified during a backup
6838 ** operation, then the values are not updated to account for any extra
6839 ** pages that need to be updated or the size of the source database file
6840 ** changing.
6841 **
6842 ** <b>Concurrent Usage of Database Handles</b>
6843 **
6844 ** ^The source [database connection] may be used by the application for other
6845 ** purposes while a backup operation is underway or being initialized.
6846 ** ^If SQLite is compiled and configured to support threadsafe database
6847 ** connections, then the source database connection may be used concurrently
6848 ** from within other threads.
6849 **
6850 ** However, the application must guarantee that the destination 
6851 ** [database connection] is not passed to any other API (by any thread) after 
6852 ** sqlcipher3_backup_init() is called and before the corresponding call to
6853 ** sqlcipher3_backup_finish().  SQLite does not currently check to see
6854 ** if the application incorrectly accesses the destination [database connection]
6855 ** and so no error code is reported, but the operations may malfunction
6856 ** nevertheless.  Use of the destination database connection while a
6857 ** backup is in progress might also also cause a mutex deadlock.
6858 **
6859 ** If running in [shared cache mode], the application must
6860 ** guarantee that the shared cache used by the destination database
6861 ** is not accessed while the backup is running. In practice this means
6862 ** that the application must guarantee that the disk file being 
6863 ** backed up to is not accessed by any connection within the process,
6864 ** not just the specific connection that was passed to sqlcipher3_backup_init().
6865 **
6866 ** The [sqlcipher3_backup] object itself is partially threadsafe. Multiple 
6867 ** threads may safely make multiple concurrent calls to sqlcipher3_backup_step().
6868 ** However, the sqlcipher3_backup_remaining() and sqlcipher3_backup_pagecount()
6869 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6870 ** same time as another thread is invoking sqlcipher3_backup_step() it is
6871 ** possible that they return invalid values.
6872 */
6873 SQLCIPHER_API sqlcipher3_backup *sqlcipher3_backup_init(
6874   sqlcipher3 *pDest,                        /* Destination database handle */
6875   const char *zDestName,                 /* Destination database name */
6876   sqlcipher3 *pSource,                      /* Source database handle */
6877   const char *zSourceName                /* Source database name */
6878 );
6879 SQLCIPHER_API int sqlcipher3_backup_step(sqlcipher3_backup *p, int nPage);
6880 SQLCIPHER_API int sqlcipher3_backup_finish(sqlcipher3_backup *p);
6881 SQLCIPHER_API int sqlcipher3_backup_remaining(sqlcipher3_backup *p);
6882 SQLCIPHER_API int sqlcipher3_backup_pagecount(sqlcipher3_backup *p);
6883
6884 /*
6885 ** CAPI3REF: Unlock Notification
6886 **
6887 ** ^When running in shared-cache mode, a database operation may fail with
6888 ** an [SQLCIPHER_LOCKED] error if the required locks on the shared-cache or
6889 ** individual tables within the shared-cache cannot be obtained. See
6890 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6891 ** ^This API may be used to register a callback that SQLite will invoke 
6892 ** when the connection currently holding the required lock relinquishes it.
6893 ** ^This API is only available if the library was compiled with the
6894 ** [SQLCIPHER_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6895 **
6896 ** See Also: [Using the SQLite Unlock Notification Feature].
6897 **
6898 ** ^Shared-cache locks are released when a database connection concludes
6899 ** its current transaction, either by committing it or rolling it back. 
6900 **
6901 ** ^When a connection (known as the blocked connection) fails to obtain a
6902 ** shared-cache lock and SQLCIPHER_LOCKED is returned to the caller, the
6903 ** identity of the database connection (the blocking connection) that
6904 ** has locked the required resource is stored internally. ^After an 
6905 ** application receives an SQLCIPHER_LOCKED error, it may call the
6906 ** sqlcipher3_unlock_notify() method with the blocked connection handle as 
6907 ** the first argument to register for a callback that will be invoked
6908 ** when the blocking connections current transaction is concluded. ^The
6909 ** callback is invoked from within the [sqlcipher3_step] or [sqlcipher3_close]
6910 ** call that concludes the blocking connections transaction.
6911 **
6912 ** ^(If sqlcipher3_unlock_notify() is called in a multi-threaded application,
6913 ** there is a chance that the blocking connection will have already
6914 ** concluded its transaction by the time sqlcipher3_unlock_notify() is invoked.
6915 ** If this happens, then the specified callback is invoked immediately,
6916 ** from within the call to sqlcipher3_unlock_notify().)^
6917 **
6918 ** ^If the blocked connection is attempting to obtain a write-lock on a
6919 ** shared-cache table, and more than one other connection currently holds
6920 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6921 ** the other connections to use as the blocking connection.
6922 **
6923 ** ^(There may be at most one unlock-notify callback registered by a 
6924 ** blocked connection. If sqlcipher3_unlock_notify() is called when the
6925 ** blocked connection already has a registered unlock-notify callback,
6926 ** then the new callback replaces the old.)^ ^If sqlcipher3_unlock_notify() is
6927 ** called with a NULL pointer as its second argument, then any existing
6928 ** unlock-notify callback is canceled. ^The blocked connections 
6929 ** unlock-notify callback may also be canceled by closing the blocked
6930 ** connection using [sqlcipher3_close()].
6931 **
6932 ** The unlock-notify callback is not reentrant. If an application invokes
6933 ** any sqlcipher3_xxx API functions from within an unlock-notify callback, a
6934 ** crash or deadlock may be the result.
6935 **
6936 ** ^Unless deadlock is detected (see below), sqlcipher3_unlock_notify() always
6937 ** returns SQLCIPHER_OK.
6938 **
6939 ** <b>Callback Invocation Details</b>
6940 **
6941 ** When an unlock-notify callback is registered, the application provides a 
6942 ** single void* pointer that is passed to the callback when it is invoked.
6943 ** However, the signature of the callback function allows SQLite to pass
6944 ** it an array of void* context pointers. The first argument passed to
6945 ** an unlock-notify callback is a pointer to an array of void* pointers,
6946 ** and the second is the number of entries in the array.
6947 **
6948 ** When a blocking connections transaction is concluded, there may be
6949 ** more than one blocked connection that has registered for an unlock-notify
6950 ** callback. ^If two or more such blocked connections have specified the
6951 ** same callback function, then instead of invoking the callback function
6952 ** multiple times, it is invoked once with the set of void* context pointers
6953 ** specified by the blocked connections bundled together into an array.
6954 ** This gives the application an opportunity to prioritize any actions 
6955 ** related to the set of unblocked database connections.
6956 **
6957 ** <b>Deadlock Detection</b>
6958 **
6959 ** Assuming that after registering for an unlock-notify callback a 
6960 ** database waits for the callback to be issued before taking any further
6961 ** action (a reasonable assumption), then using this API may cause the
6962 ** application to deadlock. For example, if connection X is waiting for
6963 ** connection Y's transaction to be concluded, and similarly connection
6964 ** Y is waiting on connection X's transaction, then neither connection
6965 ** will proceed and the system may remain deadlocked indefinitely.
6966 **
6967 ** To avoid this scenario, the sqlcipher3_unlock_notify() performs deadlock
6968 ** detection. ^If a given call to sqlcipher3_unlock_notify() would put the
6969 ** system in a deadlocked state, then SQLCIPHER_LOCKED is returned and no
6970 ** unlock-notify callback is registered. The system is said to be in
6971 ** a deadlocked state if connection A has registered for an unlock-notify
6972 ** callback on the conclusion of connection B's transaction, and connection
6973 ** B has itself registered for an unlock-notify callback when connection
6974 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6975 ** the system is also considered to be deadlocked if connection B has
6976 ** registered for an unlock-notify callback on the conclusion of connection
6977 ** C's transaction, where connection C is waiting on connection A. ^Any
6978 ** number of levels of indirection are allowed.
6979 **
6980 ** <b>The "DROP TABLE" Exception</b>
6981 **
6982 ** When a call to [sqlcipher3_step()] returns SQLCIPHER_LOCKED, it is almost 
6983 ** always appropriate to call sqlcipher3_unlock_notify(). There is however,
6984 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6985 ** SQLite checks if there are any currently executing SELECT statements
6986 ** that belong to the same connection. If there are, SQLCIPHER_LOCKED is
6987 ** returned. In this case there is no "blocking connection", so invoking
6988 ** sqlcipher3_unlock_notify() results in the unlock-notify callback being
6989 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6990 ** or "DROP INDEX" query, an infinite loop might be the result.
6991 **
6992 ** One way around this problem is to check the extended error code returned
6993 ** by an sqlcipher3_step() call. ^(If there is a blocking connection, then the
6994 ** extended error code is set to SQLCIPHER_LOCKED_SHAREDCACHE. Otherwise, in
6995 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6996 ** SQLCIPHER_LOCKED.)^
6997 */
6998 SQLCIPHER_API int sqlcipher3_unlock_notify(
6999   sqlcipher3 *pBlocked,                          /* Waiting connection */
7000   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7001   void *pNotifyArg                            /* Argument to pass to xNotify */
7002 );
7003
7004
7005 /*
7006 ** CAPI3REF: String Comparison
7007 **
7008 ** ^The [sqlcipher3_strnicmp()] API allows applications and extensions to
7009 ** compare the contents of two buffers containing UTF-8 strings in a
7010 ** case-independent fashion, using the same definition of case independence 
7011 ** that SQLite uses internally when comparing identifiers.
7012 */
7013 SQLCIPHER_API int sqlcipher3_strnicmp(const char *, const char *, int);
7014
7015 /*
7016 ** CAPI3REF: Error Logging Interface
7017 **
7018 ** ^The [sqlcipher3_log()] interface writes a message into the error log
7019 ** established by the [SQLCIPHER_CONFIG_LOG] option to [sqlcipher3_config()].
7020 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7021 ** used with [sqlcipher3_snprintf()] to generate the final output string.
7022 **
7023 ** The sqlcipher3_log() interface is intended for use by extensions such as
7024 ** virtual tables, collating functions, and SQL functions.  While there is
7025 ** nothing to prevent an application from calling sqlcipher3_log(), doing so
7026 ** is considered bad form.
7027 **
7028 ** The zFormat string must not be NULL.
7029 **
7030 ** To avoid deadlocks and other threading problems, the sqlcipher3_log() routine
7031 ** will not use dynamically allocated memory.  The log message is stored in
7032 ** a fixed-length buffer on the stack.  If the log message is longer than
7033 ** a few hundred characters, it will be truncated to the length of the
7034 ** buffer.
7035 */
7036 SQLCIPHER_API void sqlcipher3_log(int iErrCode, const char *zFormat, ...);
7037
7038 /*
7039 ** CAPI3REF: Write-Ahead Log Commit Hook
7040 **
7041 ** ^The [sqlcipher3_wal_hook()] function is used to register a callback that
7042 ** will be invoked each time a database connection commits data to a
7043 ** [write-ahead log] (i.e. whenever a transaction is committed in
7044 ** [journal_mode | journal_mode=WAL mode]). 
7045 **
7046 ** ^The callback is invoked by SQLite after the commit has taken place and 
7047 ** the associated write-lock on the database released, so the implementation 
7048 ** may read, write or [checkpoint] the database as required.
7049 **
7050 ** ^The first parameter passed to the callback function when it is invoked
7051 ** is a copy of the third parameter passed to sqlcipher3_wal_hook() when
7052 ** registering the callback. ^The second is a copy of the database handle.
7053 ** ^The third parameter is the name of the database that was written to -
7054 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7055 ** is the number of pages currently in the write-ahead log file,
7056 ** including those that were just committed.
7057 **
7058 ** The callback function should normally return [SQLCIPHER_OK].  ^If an error
7059 ** code is returned, that error will propagate back up through the
7060 ** SQLite code base to cause the statement that provoked the callback
7061 ** to report an error, though the commit will have still occurred. If the
7062 ** callback returns [SQLCIPHER_ROW] or [SQLCIPHER_DONE], or if it returns a value
7063 ** that does not correspond to any valid SQLite error code, the results
7064 ** are undefined.
7065 **
7066 ** A single database handle may have at most a single write-ahead log callback 
7067 ** registered at one time. ^Calling [sqlcipher3_wal_hook()] replaces any
7068 ** previously registered write-ahead log callback. ^Note that the
7069 ** [sqlcipher3_wal_autocheckpoint()] interface and the
7070 ** [wal_autocheckpoint pragma] both invoke [sqlcipher3_wal_hook()] and will
7071 ** those overwrite any prior [sqlcipher3_wal_hook()] settings.
7072 */
7073 SQLCIPHER_API void *sqlcipher3_wal_hook(
7074   sqlcipher3*, 
7075   int(*)(void *,sqlcipher3*,const char*,int),
7076   void*
7077 );
7078
7079 /*
7080 ** CAPI3REF: Configure an auto-checkpoint
7081 **
7082 ** ^The [sqlcipher3_wal_autocheckpoint(D,N)] is a wrapper around
7083 ** [sqlcipher3_wal_hook()] that causes any database on [database connection] D
7084 ** to automatically [checkpoint]
7085 ** after committing a transaction if there are N or
7086 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7087 ** a negative value as the nFrame parameter disables automatic
7088 ** checkpoints entirely.
7089 **
7090 ** ^The callback registered by this function replaces any existing callback
7091 ** registered using [sqlcipher3_wal_hook()].  ^Likewise, registering a callback
7092 ** using [sqlcipher3_wal_hook()] disables the automatic checkpoint mechanism
7093 ** configured by this function.
7094 **
7095 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7096 ** from SQL.
7097 **
7098 ** ^Every new [database connection] defaults to having the auto-checkpoint
7099 ** enabled with a threshold of 1000 or [SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT]
7100 ** pages.  The use of this interface
7101 ** is only necessary if the default setting is found to be suboptimal
7102 ** for a particular application.
7103 */
7104 SQLCIPHER_API int sqlcipher3_wal_autocheckpoint(sqlcipher3 *db, int N);
7105
7106 /*
7107 ** CAPI3REF: Checkpoint a database
7108 **
7109 ** ^The [sqlcipher3_wal_checkpoint(D,X)] interface causes database named X
7110 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7111 ** empty string, then a checkpoint is run on all databases of
7112 ** connection D.  ^If the database connection D is not in
7113 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7114 **
7115 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7116 ** from SQL.  ^The [sqlcipher3_wal_autocheckpoint()] interface and the
7117 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7118 ** run whenever the WAL reaches a certain size threshold.
7119 **
7120 ** See also: [sqlcipher3_wal_checkpoint_v2()]
7121 */
7122 SQLCIPHER_API int sqlcipher3_wal_checkpoint(sqlcipher3 *db, const char *zDb);
7123
7124 /*
7125 ** CAPI3REF: Checkpoint a database
7126 **
7127 ** Run a checkpoint operation on WAL database zDb attached to database 
7128 ** handle db. The specific operation is determined by the value of the 
7129 ** eMode parameter:
7130 **
7131 ** <dl>
7132 ** <dt>SQLCIPHER_CHECKPOINT_PASSIVE<dd>
7133 **   Checkpoint as many frames as possible without waiting for any database 
7134 **   readers or writers to finish. Sync the db file if all frames in the log
7135 **   are checkpointed. This mode is the same as calling 
7136 **   sqlcipher3_wal_checkpoint(). The busy-handler callback is never invoked.
7137 **
7138 ** <dt>SQLCIPHER_CHECKPOINT_FULL<dd>
7139 **   This mode blocks (calls the busy-handler callback) until there is no
7140 **   database writer and all readers are reading from the most recent database
7141 **   snapshot. It then checkpoints all frames in the log file and syncs the
7142 **   database file. This call blocks database writers while it is running,
7143 **   but not database readers.
7144 **
7145 ** <dt>SQLCIPHER_CHECKPOINT_RESTART<dd>
7146 **   This mode works the same way as SQLCIPHER_CHECKPOINT_FULL, except after 
7147 **   checkpointing the log file it blocks (calls the busy-handler callback)
7148 **   until all readers are reading from the database file only. This ensures 
7149 **   that the next client to write to the database file restarts the log file 
7150 **   from the beginning. This call blocks database writers while it is running,
7151 **   but not database readers.
7152 ** </dl>
7153 **
7154 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7155 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7156 ** the total number of checkpointed frames (including any that were already
7157 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7158 ** populated even if sqlcipher3_wal_checkpoint_v2() returns other than SQLCIPHER_OK.
7159 ** If no values are available because of an error, they are both set to -1
7160 ** before returning to communicate this to the caller.
7161 **
7162 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7163 ** any other process is running a checkpoint operation at the same time, the 
7164 ** lock cannot be obtained and SQLCIPHER_BUSY is returned. Even if there is a 
7165 ** busy-handler configured, it will not be invoked in this case.
7166 **
7167 ** The SQLCIPHER_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7168 ** "writer" lock on the database file. If the writer lock cannot be obtained
7169 ** immediately, and a busy-handler is configured, it is invoked and the writer
7170 ** lock retried until either the busy-handler returns 0 or the lock is
7171 ** successfully obtained. The busy-handler is also invoked while waiting for
7172 ** database readers as described above. If the busy-handler returns 0 before
7173 ** the writer lock is obtained or while waiting for database readers, the
7174 ** checkpoint operation proceeds from that point in the same way as 
7175 ** SQLCIPHER_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7176 ** without blocking any further. SQLCIPHER_BUSY is returned in this case.
7177 **
7178 ** If parameter zDb is NULL or points to a zero length string, then the
7179 ** specified operation is attempted on all WAL databases. In this case the
7180 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7181 ** an SQLCIPHER_BUSY error is encountered when processing one or more of the 
7182 ** attached WAL databases, the operation is still attempted on any remaining 
7183 ** attached databases and SQLCIPHER_BUSY is returned to the caller. If any other 
7184 ** error occurs while processing an attached database, processing is abandoned 
7185 ** and the error code returned to the caller immediately. If no error 
7186 ** (SQLCIPHER_BUSY or otherwise) is encountered while processing the attached 
7187 ** databases, SQLCIPHER_OK is returned.
7188 **
7189 ** If database zDb is the name of an attached database that is not in WAL
7190 ** mode, SQLCIPHER_OK is returned and both *pnLog and *pnCkpt set to -1. If
7191 ** zDb is not NULL (or a zero length string) and is not the name of any
7192 ** attached database, SQLCIPHER_ERROR is returned to the caller.
7193 */
7194 SQLCIPHER_API int sqlcipher3_wal_checkpoint_v2(
7195   sqlcipher3 *db,                    /* Database handle */
7196   const char *zDb,                /* Name of attached database (or NULL) */
7197   int eMode,                      /* SQLCIPHER_CHECKPOINT_* value */
7198   int *pnLog,                     /* OUT: Size of WAL log in frames */
7199   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7200 );
7201
7202 /*
7203 ** CAPI3REF: Checkpoint operation parameters
7204 **
7205 ** These constants can be used as the 3rd parameter to
7206 ** [sqlcipher3_wal_checkpoint_v2()].  See the [sqlcipher3_wal_checkpoint_v2()]
7207 ** documentation for additional information about the meaning and use of
7208 ** each of these values.
7209 */
7210 #define SQLCIPHER_CHECKPOINT_PASSIVE 0
7211 #define SQLCIPHER_CHECKPOINT_FULL    1
7212 #define SQLCIPHER_CHECKPOINT_RESTART 2
7213
7214 /*
7215 ** CAPI3REF: Virtual Table Interface Configuration
7216 **
7217 ** This function may be called by either the [xConnect] or [xCreate] method
7218 ** of a [virtual table] implementation to configure
7219 ** various facets of the virtual table interface.
7220 **
7221 ** If this interface is invoked outside the context of an xConnect or
7222 ** xCreate virtual table method then the behavior is undefined.
7223 **
7224 ** At present, there is only one option that may be configured using
7225 ** this function. (See [SQLCIPHER_VTAB_CONSTRAINT_SUPPORT].)  Further options
7226 ** may be added in the future.
7227 */
7228 SQLCIPHER_API int sqlcipher3_vtab_config(sqlcipher3*, int op, ...);
7229
7230 /*
7231 ** CAPI3REF: Virtual Table Configuration Options
7232 **
7233 ** These macros define the various options to the
7234 ** [sqlcipher3_vtab_config()] interface that [virtual table] implementations
7235 ** can use to customize and optimize their behavior.
7236 **
7237 ** <dl>
7238 ** <dt>SQLCIPHER_VTAB_CONSTRAINT_SUPPORT
7239 ** <dd>Calls of the form
7240 ** [sqlcipher3_vtab_config](db,SQLCIPHER_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7241 ** where X is an integer.  If X is zero, then the [virtual table] whose
7242 ** [xCreate] or [xConnect] method invoked [sqlcipher3_vtab_config()] does not
7243 ** support constraints.  In this configuration (which is the default) if
7244 ** a call to the [xUpdate] method returns [SQLCIPHER_CONSTRAINT], then the entire
7245 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7246 ** specified as part of the users SQL statement, regardless of the actual
7247 ** ON CONFLICT mode specified.
7248 **
7249 ** If X is non-zero, then the virtual table implementation guarantees
7250 ** that if [xUpdate] returns [SQLCIPHER_CONSTRAINT], it will do so before
7251 ** any modifications to internal or persistent data structures have been made.
7252 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7253 ** is able to roll back a statement or database transaction, and abandon
7254 ** or continue processing the current SQL statement as appropriate. 
7255 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7256 ** [SQLCIPHER_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7257 ** had been ABORT.
7258 **
7259 ** Virtual table implementations that are required to handle OR REPLACE
7260 ** must do so within the [xUpdate] method. If a call to the 
7261 ** [sqlcipher3_vtab_on_conflict()] function indicates that the current ON 
7262 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7263 ** silently replace the appropriate rows within the xUpdate callback and
7264 ** return SQLCIPHER_OK. Or, if this is not possible, it may return
7265 ** SQLCIPHER_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7266 ** constraint handling.
7267 ** </dl>
7268 */
7269 #define SQLCIPHER_VTAB_CONSTRAINT_SUPPORT 1
7270
7271 /*
7272 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7273 **
7274 ** This function may only be called from within a call to the [xUpdate] method
7275 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7276 ** value returned is one of [SQLCIPHER_ROLLBACK], [SQLCIPHER_IGNORE], [SQLCIPHER_FAIL],
7277 ** [SQLCIPHER_ABORT], or [SQLCIPHER_REPLACE], according to the [ON CONFLICT] mode
7278 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7279 ** [virtual table].
7280 */
7281 SQLCIPHER_API int sqlcipher3_vtab_on_conflict(sqlcipher3 *);
7282
7283 /*
7284 ** CAPI3REF: Conflict resolution modes
7285 **
7286 ** These constants are returned by [sqlcipher3_vtab_on_conflict()] to
7287 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7288 ** is for the SQL statement being evaluated.
7289 **
7290 ** Note that the [SQLCIPHER_IGNORE] constant is also used as a potential
7291 ** return value from the [sqlcipher3_set_authorizer()] callback and that
7292 ** [SQLCIPHER_ABORT] is also a [result code].
7293 */
7294 #define SQLCIPHER_ROLLBACK 1
7295 /* #define SQLCIPHER_IGNORE 2 // Also used by sqlcipher3_authorizer() callback */
7296 #define SQLCIPHER_FAIL     3
7297 /* #define SQLCIPHER_ABORT 4  // Also an error code */
7298 #define SQLCIPHER_REPLACE  5
7299
7300
7301
7302 /*
7303 ** Undo the hack that converts floating point types to integer for
7304 ** builds on processors without floating point support.
7305 */
7306 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
7307 # undef double
7308 #endif
7309
7310 #if 0
7311 }  /* End of the 'extern "C"' block */
7312 #endif
7313 #endif
7314
7315 /*
7316 ** 2010 August 30
7317 **
7318 ** The author disclaims copyright to this source code.  In place of
7319 ** a legal notice, here is a blessing:
7320 **
7321 **    May you do good and not evil.
7322 **    May you find forgiveness for yourself and forgive others.
7323 **    May you share freely, never taking more than you give.
7324 **
7325 *************************************************************************
7326 */
7327
7328 #ifndef _SQLCIPHER3RTREE_H_
7329 #define _SQLCIPHER3RTREE_H_
7330
7331
7332 #if 0
7333 extern "C" {
7334 #endif
7335
7336 typedef struct sqlcipher3_rtree_geometry sqlcipher3_rtree_geometry;
7337
7338 /*
7339 ** Register a geometry callback named zGeom that can be used as part of an
7340 ** R-Tree geometry query as follows:
7341 **
7342 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7343 */
7344 SQLCIPHER_API int sqlcipher3_rtree_geometry_callback(
7345   sqlcipher3 *db,
7346   const char *zGeom,
7347   int (*xGeom)(sqlcipher3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7348   void *pContext
7349 );
7350
7351
7352 /*
7353 ** A pointer to a structure of the following type is passed as the first
7354 ** argument to callbacks registered using rtree_geometry_callback().
7355 */
7356 struct sqlcipher3_rtree_geometry {
7357   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7358   int nParam;                     /* Size of array aParam[] */
7359   double *aParam;                 /* Parameters passed to SQL geom function */
7360   void *pUser;                    /* Callback implementation user data */
7361   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7362 };
7363
7364
7365 #if 0
7366 }  /* end of the 'extern "C"' block */
7367 #endif
7368
7369 #endif  /* ifndef _SQLCIPHER3RTREE_H_ */
7370
7371
7372 /************** End of sqlcipher3.h *********************************************/
7373 /************** Continuing where we left off in sqlcipherInt.h ******************/
7374 /************** Include hash.h in the middle of sqlcipherInt.h ******************/
7375 /************** Begin file hash.h ********************************************/
7376 /*
7377 ** 2001 September 22
7378 **
7379 ** The author disclaims copyright to this source code.  In place of
7380 ** a legal notice, here is a blessing:
7381 **
7382 **    May you do good and not evil.
7383 **    May you find forgiveness for yourself and forgive others.
7384 **    May you share freely, never taking more than you give.
7385 **
7386 *************************************************************************
7387 ** This is the header file for the generic hash-table implemenation
7388 ** used in SQLite.
7389 */
7390 #ifndef _SQLCIPHER_HASH_H_
7391 #define _SQLCIPHER_HASH_H_
7392
7393 /* Forward declarations of structures. */
7394 typedef struct Hash Hash;
7395 typedef struct HashElem HashElem;
7396
7397 /* A complete hash table is an instance of the following structure.
7398 ** The internals of this structure are intended to be opaque -- client
7399 ** code should not attempt to access or modify the fields of this structure
7400 ** directly.  Change this structure only by using the routines below.
7401 ** However, some of the "procedures" and "functions" for modifying and
7402 ** accessing this structure are really macros, so we can't really make
7403 ** this structure opaque.
7404 **
7405 ** All elements of the hash table are on a single doubly-linked list.
7406 ** Hash.first points to the head of this list.
7407 **
7408 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7409 ** the global doubly-linked list.  The contents of the bucket are the
7410 ** element pointed to plus the next _ht.count-1 elements in the list.
7411 **
7412 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7413 ** by a linear search of the global list.  For small tables, the 
7414 ** Hash.ht table is never allocated because if there are few elements
7415 ** in the table, it is faster to do a linear search than to manage
7416 ** the hash table.
7417 */
7418 struct Hash {
7419   unsigned int htsize;      /* Number of buckets in the hash table */
7420   unsigned int count;       /* Number of entries in this table */
7421   HashElem *first;          /* The first element of the array */
7422   struct _ht {              /* the hash table */
7423     int count;                 /* Number of entries with this hash */
7424     HashElem *chain;           /* Pointer to first entry with this hash */
7425   } *ht;
7426 };
7427
7428 /* Each element in the hash table is an instance of the following 
7429 ** structure.  All elements are stored on a single doubly-linked list.
7430 **
7431 ** Again, this structure is intended to be opaque, but it can't really
7432 ** be opaque because it is used by macros.
7433 */
7434 struct HashElem {
7435   HashElem *next, *prev;       /* Next and previous elements in the table */
7436   void *data;                  /* Data associated with this element */
7437   const char *pKey; int nKey;  /* Key associated with this element */
7438 };
7439
7440 /*
7441 ** Access routines.  To delete, insert a NULL pointer.
7442 */
7443 SQLCIPHER_PRIVATE void sqlcipher3HashInit(Hash*);
7444 SQLCIPHER_PRIVATE void *sqlcipher3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7445 SQLCIPHER_PRIVATE void *sqlcipher3HashFind(const Hash*, const char *pKey, int nKey);
7446 SQLCIPHER_PRIVATE void sqlcipher3HashClear(Hash*);
7447
7448 /*
7449 ** Macros for looping over all elements of a hash table.  The idiom is
7450 ** like this:
7451 **
7452 **   Hash h;
7453 **   HashElem *p;
7454 **   ...
7455 **   for(p=sqlcipherHashFirst(&h); p; p=sqlcipherHashNext(p)){
7456 **     SomeStructure *pData = sqlcipherHashData(p);
7457 **     // do something with pData
7458 **   }
7459 */
7460 #define sqlcipherHashFirst(H)  ((H)->first)
7461 #define sqlcipherHashNext(E)   ((E)->next)
7462 #define sqlcipherHashData(E)   ((E)->data)
7463 /* #define sqlcipherHashKey(E)    ((E)->pKey) // NOT USED */
7464 /* #define sqlcipherHashKeysize(E) ((E)->nKey)  // NOT USED */
7465
7466 /*
7467 ** Number of entries in a hash table
7468 */
7469 /* #define sqlcipherHashCount(H)  ((H)->count) // NOT USED */
7470
7471 #endif /* _SQLCIPHER_HASH_H_ */
7472
7473 /************** End of hash.h ************************************************/
7474 /************** Continuing where we left off in sqlcipherInt.h ******************/
7475 /************** Include parse.h in the middle of sqlcipherInt.h *****************/
7476 /************** Begin file parse.h *******************************************/
7477 #define TK_SEMI                            1
7478 #define TK_EXPLAIN                         2
7479 #define TK_QUERY                           3
7480 #define TK_PLAN                            4
7481 #define TK_BEGIN                           5
7482 #define TK_TRANSACTION                     6
7483 #define TK_DEFERRED                        7
7484 #define TK_IMMEDIATE                       8
7485 #define TK_EXCLUSIVE                       9
7486 #define TK_COMMIT                         10
7487 #define TK_END                            11
7488 #define TK_ROLLBACK                       12
7489 #define TK_SAVEPOINT                      13
7490 #define TK_RELEASE                        14
7491 #define TK_TO                             15
7492 #define TK_TABLE                          16
7493 #define TK_CREATE                         17
7494 #define TK_IF                             18
7495 #define TK_NOT                            19
7496 #define TK_EXISTS                         20
7497 #define TK_TEMP                           21
7498 #define TK_LP                             22
7499 #define TK_RP                             23
7500 #define TK_AS                             24
7501 #define TK_COMMA                          25
7502 #define TK_ID                             26
7503 #define TK_INDEXED                        27
7504 #define TK_ABORT                          28
7505 #define TK_ACTION                         29
7506 #define TK_AFTER                          30
7507 #define TK_ANALYZE                        31
7508 #define TK_ASC                            32
7509 #define TK_ATTACH                         33
7510 #define TK_BEFORE                         34
7511 #define TK_BY                             35
7512 #define TK_CASCADE                        36
7513 #define TK_CAST                           37
7514 #define TK_COLUMNKW                       38
7515 #define TK_CONFLICT                       39
7516 #define TK_DATABASE                       40
7517 #define TK_DESC                           41
7518 #define TK_DETACH                         42
7519 #define TK_EACH                           43
7520 #define TK_FAIL                           44
7521 #define TK_FOR                            45
7522 #define TK_IGNORE                         46
7523 #define TK_INITIALLY                      47
7524 #define TK_INSTEAD                        48
7525 #define TK_LIKE_KW                        49
7526 #define TK_MATCH                          50
7527 #define TK_NO                             51
7528 #define TK_KEY                            52
7529 #define TK_OF                             53
7530 #define TK_OFFSET                         54
7531 #define TK_PRAGMA                         55
7532 #define TK_RAISE                          56
7533 #define TK_REPLACE                        57
7534 #define TK_RESTRICT                       58
7535 #define TK_ROW                            59
7536 #define TK_TRIGGER                        60
7537 #define TK_VACUUM                         61
7538 #define TK_VIEW                           62
7539 #define TK_VIRTUAL                        63
7540 #define TK_REINDEX                        64
7541 #define TK_RENAME                         65
7542 #define TK_CTIME_KW                       66
7543 #define TK_ANY                            67
7544 #define TK_OR                             68
7545 #define TK_AND                            69
7546 #define TK_IS                             70
7547 #define TK_BETWEEN                        71
7548 #define TK_IN                             72
7549 #define TK_ISNULL                         73
7550 #define TK_NOTNULL                        74
7551 #define TK_NE                             75
7552 #define TK_EQ                             76
7553 #define TK_GT                             77
7554 #define TK_LE                             78
7555 #define TK_LT                             79
7556 #define TK_GE                             80
7557 #define TK_ESCAPE                         81
7558 #define TK_BITAND                         82
7559 #define TK_BITOR                          83
7560 #define TK_LSHIFT                         84
7561 #define TK_RSHIFT                         85
7562 #define TK_PLUS                           86
7563 #define TK_MINUS                          87
7564 #define TK_STAR                           88
7565 #define TK_SLASH                          89
7566 #define TK_REM                            90
7567 #define TK_CONCAT                         91
7568 #define TK_COLLATE                        92
7569 #define TK_BITNOT                         93
7570 #define TK_STRING                         94
7571 #define TK_JOIN_KW                        95
7572 #define TK_CONSTRAINT                     96
7573 #define TK_DEFAULT                        97
7574 #define TK_NULL                           98
7575 #define TK_PRIMARY                        99
7576 #define TK_UNIQUE                         100
7577 #define TK_CHECK                          101
7578 #define TK_REFERENCES                     102
7579 #define TK_AUTOINCR                       103
7580 #define TK_ON                             104
7581 #define TK_INSERT                         105
7582 #define TK_DELETE                         106
7583 #define TK_UPDATE                         107
7584 #define TK_SET                            108
7585 #define TK_DEFERRABLE                     109
7586 #define TK_FOREIGN                        110
7587 #define TK_DROP                           111
7588 #define TK_UNION                          112
7589 #define TK_ALL                            113
7590 #define TK_EXCEPT                         114
7591 #define TK_INTERSECT                      115
7592 #define TK_SELECT                         116
7593 #define TK_DISTINCT                       117
7594 #define TK_DOT                            118
7595 #define TK_FROM                           119
7596 #define TK_JOIN                           120
7597 #define TK_USING                          121
7598 #define TK_ORDER                          122
7599 #define TK_GROUP                          123
7600 #define TK_HAVING                         124
7601 #define TK_LIMIT                          125
7602 #define TK_WHERE                          126
7603 #define TK_INTO                           127
7604 #define TK_VALUES                         128
7605 #define TK_INTEGER                        129
7606 #define TK_FLOAT                          130
7607 #define TK_BLOB                           131
7608 #define TK_REGISTER                       132
7609 #define TK_VARIABLE                       133
7610 #define TK_CASE                           134
7611 #define TK_WHEN                           135
7612 #define TK_THEN                           136
7613 #define TK_ELSE                           137
7614 #define TK_INDEX                          138
7615 #define TK_ALTER                          139
7616 #define TK_ADD                            140
7617 #define TK_TO_TEXT                        141
7618 #define TK_TO_BLOB                        142
7619 #define TK_TO_NUMERIC                     143
7620 #define TK_TO_INT                         144
7621 #define TK_TO_REAL                        145
7622 #define TK_ISNOT                          146
7623 #define TK_END_OF_FILE                    147
7624 #define TK_ILLEGAL                        148
7625 #define TK_SPACE                          149
7626 #define TK_UNCLOSED_STRING                150
7627 #define TK_FUNCTION                       151
7628 #define TK_COLUMN                         152
7629 #define TK_AGG_FUNCTION                   153
7630 #define TK_AGG_COLUMN                     154
7631 #define TK_CONST_FUNC                     155
7632 #define TK_UMINUS                         156
7633 #define TK_UPLUS                          157
7634
7635 /************** End of parse.h ***********************************************/
7636 /************** Continuing where we left off in sqlcipherInt.h ******************/
7637 #include <stdio.h>
7638 #include <stdlib.h>
7639 #include <string.h>
7640 #include <assert.h>
7641 #include <stddef.h>
7642
7643 /*
7644 ** If compiling for a processor that lacks floating point support,
7645 ** substitute integer for floating-point
7646 */
7647 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
7648 # define double sqlcipher_int64
7649 # define float sqlcipher_int64
7650 # define LONGDOUBLE_TYPE sqlcipher_int64
7651 # ifndef SQLCIPHER_BIG_DBL
7652 #   define SQLCIPHER_BIG_DBL (((sqlcipher3_int64)1)<<50)
7653 # endif
7654 # define SQLCIPHER_OMIT_DATETIME_FUNCS 1
7655 # define SQLCIPHER_OMIT_TRACE 1
7656 # undef SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT
7657 # undef SQLCIPHER_HAVE_ISNAN
7658 #endif
7659 #ifndef SQLCIPHER_BIG_DBL
7660 # define SQLCIPHER_BIG_DBL (1e99)
7661 #endif
7662
7663 /*
7664 ** OMIT_TEMPDB is set to 1 if SQLCIPHER_OMIT_TEMPDB is defined, or 0
7665 ** afterward. Having this macro allows us to cause the C compiler 
7666 ** to omit code used by TEMP tables without messy #ifndef statements.
7667 */
7668 #ifdef SQLCIPHER_OMIT_TEMPDB
7669 #define OMIT_TEMPDB 1
7670 #else
7671 #define OMIT_TEMPDB 0
7672 #endif
7673
7674 /*
7675 ** The "file format" number is an integer that is incremented whenever
7676 ** the VDBE-level file format changes.  The following macros define the
7677 ** the default file format for new databases and the maximum file format
7678 ** that the library can read.
7679 */
7680 #define SQLCIPHER_MAX_FILE_FORMAT 4
7681 #ifndef SQLCIPHER_DEFAULT_FILE_FORMAT
7682 # define SQLCIPHER_DEFAULT_FILE_FORMAT 1
7683 #endif
7684
7685 /*
7686 ** Determine whether triggers are recursive by default.  This can be
7687 ** changed at run-time using a pragma.
7688 */
7689 #ifndef SQLCIPHER_DEFAULT_RECURSIVE_TRIGGERS
7690 # define SQLCIPHER_DEFAULT_RECURSIVE_TRIGGERS 0
7691 #endif
7692
7693 /*
7694 ** Provide a default value for SQLCIPHER_TEMP_STORE in case it is not specified
7695 ** on the command-line
7696 */
7697 #ifndef SQLCIPHER_TEMP_STORE
7698 # define SQLCIPHER_TEMP_STORE 1
7699 #endif
7700
7701 /*
7702 ** GCC does not define the offsetof() macro so we'll have to do it
7703 ** ourselves.
7704 */
7705 #ifndef offsetof
7706 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7707 #endif
7708
7709 /*
7710 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7711 ** not, there are still machines out there that use EBCDIC.)
7712 */
7713 #if 'A' == '\301'
7714 # define SQLCIPHER_EBCDIC 1
7715 #else
7716 # define SQLCIPHER_ASCII 1
7717 #endif
7718
7719 /*
7720 ** Integers of known sizes.  These typedefs might change for architectures
7721 ** where the sizes very.  Preprocessor macros are available so that the
7722 ** types can be conveniently redefined at compile-type.  Like this:
7723 **
7724 **         cc '-DUINTPTR_TYPE=long long int' ...
7725 */
7726 #ifndef UINT32_TYPE
7727 # ifdef HAVE_UINT32_T
7728 #  define UINT32_TYPE uint32_t
7729 # else
7730 #  define UINT32_TYPE unsigned int
7731 # endif
7732 #endif
7733 #ifndef UINT16_TYPE
7734 # ifdef HAVE_UINT16_T
7735 #  define UINT16_TYPE uint16_t
7736 # else
7737 #  define UINT16_TYPE unsigned short int
7738 # endif
7739 #endif
7740 #ifndef INT16_TYPE
7741 # ifdef HAVE_INT16_T
7742 #  define INT16_TYPE int16_t
7743 # else
7744 #  define INT16_TYPE short int
7745 # endif
7746 #endif
7747 #ifndef UINT8_TYPE
7748 # ifdef HAVE_UINT8_T
7749 #  define UINT8_TYPE uint8_t
7750 # else
7751 #  define UINT8_TYPE unsigned char
7752 # endif
7753 #endif
7754 #ifndef INT8_TYPE
7755 # ifdef HAVE_INT8_T
7756 #  define INT8_TYPE int8_t
7757 # else
7758 #  define INT8_TYPE signed char
7759 # endif
7760 #endif
7761 #ifndef LONGDOUBLE_TYPE
7762 # define LONGDOUBLE_TYPE long double
7763 #endif
7764 typedef sqlcipher_int64 i64;          /* 8-byte signed integer */
7765 typedef sqlcipher_uint64 u64;         /* 8-byte unsigned integer */
7766 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7767 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7768 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7769 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7770 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7771
7772 /*
7773 ** SQLCIPHER_MAX_U32 is a u64 constant that is the maximum u64 value
7774 ** that can be stored in a u32 without loss of data.  The value
7775 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7776 ** have to specify the value in the less intuitive manner shown:
7777 */
7778 #define SQLCIPHER_MAX_U32  ((((u64)1)<<32)-1)
7779
7780 /*
7781 ** The datatype used to store estimates of the number of rows in a
7782 ** table or index.  This is an unsigned integer type.  For 99.9% of
7783 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
7784 ** can be used at compile-time if desired.
7785 */
7786 #ifdef SQLCIPHER_64BIT_STATS
7787  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
7788 #else
7789  typedef u32 tRowcnt;    /* 32-bit is the default */
7790 #endif
7791
7792 /*
7793 ** Macros to determine whether the machine is big or little endian,
7794 ** evaluated at runtime.
7795 */
7796 #ifdef SQLCIPHER_AMALGAMATION
7797 SQLCIPHER_PRIVATE const int sqlcipher3one = 1;
7798 #else
7799 SQLCIPHER_PRIVATE const int sqlcipher3one;
7800 #endif
7801 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7802                              || defined(__x86_64) || defined(__x86_64__)
7803 # define SQLCIPHER_BIGENDIAN    0
7804 # define SQLCIPHER_LITTLEENDIAN 1
7805 # define SQLCIPHER_UTF16NATIVE  SQLCIPHER_UTF16LE
7806 #else
7807 # define SQLCIPHER_BIGENDIAN    (*(char *)(&sqlcipher3one)==0)
7808 # define SQLCIPHER_LITTLEENDIAN (*(char *)(&sqlcipher3one)==1)
7809 # define SQLCIPHER_UTF16NATIVE (SQLCIPHER_BIGENDIAN?SQLCIPHER_UTF16BE:SQLCIPHER_UTF16LE)
7810 #endif
7811
7812 /*
7813 ** Constants for the largest and smallest possible 64-bit signed integers.
7814 ** These macros are designed to work correctly on both 32-bit and 64-bit
7815 ** compilers.
7816 */
7817 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7818 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7819
7820 /* 
7821 ** Round up a number to the next larger multiple of 8.  This is used
7822 ** to force 8-byte alignment on 64-bit architectures.
7823 */
7824 #define ROUND8(x)     (((x)+7)&~7)
7825
7826 /*
7827 ** Round down to the nearest multiple of 8
7828 */
7829 #define ROUNDDOWN8(x) ((x)&~7)
7830
7831 /*
7832 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7833 ** macro is used only within assert() to verify that the code gets
7834 ** all alignment restrictions correct.
7835 **
7836 ** Except, if SQLCIPHER_4_BYTE_ALIGNED_MALLOC is defined, then the
7837 ** underlying malloc() implemention might return us 4-byte aligned
7838 ** pointers.  In that case, only verify 4-byte alignment.
7839 */
7840 #ifdef SQLCIPHER_4_BYTE_ALIGNED_MALLOC
7841 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7842 #else
7843 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7844 #endif
7845
7846
7847 /*
7848 ** An instance of the following structure is used to store the busy-handler
7849 ** callback for a given sqlcipher handle. 
7850 **
7851 ** The sqlcipher.busyHandler member of the sqlcipher struct contains the busy
7852 ** callback for the database handle. Each pager opened via the sqlcipher
7853 ** handle is passed a pointer to sqlcipher.busyHandler. The busy-handler
7854 ** callback is currently invoked only from within pager.c.
7855 */
7856 typedef struct BusyHandler BusyHandler;
7857 struct BusyHandler {
7858   int (*xFunc)(void *,int);  /* The busy callback */
7859   void *pArg;                /* First arg to busy callback */
7860   int nBusy;                 /* Incremented with each busy call */
7861 };
7862
7863 /*
7864 ** Name of the master database table.  The master database table
7865 ** is a special table that holds the names and attributes of all
7866 ** user tables and indices.
7867 */
7868 #define MASTER_NAME       "sqlcipher_master"
7869 #define TEMP_MASTER_NAME  "sqlcipher_temp_master"
7870
7871 /*
7872 ** The root-page of the master database table.
7873 */
7874 #define MASTER_ROOT       1
7875
7876 /*
7877 ** The name of the schema table.
7878 */
7879 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7880
7881 /*
7882 ** A convenience macro that returns the number of elements in
7883 ** an array.
7884 */
7885 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7886
7887 /*
7888 ** The following value as a destructor means to use sqlcipher3DbFree().
7889 ** This is an internal extension to SQLCIPHER_STATIC and SQLCIPHER_TRANSIENT.
7890 */
7891 #define SQLCIPHER_DYNAMIC   ((sqlcipher3_destructor_type)sqlcipher3DbFree)
7892
7893 /*
7894 ** When SQLCIPHER_OMIT_WSD is defined, it means that the target platform does
7895 ** not support Writable Static Data (WSD) such as global and static variables.
7896 ** All variables must either be on the stack or dynamically allocated from
7897 ** the heap.  When WSD is unsupported, the variable declarations scattered
7898 ** throughout the SQLite code must become constants instead.  The SQLCIPHER_WSD
7899 ** macro is used for this purpose.  And instead of referencing the variable
7900 ** directly, we use its constant as a key to lookup the run-time allocated
7901 ** buffer that holds real variable.  The constant is also the initializer
7902 ** for the run-time allocated buffer.
7903 **
7904 ** In the usual case where WSD is supported, the SQLCIPHER_WSD and GLOBAL
7905 ** macros become no-ops and have zero performance impact.
7906 */
7907 #ifdef SQLCIPHER_OMIT_WSD
7908   #define SQLCIPHER_WSD const
7909   #define GLOBAL(t,v) (*(t*)sqlcipher3_wsd_find((void*)&(v), sizeof(v)))
7910   #define sqlcipher3GlobalConfig GLOBAL(struct Sqlite3Config, sqlcipher3Config)
7911 SQLCIPHER_API   int sqlcipher3_wsd_init(int N, int J);
7912 SQLCIPHER_API   void *sqlcipher3_wsd_find(void *K, int L);
7913 #else
7914   #define SQLCIPHER_WSD 
7915   #define GLOBAL(t,v) v
7916   #define sqlcipher3GlobalConfig sqlcipher3Config
7917 #endif
7918
7919 /*
7920 ** The following macros are used to suppress compiler warnings and to
7921 ** make it clear to human readers when a function parameter is deliberately 
7922 ** left unused within the body of a function. This usually happens when
7923 ** a function is called via a function pointer. For example the 
7924 ** implementation of an SQL aggregate step callback may not use the
7925 ** parameter indicating the number of arguments passed to the aggregate,
7926 ** if it knows that this is enforced elsewhere.
7927 **
7928 ** When a function parameter is not used at all within the body of a function,
7929 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7930 ** However, these macros may also be used to suppress warnings related to
7931 ** parameters that may or may not be used depending on compilation options.
7932 ** For example those parameters only used in assert() statements. In these
7933 ** cases the parameters are named as per the usual conventions.
7934 */
7935 #define UNUSED_PARAMETER(x) (void)(x)
7936 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7937
7938 /*
7939 ** Forward references to structures
7940 */
7941 typedef struct AggInfo AggInfo;
7942 typedef struct AuthContext AuthContext;
7943 typedef struct AutoincInfo AutoincInfo;
7944 typedef struct Bitvec Bitvec;
7945 typedef struct CollSeq CollSeq;
7946 typedef struct Column Column;
7947 typedef struct Db Db;
7948 typedef struct Schema Schema;
7949 typedef struct Expr Expr;
7950 typedef struct ExprList ExprList;
7951 typedef struct ExprSpan ExprSpan;
7952 typedef struct FKey FKey;
7953 typedef struct FuncDestructor FuncDestructor;
7954 typedef struct FuncDef FuncDef;
7955 typedef struct FuncDefHash FuncDefHash;
7956 typedef struct IdList IdList;
7957 typedef struct Index Index;
7958 typedef struct IndexSample IndexSample;
7959 typedef struct KeyClass KeyClass;
7960 typedef struct KeyInfo KeyInfo;
7961 typedef struct Lookaside Lookaside;
7962 typedef struct LookasideSlot LookasideSlot;
7963 typedef struct Module Module;
7964 typedef struct NameContext NameContext;
7965 typedef struct Parse Parse;
7966 typedef struct RowSet RowSet;
7967 typedef struct Savepoint Savepoint;
7968 typedef struct Select Select;
7969 typedef struct SrcList SrcList;
7970 typedef struct StrAccum StrAccum;
7971 typedef struct Table Table;
7972 typedef struct TableLock TableLock;
7973 typedef struct Token Token;
7974 typedef struct Trigger Trigger;
7975 typedef struct TriggerPrg TriggerPrg;
7976 typedef struct TriggerStep TriggerStep;
7977 typedef struct UnpackedRecord UnpackedRecord;
7978 typedef struct VTable VTable;
7979 typedef struct VtabCtx VtabCtx;
7980 typedef struct Walker Walker;
7981 typedef struct WherePlan WherePlan;
7982 typedef struct WhereInfo WhereInfo;
7983 typedef struct WhereLevel WhereLevel;
7984
7985 /*
7986 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7987 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7988 ** pointer types (i.e. FuncDef) defined above.
7989 */
7990 /************** Include btree.h in the middle of sqlcipherInt.h *****************/
7991 /************** Begin file btree.h *******************************************/
7992 /*
7993 ** 2001 September 15
7994 **
7995 ** The author disclaims copyright to this source code.  In place of
7996 ** a legal notice, here is a blessing:
7997 **
7998 **    May you do good and not evil.
7999 **    May you find forgiveness for yourself and forgive others.
8000 **    May you share freely, never taking more than you give.
8001 **
8002 *************************************************************************
8003 ** This header file defines the interface that the sqlcipher B-Tree file
8004 ** subsystem.  See comments in the source code for a detailed description
8005 ** of what each interface routine does.
8006 */
8007 #ifndef _BTREE_H_
8008 #define _BTREE_H_
8009
8010 /* TODO: This definition is just included so other modules compile. It
8011 ** needs to be revisited.
8012 */
8013 #define SQLCIPHER_N_BTREE_META 10
8014
8015 /*
8016 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8017 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8018 */
8019 #ifndef SQLCIPHER_DEFAULT_AUTOVACUUM
8020   #define SQLCIPHER_DEFAULT_AUTOVACUUM 0
8021 #endif
8022
8023 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8024 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8025 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8026
8027 /*
8028 ** Forward declarations of structure
8029 */
8030 typedef struct Btree Btree;
8031 typedef struct BtCursor BtCursor;
8032 typedef struct BtShared BtShared;
8033
8034
8035 SQLCIPHER_PRIVATE int sqlcipher3BtreeOpen(
8036   sqlcipher3_vfs *pVfs,       /* VFS to use with this b-tree */
8037   const char *zFilename,   /* Name of database file to open */
8038   sqlcipher3 *db,             /* Associated database connection */
8039   Btree **ppBtree,         /* Return open Btree* here */
8040   int flags,               /* Flags */
8041   int vfsFlags             /* Flags passed through to VFS open */
8042 );
8043
8044 /* The flags parameter to sqlcipher3BtreeOpen can be the bitwise or of the
8045 ** following values.
8046 **
8047 ** NOTE:  These values must match the corresponding PAGER_ values in
8048 ** pager.h.
8049 */
8050 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8051 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
8052 #define BTREE_MEMORY        4  /* This is an in-memory DB */
8053 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
8054 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
8055
8056 SQLCIPHER_PRIVATE int sqlcipher3BtreeClose(Btree*);
8057 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetCacheSize(Btree*,int);
8058 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetSafetyLevel(Btree*,int,int,int);
8059 SQLCIPHER_PRIVATE int sqlcipher3BtreeSyncDisabled(Btree*);
8060 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8061 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetPageSize(Btree*);
8062 SQLCIPHER_PRIVATE int sqlcipher3BtreeMaxPageCount(Btree*,int);
8063 SQLCIPHER_PRIVATE u32 sqlcipher3BtreeLastPage(Btree*);
8064 SQLCIPHER_PRIVATE int sqlcipher3BtreeSecureDelete(Btree*,int);
8065 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetReserve(Btree*);
8066 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetAutoVacuum(Btree *, int);
8067 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetAutoVacuum(Btree *);
8068 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginTrans(Btree*,int);
8069 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8070 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseTwo(Btree*, int);
8071 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommit(Btree*);
8072 SQLCIPHER_PRIVATE int sqlcipher3BtreeRollback(Btree*);
8073 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginStmt(Btree*,int);
8074 SQLCIPHER_PRIVATE int sqlcipher3BtreeCreateTable(Btree*, int*, int flags);
8075 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInTrans(Btree*);
8076 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInReadTrans(Btree*);
8077 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInBackup(Btree*);
8078 SQLCIPHER_PRIVATE void *sqlcipher3BtreeSchema(Btree *, int, void(*)(void *));
8079 SQLCIPHER_PRIVATE int sqlcipher3BtreeSchemaLocked(Btree *pBtree);
8080 SQLCIPHER_PRIVATE int sqlcipher3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8081 SQLCIPHER_PRIVATE int sqlcipher3BtreeSavepoint(Btree *, int, int);
8082
8083 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetFilename(Btree *);
8084 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetJournalname(Btree *);
8085 SQLCIPHER_PRIVATE int sqlcipher3BtreeCopyFile(Btree *, Btree *);
8086
8087 SQLCIPHER_PRIVATE int sqlcipher3BtreeIncrVacuum(Btree *);
8088
8089 /* The flags parameter to sqlcipher3BtreeCreateTable can be the bitwise OR
8090 ** of the flags shown below.
8091 **
8092 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8093 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8094 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8095 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8096 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8097 ** indices.)
8098 */
8099 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8100 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8101
8102 SQLCIPHER_PRIVATE int sqlcipher3BtreeDropTable(Btree*, int, int*);
8103 SQLCIPHER_PRIVATE int sqlcipher3BtreeClearTable(Btree*, int, int*);
8104 SQLCIPHER_PRIVATE void sqlcipher3BtreeTripAllCursors(Btree*, int);
8105
8106 SQLCIPHER_PRIVATE void sqlcipher3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8107 SQLCIPHER_PRIVATE int sqlcipher3BtreeUpdateMeta(Btree*, int idx, u32 value);
8108
8109 /*
8110 ** The second parameter to sqlcipher3BtreeGetMeta or sqlcipher3BtreeUpdateMeta
8111 ** should be one of the following values. The integer values are assigned 
8112 ** to constants so that the offset of the corresponding field in an
8113 ** SQLite database header may be found using the following formula:
8114 **
8115 **   offset = 36 + (idx * 4)
8116 **
8117 ** For example, the free-page-count field is located at byte offset 36 of
8118 ** the database file header. The incr-vacuum-flag field is located at
8119 ** byte offset 64 (== 36+4*7).
8120 */
8121 #define BTREE_FREE_PAGE_COUNT     0
8122 #define BTREE_SCHEMA_VERSION      1
8123 #define BTREE_FILE_FORMAT         2
8124 #define BTREE_DEFAULT_CACHE_SIZE  3
8125 #define BTREE_LARGEST_ROOT_PAGE   4
8126 #define BTREE_TEXT_ENCODING       5
8127 #define BTREE_USER_VERSION        6
8128 #define BTREE_INCR_VACUUM         7
8129
8130 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursor(
8131   Btree*,                              /* BTree containing table to open */
8132   int iTable,                          /* Index of root page */
8133   int wrFlag,                          /* 1 for writing.  0 for read-only */
8134   struct KeyInfo*,                     /* First argument to compare function */
8135   BtCursor *pCursor                    /* Space to write cursor structure */
8136 );
8137 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorSize(void);
8138 SQLCIPHER_PRIVATE void sqlcipher3BtreeCursorZero(BtCursor*);
8139
8140 SQLCIPHER_PRIVATE int sqlcipher3BtreeCloseCursor(BtCursor*);
8141 SQLCIPHER_PRIVATE int sqlcipher3BtreeMovetoUnpacked(
8142   BtCursor*,
8143   UnpackedRecord *pUnKey,
8144   i64 intKey,
8145   int bias,
8146   int *pRes
8147 );
8148 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorHasMoved(BtCursor*, int*);
8149 SQLCIPHER_PRIVATE int sqlcipher3BtreeDelete(BtCursor*);
8150 SQLCIPHER_PRIVATE int sqlcipher3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8151                                   const void *pData, int nData,
8152                                   int nZero, int bias, int seekResult);
8153 SQLCIPHER_PRIVATE int sqlcipher3BtreeFirst(BtCursor*, int *pRes);
8154 SQLCIPHER_PRIVATE int sqlcipher3BtreeLast(BtCursor*, int *pRes);
8155 SQLCIPHER_PRIVATE int sqlcipher3BtreeNext(BtCursor*, int *pRes);
8156 SQLCIPHER_PRIVATE int sqlcipher3BtreeEof(BtCursor*);
8157 SQLCIPHER_PRIVATE int sqlcipher3BtreePrevious(BtCursor*, int *pRes);
8158 SQLCIPHER_PRIVATE int sqlcipher3BtreeKeySize(BtCursor*, i64 *pSize);
8159 SQLCIPHER_PRIVATE int sqlcipher3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8160 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeKeyFetch(BtCursor*, int *pAmt);
8161 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeDataFetch(BtCursor*, int *pAmt);
8162 SQLCIPHER_PRIVATE int sqlcipher3BtreeDataSize(BtCursor*, u32 *pSize);
8163 SQLCIPHER_PRIVATE int sqlcipher3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8164 SQLCIPHER_PRIVATE void sqlcipher3BtreeSetCachedRowid(BtCursor*, sqlcipher3_int64);
8165 SQLCIPHER_PRIVATE sqlcipher3_int64 sqlcipher3BtreeGetCachedRowid(BtCursor*);
8166
8167 SQLCIPHER_PRIVATE char *sqlcipher3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8168 SQLCIPHER_PRIVATE struct Pager *sqlcipher3BtreePager(Btree*);
8169
8170 SQLCIPHER_PRIVATE int sqlcipher3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8171 SQLCIPHER_PRIVATE void sqlcipher3BtreeCacheOverflow(BtCursor *);
8172 SQLCIPHER_PRIVATE void sqlcipher3BtreeClearCursor(BtCursor *);
8173
8174 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetVersion(Btree *pBt, int iVersion);
8175
8176 #ifndef NDEBUG
8177 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorIsValid(BtCursor*);
8178 #endif
8179
8180 #ifndef SQLCIPHER_OMIT_BTREECOUNT
8181 SQLCIPHER_PRIVATE int sqlcipher3BtreeCount(BtCursor *, i64 *);
8182 #endif
8183
8184 #ifdef SQLCIPHER_TEST
8185 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorInfo(BtCursor*, int*, int);
8186 SQLCIPHER_PRIVATE void sqlcipher3BtreeCursorList(Btree*);
8187 #endif
8188
8189 #ifndef SQLCIPHER_OMIT_WAL
8190 SQLCIPHER_PRIVATE   int sqlcipher3BtreeCheckpoint(Btree*, int, int *, int *);
8191 #endif
8192
8193 /*
8194 ** If we are not using shared cache, then there is no need to
8195 ** use mutexes to access the BtShared structures.  So make the
8196 ** Enter and Leave procedures no-ops.
8197 */
8198 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
8199 SQLCIPHER_PRIVATE   void sqlcipher3BtreeEnter(Btree*);
8200 SQLCIPHER_PRIVATE   void sqlcipher3BtreeEnterAll(sqlcipher3*);
8201 #else
8202 # define sqlcipher3BtreeEnter(X) 
8203 # define sqlcipher3BtreeEnterAll(X)
8204 #endif
8205
8206 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE
8207 SQLCIPHER_PRIVATE   int sqlcipher3BtreeSharable(Btree*);
8208 SQLCIPHER_PRIVATE   void sqlcipher3BtreeLeave(Btree*);
8209 SQLCIPHER_PRIVATE   void sqlcipher3BtreeEnterCursor(BtCursor*);
8210 SQLCIPHER_PRIVATE   void sqlcipher3BtreeLeaveCursor(BtCursor*);
8211 SQLCIPHER_PRIVATE   void sqlcipher3BtreeLeaveAll(sqlcipher3*);
8212 #ifndef NDEBUG
8213   /* These routines are used inside assert() statements only. */
8214 SQLCIPHER_PRIVATE   int sqlcipher3BtreeHoldsMutex(Btree*);
8215 SQLCIPHER_PRIVATE   int sqlcipher3BtreeHoldsAllMutexes(sqlcipher3*);
8216 SQLCIPHER_PRIVATE   int sqlcipher3SchemaMutexHeld(sqlcipher3*,int,Schema*);
8217 #endif
8218 #else
8219
8220 # define sqlcipher3BtreeSharable(X) 0
8221 # define sqlcipher3BtreeLeave(X)
8222 # define sqlcipher3BtreeEnterCursor(X)
8223 # define sqlcipher3BtreeLeaveCursor(X)
8224 # define sqlcipher3BtreeLeaveAll(X)
8225
8226 # define sqlcipher3BtreeHoldsMutex(X) 1
8227 # define sqlcipher3BtreeHoldsAllMutexes(X) 1
8228 # define sqlcipher3SchemaMutexHeld(X,Y,Z) 1
8229 #endif
8230
8231
8232 #endif /* _BTREE_H_ */
8233
8234 /************** End of btree.h ***********************************************/
8235 /************** Continuing where we left off in sqlcipherInt.h ******************/
8236 /************** Include vdbe.h in the middle of sqlcipherInt.h ******************/
8237 /************** Begin file vdbe.h ********************************************/
8238 /*
8239 ** 2001 September 15
8240 **
8241 ** The author disclaims copyright to this source code.  In place of
8242 ** a legal notice, here is a blessing:
8243 **
8244 **    May you do good and not evil.
8245 **    May you find forgiveness for yourself and forgive others.
8246 **    May you share freely, never taking more than you give.
8247 **
8248 *************************************************************************
8249 ** Header file for the Virtual DataBase Engine (VDBE)
8250 **
8251 ** This header defines the interface to the virtual database engine
8252 ** or VDBE.  The VDBE implements an abstract machine that runs a
8253 ** simple program to access and modify the underlying database.
8254 */
8255 #ifndef _SQLCIPHER_VDBE_H_
8256 #define _SQLCIPHER_VDBE_H_
8257 /* #include <stdio.h> */
8258
8259 /*
8260 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8261 ** in the source file sqlcipherVdbe.c are allowed to see the insides
8262 ** of this structure.
8263 */
8264 typedef struct Vdbe Vdbe;
8265
8266 /*
8267 ** The names of the following types declared in vdbeInt.h are required
8268 ** for the VdbeOp definition.
8269 */
8270 typedef struct VdbeFunc VdbeFunc;
8271 typedef struct Mem Mem;
8272 typedef struct SubProgram SubProgram;
8273
8274 /*
8275 ** A single instruction of the virtual machine has an opcode
8276 ** and as many as three operands.  The instruction is recorded
8277 ** as an instance of the following structure:
8278 */
8279 struct VdbeOp {
8280   u8 opcode;          /* What operation to perform */
8281   signed char p4type; /* One of the P4_xxx constants for p4 */
8282   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8283   u8 p5;              /* Fifth parameter is an unsigned character */
8284   int p1;             /* First operand */
8285   int p2;             /* Second parameter (often the jump destination) */
8286   int p3;             /* The third parameter */
8287   union {             /* fourth parameter */
8288     int i;                 /* Integer value if p4type==P4_INT32 */
8289     void *p;               /* Generic pointer */
8290     char *z;               /* Pointer to data for string (char array) types */
8291     i64 *pI64;             /* Used when p4type is P4_INT64 */
8292     double *pReal;         /* Used when p4type is P4_REAL */
8293     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8294     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8295     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8296     Mem *pMem;             /* Used when p4type is P4_MEM */
8297     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8298     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8299     int *ai;               /* Used when p4type is P4_INTARRAY */
8300     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8301     int (*xAdvance)(BtCursor *, int *);
8302   } p4;
8303 #ifdef SQLCIPHER_DEBUG
8304   char *zComment;          /* Comment to improve readability */
8305 #endif
8306 #ifdef VDBE_PROFILE
8307   int cnt;                 /* Number of times this instruction was executed */
8308   u64 cycles;              /* Total time spent executing this instruction */
8309 #endif
8310 };
8311 typedef struct VdbeOp VdbeOp;
8312
8313
8314 /*
8315 ** A sub-routine used to implement a trigger program.
8316 */
8317 struct SubProgram {
8318   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8319   int nOp;                      /* Elements in aOp[] */
8320   int nMem;                     /* Number of memory cells required */
8321   int nCsr;                     /* Number of cursors required */
8322   void *token;                  /* id that may be used to recursive triggers */
8323   SubProgram *pNext;            /* Next sub-program already visited */
8324 };
8325
8326 /*
8327 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8328 ** it takes up less space.
8329 */
8330 struct VdbeOpList {
8331   u8 opcode;          /* What operation to perform */
8332   signed char p1;     /* First operand */
8333   signed char p2;     /* Second parameter (often the jump destination) */
8334   signed char p3;     /* Third parameter */
8335 };
8336 typedef struct VdbeOpList VdbeOpList;
8337
8338 /*
8339 ** Allowed values of VdbeOp.p4type
8340 */
8341 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8342 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqlcipherMalloc() */
8343 #define P4_STATIC   (-2)  /* Pointer to a static string */
8344 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8345 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8346 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8347 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8348 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8349 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8350 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlcipher3_vtab structure */
8351 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlcipher3_mprintf() */
8352 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8353 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8354 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8355 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8356 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8357 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8358
8359 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8360 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8361 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8362 ** gets freed when the Vdbe is finalized so it still should be obtained
8363 ** from a single sqlcipherMalloc().  But no copy is made and the calling
8364 ** function should *not* try to free the KeyInfo.
8365 */
8366 #define P4_KEYINFO_HANDOFF (-16)
8367 #define P4_KEYINFO_STATIC  (-17)
8368
8369 /*
8370 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8371 ** number of columns of data returned by the statement.
8372 */
8373 #define COLNAME_NAME     0
8374 #define COLNAME_DECLTYPE 1
8375 #define COLNAME_DATABASE 2
8376 #define COLNAME_TABLE    3
8377 #define COLNAME_COLUMN   4
8378 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
8379 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8380 #else
8381 # ifdef SQLCIPHER_OMIT_DECLTYPE
8382 #   define COLNAME_N      1      /* Store only the name */
8383 # else
8384 #   define COLNAME_N      2      /* Store the name and decltype */
8385 # endif
8386 #endif
8387
8388 /*
8389 ** The following macro converts a relative address in the p2 field
8390 ** of a VdbeOp structure into a negative number so that 
8391 ** sqlcipher3VdbeAddOpList() knows that the address is relative.  Calling
8392 ** the macro again restores the address.
8393 */
8394 #define ADDR(X)  (-1-(X))
8395
8396 /*
8397 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8398 ** header file that defines a number for each opcode used by the VDBE.
8399 */
8400 /************** Include opcodes.h in the middle of vdbe.h ********************/
8401 /************** Begin file opcodes.h *****************************************/
8402 /* Automatically generated.  Do not edit */
8403 /* See the mkopcodeh.awk script for details */
8404 #define OP_Goto                                 1
8405 #define OP_Gosub                                2
8406 #define OP_Return                               3
8407 #define OP_Yield                                4
8408 #define OP_HaltIfNull                           5
8409 #define OP_Halt                                 6
8410 #define OP_Integer                              7
8411 #define OP_Int64                                8
8412 #define OP_Real                               130   /* same as TK_FLOAT    */
8413 #define OP_String8                             94   /* same as TK_STRING   */
8414 #define OP_String                               9
8415 #define OP_Null                                10
8416 #define OP_Blob                                11
8417 #define OP_Variable                            12
8418 #define OP_Move                                13
8419 #define OP_Copy                                14
8420 #define OP_SCopy                               15
8421 #define OP_ResultRow                           16
8422 #define OP_Concat                              91   /* same as TK_CONCAT   */
8423 #define OP_Add                                 86   /* same as TK_PLUS     */
8424 #define OP_Subtract                            87   /* same as TK_MINUS    */
8425 #define OP_Multiply                            88   /* same as TK_STAR     */
8426 #define OP_Divide                              89   /* same as TK_SLASH    */
8427 #define OP_Remainder                           90   /* same as TK_REM      */
8428 #define OP_CollSeq                             17
8429 #define OP_Function                            18
8430 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8431 #define OP_BitOr                               83   /* same as TK_BITOR    */
8432 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8433 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8434 #define OP_AddImm                              20
8435 #define OP_MustBeInt                           21
8436 #define OP_RealAffinity                        22
8437 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8438 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8439 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8440 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8441 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8442 #define OP_Eq                                  76   /* same as TK_EQ       */
8443 #define OP_Ne                                  75   /* same as TK_NE       */
8444 #define OP_Lt                                  79   /* same as TK_LT       */
8445 #define OP_Le                                  78   /* same as TK_LE       */
8446 #define OP_Gt                                  77   /* same as TK_GT       */
8447 #define OP_Ge                                  80   /* same as TK_GE       */
8448 #define OP_Permutation                         23
8449 #define OP_Compare                             24
8450 #define OP_Jump                                25
8451 #define OP_And                                 69   /* same as TK_AND      */
8452 #define OP_Or                                  68   /* same as TK_OR       */
8453 #define OP_Not                                 19   /* same as TK_NOT      */
8454 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8455 #define OP_Once                                26
8456 #define OP_If                                  27
8457 #define OP_IfNot                               28
8458 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8459 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8460 #define OP_Column                              29
8461 #define OP_Affinity                            30
8462 #define OP_MakeRecord                          31
8463 #define OP_Count                               32
8464 #define OP_Savepoint                           33
8465 #define OP_AutoCommit                          34
8466 #define OP_Transaction                         35
8467 #define OP_ReadCookie                          36
8468 #define OP_SetCookie                           37
8469 #define OP_VerifyCookie                        38
8470 #define OP_OpenRead                            39
8471 #define OP_OpenWrite                           40
8472 #define OP_OpenAutoindex                       41
8473 #define OP_OpenEphemeral                       42
8474 #define OP_SorterOpen                          43
8475 #define OP_OpenPseudo                          44
8476 #define OP_Close                               45
8477 #define OP_SeekLt                              46
8478 #define OP_SeekLe                              47
8479 #define OP_SeekGe                              48
8480 #define OP_SeekGt                              49
8481 #define OP_Seek                                50
8482 #define OP_NotFound                            51
8483 #define OP_Found                               52
8484 #define OP_IsUnique                            53
8485 #define OP_NotExists                           54
8486 #define OP_Sequence                            55
8487 #define OP_NewRowid                            56
8488 #define OP_Insert                              57
8489 #define OP_InsertInt                           58
8490 #define OP_Delete                              59
8491 #define OP_ResetCount                          60
8492 #define OP_SorterCompare                       61
8493 #define OP_SorterData                          62
8494 #define OP_RowKey                              63
8495 #define OP_RowData                             64
8496 #define OP_Rowid                               65
8497 #define OP_NullRow                             66
8498 #define OP_Last                                67
8499 #define OP_SorterSort                          70
8500 #define OP_Sort                                71
8501 #define OP_Rewind                              72
8502 #define OP_SorterNext                          81
8503 #define OP_Prev                                92
8504 #define OP_Next                                95
8505 #define OP_SorterInsert                        96
8506 #define OP_IdxInsert                           97
8507 #define OP_IdxDelete                           98
8508 #define OP_IdxRowid                            99
8509 #define OP_IdxLT                              100
8510 #define OP_IdxGE                              101
8511 #define OP_Destroy                            102
8512 #define OP_Clear                              103
8513 #define OP_CreateIndex                        104
8514 #define OP_CreateTable                        105
8515 #define OP_ParseSchema                        106
8516 #define OP_LoadAnalysis                       107
8517 #define OP_DropTable                          108
8518 #define OP_DropIndex                          109
8519 #define OP_DropTrigger                        110
8520 #define OP_IntegrityCk                        111
8521 #define OP_RowSetAdd                          112
8522 #define OP_RowSetRead                         113
8523 #define OP_RowSetTest                         114
8524 #define OP_Program                            115
8525 #define OP_Param                              116
8526 #define OP_FkCounter                          117
8527 #define OP_FkIfZero                           118
8528 #define OP_MemMax                             119
8529 #define OP_IfPos                              120
8530 #define OP_IfNeg                              121
8531 #define OP_IfZero                             122
8532 #define OP_AggStep                            123
8533 #define OP_AggFinal                           124
8534 #define OP_Checkpoint                         125
8535 #define OP_JournalMode                        126
8536 #define OP_Vacuum                             127
8537 #define OP_IncrVacuum                         128
8538 #define OP_Expire                             129
8539 #define OP_TableLock                          131
8540 #define OP_VBegin                             132
8541 #define OP_VCreate                            133
8542 #define OP_VDestroy                           134
8543 #define OP_VOpen                              135
8544 #define OP_VFilter                            136
8545 #define OP_VColumn                            137
8546 #define OP_VNext                              138
8547 #define OP_VRename                            139
8548 #define OP_VUpdate                            140
8549 #define OP_Pagecount                          146
8550 #define OP_MaxPgcnt                           147
8551 #define OP_Trace                              148
8552 #define OP_Noop                               149
8553 #define OP_Explain                            150
8554
8555
8556 /* Properties such as "out2" or "jump" that are specified in
8557 ** comments following the "case" for each opcode in the vdbe.c
8558 ** are encoded into bitvectors as follows:
8559 */
8560 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8561 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8562 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8563 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8564 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8565 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8566 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8567 #define OPFLG_INITIALIZER {\
8568 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8569 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8570 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8571 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00,\
8572 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8573 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8574 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8575 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8576 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8577 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8578 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8579 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8580 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8581 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8582 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8583 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8584 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8585 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8586 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8587
8588 /************** End of opcodes.h *********************************************/
8589 /************** Continuing where we left off in vdbe.h ***********************/
8590
8591 /*
8592 ** Prototypes for the VDBE interface.  See comments on the implementation
8593 ** for a description of what each of these routines does.
8594 */
8595 SQLCIPHER_PRIVATE Vdbe *sqlcipher3VdbeCreate(sqlcipher3*);
8596 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp0(Vdbe*,int);
8597 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp1(Vdbe*,int,int);
8598 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp2(Vdbe*,int,int,int);
8599 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp3(Vdbe*,int,int,int,int);
8600 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8601 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8602 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8603 SQLCIPHER_PRIVATE void sqlcipher3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8604 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8605 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8606 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8607 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP5(Vdbe*, u8 P5);
8608 SQLCIPHER_PRIVATE void sqlcipher3VdbeJumpHere(Vdbe*, int addr);
8609 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeToNoop(Vdbe*, int addr);
8610 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8611 SQLCIPHER_PRIVATE void sqlcipher3VdbeUsesBtree(Vdbe*, int);
8612 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeGetOp(Vdbe*, int);
8613 SQLCIPHER_PRIVATE int sqlcipher3VdbeMakeLabel(Vdbe*);
8614 SQLCIPHER_PRIVATE void sqlcipher3VdbeRunOnlyOnce(Vdbe*);
8615 SQLCIPHER_PRIVATE void sqlcipher3VdbeDelete(Vdbe*);
8616 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteObject(sqlcipher3*,Vdbe*);
8617 SQLCIPHER_PRIVATE void sqlcipher3VdbeMakeReady(Vdbe*,Parse*);
8618 SQLCIPHER_PRIVATE int sqlcipher3VdbeFinalize(Vdbe*);
8619 SQLCIPHER_PRIVATE void sqlcipher3VdbeResolveLabel(Vdbe*, int);
8620 SQLCIPHER_PRIVATE int sqlcipher3VdbeCurrentAddr(Vdbe*);
8621 #ifdef SQLCIPHER_DEBUG
8622 SQLCIPHER_PRIVATE   int sqlcipher3VdbeAssertMayAbort(Vdbe *, int);
8623 SQLCIPHER_PRIVATE   void sqlcipher3VdbeTrace(Vdbe*,FILE*);
8624 #endif
8625 SQLCIPHER_PRIVATE void sqlcipher3VdbeResetStepResult(Vdbe*);
8626 SQLCIPHER_PRIVATE void sqlcipher3VdbeRewind(Vdbe*);
8627 SQLCIPHER_PRIVATE int sqlcipher3VdbeReset(Vdbe*);
8628 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetNumCols(Vdbe*,int);
8629 SQLCIPHER_PRIVATE int sqlcipher3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8630 SQLCIPHER_PRIVATE void sqlcipher3VdbeCountChanges(Vdbe*);
8631 SQLCIPHER_PRIVATE sqlcipher3 *sqlcipher3VdbeDb(Vdbe*);
8632 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetSql(Vdbe*, const char *z, int n, int);
8633 SQLCIPHER_PRIVATE void sqlcipher3VdbeSwap(Vdbe*,Vdbe*);
8634 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeTakeOpArray(Vdbe*, int*, int*);
8635 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3VdbeGetValue(Vdbe*, int, u8);
8636 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetVarmask(Vdbe*, int);
8637 #ifndef SQLCIPHER_OMIT_TRACE
8638 SQLCIPHER_PRIVATE   char *sqlcipher3VdbeExpandSql(Vdbe*, const char*);
8639 #endif
8640
8641 SQLCIPHER_PRIVATE void sqlcipher3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8642 SQLCIPHER_PRIVATE int sqlcipher3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8643 SQLCIPHER_PRIVATE UnpackedRecord *sqlcipher3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8644
8645 #ifndef SQLCIPHER_OMIT_TRIGGER
8646 SQLCIPHER_PRIVATE void sqlcipher3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8647 #endif
8648
8649
8650 #ifndef NDEBUG
8651 SQLCIPHER_PRIVATE   void sqlcipher3VdbeComment(Vdbe*, const char*, ...);
8652 # define VdbeComment(X)  sqlcipher3VdbeComment X
8653 SQLCIPHER_PRIVATE   void sqlcipher3VdbeNoopComment(Vdbe*, const char*, ...);
8654 # define VdbeNoopComment(X)  sqlcipher3VdbeNoopComment X
8655 #else
8656 # define VdbeComment(X)
8657 # define VdbeNoopComment(X)
8658 #endif
8659
8660 #endif
8661
8662 /************** End of vdbe.h ************************************************/
8663 /************** Continuing where we left off in sqlcipherInt.h ******************/
8664 /************** Include pager.h in the middle of sqlcipherInt.h *****************/
8665 /************** Begin file pager.h *******************************************/
8666 /*
8667 ** 2001 September 15
8668 **
8669 ** The author disclaims copyright to this source code.  In place of
8670 ** a legal notice, here is a blessing:
8671 **
8672 **    May you do good and not evil.
8673 **    May you find forgiveness for yourself and forgive others.
8674 **    May you share freely, never taking more than you give.
8675 **
8676 *************************************************************************
8677 ** This header file defines the interface that the sqlcipher page cache
8678 ** subsystem.  The page cache subsystem reads and writes a file a page
8679 ** at a time and provides a journal for rollback.
8680 */
8681
8682 #ifndef _PAGER_H_
8683 #define _PAGER_H_
8684
8685 /*
8686 ** Default maximum size for persistent journal files. A negative 
8687 ** value means no limit. This value may be overridden using the 
8688 ** sqlcipher3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8689 */
8690 #ifndef SQLCIPHER_DEFAULT_JOURNAL_SIZE_LIMIT
8691   #define SQLCIPHER_DEFAULT_JOURNAL_SIZE_LIMIT -1
8692 #endif
8693
8694 /*
8695 ** The type used to represent a page number.  The first page in a file
8696 ** is called page 1.  0 is used to represent "not a page".
8697 */
8698 typedef u32 Pgno;
8699
8700 /*
8701 ** Each open file is managed by a separate instance of the "Pager" structure.
8702 */
8703 typedef struct Pager Pager;
8704
8705 /*
8706 ** Handle type for pages.
8707 */
8708 typedef struct PgHdr DbPage;
8709
8710 /*
8711 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8712 ** reserved for working around a windows/posix incompatibility). It is
8713 ** used in the journal to signify that the remainder of the journal file 
8714 ** is devoted to storing a master journal name - there are no more pages to
8715 ** roll back. See comments for function writeMasterJournal() in pager.c 
8716 ** for details.
8717 */
8718 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8719
8720 /*
8721 ** Allowed values for the flags parameter to sqlcipher3PagerOpen().
8722 **
8723 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8724 */
8725 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8726 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8727 #define PAGER_MEMORY        0x0004    /* In-memory database */
8728
8729 /*
8730 ** Valid values for the second argument to sqlcipher3PagerLockingMode().
8731 */
8732 #define PAGER_LOCKINGMODE_QUERY      -1
8733 #define PAGER_LOCKINGMODE_NORMAL      0
8734 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8735
8736 /*
8737 ** Numeric constants that encode the journalmode.  
8738 */
8739 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8740 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8741 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8742 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8743 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8744 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8745 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8746
8747 /*
8748 ** The remainder of this file contains the declarations of the functions
8749 ** that make up the Pager sub-system API. See source code comments for 
8750 ** a detailed description of each routine.
8751 */
8752
8753 /* Open and close a Pager connection. */ 
8754 SQLCIPHER_PRIVATE int sqlcipher3PagerOpen(
8755   sqlcipher3_vfs*,
8756   Pager **ppPager,
8757   const char*,
8758   int,
8759   int,
8760   int,
8761   void(*)(DbPage*)
8762 );
8763 SQLCIPHER_PRIVATE int sqlcipher3PagerClose(Pager *pPager);
8764 SQLCIPHER_PRIVATE int sqlcipher3PagerReadFileheader(Pager*, int, unsigned char*);
8765
8766 /* Functions used to configure a Pager object. */
8767 SQLCIPHER_PRIVATE void sqlcipher3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8768 SQLCIPHER_PRIVATE int sqlcipher3PagerSetPagesize(Pager*, u32*, int);
8769 SQLCIPHER_PRIVATE int sqlcipher3PagerMaxPageCount(Pager*, int);
8770 SQLCIPHER_PRIVATE void sqlcipher3PagerSetCachesize(Pager*, int);
8771 SQLCIPHER_PRIVATE void sqlcipher3PagerSetSafetyLevel(Pager*,int,int,int);
8772 SQLCIPHER_PRIVATE int sqlcipher3PagerLockingMode(Pager *, int);
8773 SQLCIPHER_PRIVATE int sqlcipher3PagerSetJournalMode(Pager *, int);
8774 SQLCIPHER_PRIVATE int sqlcipher3PagerGetJournalMode(Pager*);
8775 SQLCIPHER_PRIVATE int sqlcipher3PagerOkToChangeJournalMode(Pager*);
8776 SQLCIPHER_PRIVATE i64 sqlcipher3PagerJournalSizeLimit(Pager *, i64);
8777 SQLCIPHER_PRIVATE sqlcipher3_backup **sqlcipher3PagerBackupPtr(Pager*);
8778
8779 /* Functions used to obtain and release page references. */ 
8780 SQLCIPHER_PRIVATE int sqlcipher3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8781 #define sqlcipher3PagerGet(A,B,C) sqlcipher3PagerAcquire(A,B,C,0)
8782 SQLCIPHER_PRIVATE DbPage *sqlcipher3PagerLookup(Pager *pPager, Pgno pgno);
8783 SQLCIPHER_PRIVATE void sqlcipher3PagerRef(DbPage*);
8784 SQLCIPHER_PRIVATE void sqlcipher3PagerUnref(DbPage*);
8785
8786 /* Operations on page references. */
8787 SQLCIPHER_PRIVATE int sqlcipher3PagerWrite(DbPage*);
8788 SQLCIPHER_PRIVATE void sqlcipher3PagerDontWrite(DbPage*);
8789 SQLCIPHER_PRIVATE int sqlcipher3PagerMovepage(Pager*,DbPage*,Pgno,int);
8790 SQLCIPHER_PRIVATE int sqlcipher3PagerPageRefcount(DbPage*);
8791 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetData(DbPage *); 
8792 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetExtra(DbPage *); 
8793
8794 /* Functions used to manage pager transactions and savepoints. */
8795 SQLCIPHER_PRIVATE void sqlcipher3PagerPagecount(Pager*, int*);
8796 SQLCIPHER_PRIVATE int sqlcipher3PagerBegin(Pager*, int exFlag, int);
8797 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8798 SQLCIPHER_PRIVATE int sqlcipher3PagerExclusiveLock(Pager*);
8799 SQLCIPHER_PRIVATE int sqlcipher3PagerSync(Pager *pPager);
8800 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseTwo(Pager*);
8801 SQLCIPHER_PRIVATE int sqlcipher3PagerRollback(Pager*);
8802 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenSavepoint(Pager *pPager, int n);
8803 SQLCIPHER_PRIVATE int sqlcipher3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8804 SQLCIPHER_PRIVATE int sqlcipher3PagerSharedLock(Pager *pPager);
8805
8806 SQLCIPHER_PRIVATE int sqlcipher3PagerCheckpoint(Pager *pPager, int, int*, int*);
8807 SQLCIPHER_PRIVATE int sqlcipher3PagerWalSupported(Pager *pPager);
8808 SQLCIPHER_PRIVATE int sqlcipher3PagerWalCallback(Pager *pPager);
8809 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenWal(Pager *pPager, int *pisOpen);
8810 SQLCIPHER_PRIVATE int sqlcipher3PagerCloseWal(Pager *pPager);
8811
8812 /* Functions used to query pager state and configuration. */
8813 SQLCIPHER_PRIVATE u8 sqlcipher3PagerIsreadonly(Pager*);
8814 SQLCIPHER_PRIVATE int sqlcipher3PagerRefcount(Pager*);
8815 SQLCIPHER_PRIVATE int sqlcipher3PagerMemUsed(Pager*);
8816 SQLCIPHER_PRIVATE const char *sqlcipher3PagerFilename(Pager*);
8817 SQLCIPHER_PRIVATE const sqlcipher3_vfs *sqlcipher3PagerVfs(Pager*);
8818 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3PagerFile(Pager*);
8819 SQLCIPHER_PRIVATE const char *sqlcipher3PagerJournalname(Pager*);
8820 SQLCIPHER_PRIVATE int sqlcipher3PagerNosync(Pager*);
8821 SQLCIPHER_PRIVATE void *sqlcipher3PagerTempSpace(Pager*);
8822 SQLCIPHER_PRIVATE int sqlcipher3PagerIsMemdb(Pager*);
8823 SQLCIPHER_PRIVATE void sqlcipher3PagerCacheStat(Pager *, int, int, int *);
8824 SQLCIPHER_PRIVATE void sqlcipher3PagerClearCache(Pager *);
8825
8826 /* Functions used to truncate the database file. */
8827 SQLCIPHER_PRIVATE void sqlcipher3PagerTruncateImage(Pager*,Pgno);
8828
8829 #if defined(SQLCIPHER_HAS_CODEC) && !defined(SQLCIPHER_OMIT_WAL)
8830 SQLCIPHER_PRIVATE void *sqlcipher3PagerCodec(DbPage *);
8831 #endif
8832
8833 /* Functions to support testing and debugging. */
8834 #if !defined(NDEBUG) || defined(SQLCIPHER_TEST)
8835 SQLCIPHER_PRIVATE   Pgno sqlcipher3PagerPagenumber(DbPage*);
8836 SQLCIPHER_PRIVATE   int sqlcipher3PagerIswriteable(DbPage*);
8837 #endif
8838 #ifdef SQLCIPHER_TEST
8839 SQLCIPHER_PRIVATE   int *sqlcipher3PagerStats(Pager*);
8840 SQLCIPHER_PRIVATE   void sqlcipher3PagerRefdump(Pager*);
8841   void disable_simulated_io_errors(void);
8842   void enable_simulated_io_errors(void);
8843 #else
8844 # define disable_simulated_io_errors()
8845 # define enable_simulated_io_errors()
8846 #endif
8847
8848 #endif /* _PAGER_H_ */
8849
8850 /************** End of pager.h ***********************************************/
8851 /************** Continuing where we left off in sqlcipherInt.h ******************/
8852 /************** Include pcache.h in the middle of sqlcipherInt.h ****************/
8853 /************** Begin file pcache.h ******************************************/
8854 /*
8855 ** 2008 August 05
8856 **
8857 ** The author disclaims copyright to this source code.  In place of
8858 ** a legal notice, here is a blessing:
8859 **
8860 **    May you do good and not evil.
8861 **    May you find forgiveness for yourself and forgive others.
8862 **    May you share freely, never taking more than you give.
8863 **
8864 *************************************************************************
8865 ** This header file defines the interface that the sqlcipher page cache
8866 ** subsystem. 
8867 */
8868
8869 #ifndef _PCACHE_H_
8870
8871 typedef struct PgHdr PgHdr;
8872 typedef struct PCache PCache;
8873
8874 /*
8875 ** Every page in the cache is controlled by an instance of the following
8876 ** structure.
8877 */
8878 struct PgHdr {
8879   void *pData;                   /* Content of this page */
8880   void *pExtra;                  /* Extra content */
8881   PgHdr *pDirty;                 /* Transient list of dirty pages */
8882   Pgno pgno;                     /* Page number for this page */
8883   Pager *pPager;                 /* The pager this page is part of */
8884 #ifdef SQLCIPHER_CHECK_PAGES
8885   u32 pageHash;                  /* Hash of page content */
8886 #endif
8887   u16 flags;                     /* PGHDR flags defined below */
8888
8889   /**********************************************************************
8890   ** Elements above are public.  All that follows is private to pcache.c
8891   ** and should not be accessed by other modules.
8892   */
8893   i16 nRef;                      /* Number of users of this page */
8894   PCache *pCache;                /* Cache that owns this page */
8895
8896   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8897   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8898 };
8899
8900 /* Bit values for PgHdr.flags */
8901 #define PGHDR_DIRTY             0x002  /* Page has changed */
8902 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8903                                        ** writing this page to the database */
8904 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8905 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8906 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8907
8908 /* Initialize and shutdown the page cache subsystem */
8909 SQLCIPHER_PRIVATE int sqlcipher3PcacheInitialize(void);
8910 SQLCIPHER_PRIVATE void sqlcipher3PcacheShutdown(void);
8911
8912 /* Page cache buffer management:
8913 ** These routines implement SQLCIPHER_CONFIG_PAGECACHE.
8914 */
8915 SQLCIPHER_PRIVATE void sqlcipher3PCacheBufferSetup(void *, int sz, int n);
8916
8917 /* Create a new pager cache.
8918 ** Under memory stress, invoke xStress to try to make pages clean.
8919 ** Only clean and unpinned pages can be reclaimed.
8920 */
8921 SQLCIPHER_PRIVATE void sqlcipher3PcacheOpen(
8922   int szPage,                    /* Size of every page */
8923   int szExtra,                   /* Extra space associated with each page */
8924   int bPurgeable,                /* True if pages are on backing store */
8925   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8926   void *pStress,                 /* Argument to xStress */
8927   PCache *pToInit                /* Preallocated space for the PCache */
8928 );
8929
8930 /* Modify the page-size after the cache has been created. */
8931 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetPageSize(PCache *, int);
8932
8933 /* Return the size in bytes of a PCache object.  Used to preallocate
8934 ** storage space.
8935 */
8936 SQLCIPHER_PRIVATE int sqlcipher3PcacheSize(void);
8937
8938 /* One release per successful fetch.  Page is pinned until released.
8939 ** Reference counted. 
8940 */
8941 SQLCIPHER_PRIVATE int sqlcipher3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8942 SQLCIPHER_PRIVATE void sqlcipher3PcacheRelease(PgHdr*);
8943
8944 SQLCIPHER_PRIVATE void sqlcipher3PcacheDrop(PgHdr*);         /* Remove page from cache */
8945 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8946 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8947 SQLCIPHER_PRIVATE void sqlcipher3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8948
8949 /* Change a page number.  Used by incr-vacuum. */
8950 SQLCIPHER_PRIVATE void sqlcipher3PcacheMove(PgHdr*, Pgno);
8951
8952 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8953 SQLCIPHER_PRIVATE void sqlcipher3PcacheTruncate(PCache*, Pgno x);
8954
8955 /* Get a list of all dirty pages in the cache, sorted by page number */
8956 SQLCIPHER_PRIVATE PgHdr *sqlcipher3PcacheDirtyList(PCache*);
8957
8958 /* Reset and close the cache object */
8959 SQLCIPHER_PRIVATE void sqlcipher3PcacheClose(PCache*);
8960
8961 /* Clear flags from pages of the page cache */
8962 SQLCIPHER_PRIVATE void sqlcipher3PcacheClearSyncFlags(PCache *);
8963
8964 /* Discard the contents of the cache */
8965 SQLCIPHER_PRIVATE void sqlcipher3PcacheClear(PCache*);
8966
8967 /* Return the total number of outstanding page references */
8968 SQLCIPHER_PRIVATE int sqlcipher3PcacheRefCount(PCache*);
8969
8970 /* Increment the reference count of an existing page */
8971 SQLCIPHER_PRIVATE void sqlcipher3PcacheRef(PgHdr*);
8972
8973 SQLCIPHER_PRIVATE int sqlcipher3PcachePageRefcount(PgHdr*);
8974
8975 /* Return the total number of pages stored in the cache */
8976 SQLCIPHER_PRIVATE int sqlcipher3PcachePagecount(PCache*);
8977
8978 #if defined(SQLCIPHER_CHECK_PAGES) || defined(SQLCIPHER_DEBUG)
8979 /* Iterate through all dirty pages currently stored in the cache. This
8980 ** interface is only available if SQLCIPHER_CHECK_PAGES is defined when the 
8981 ** library is built.
8982 */
8983 SQLCIPHER_PRIVATE void sqlcipher3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8984 #endif
8985
8986 /* Set and get the suggested cache-size for the specified pager-cache.
8987 **
8988 ** If no global maximum is configured, then the system attempts to limit
8989 ** the total number of pages cached by purgeable pager-caches to the sum
8990 ** of the suggested cache-sizes.
8991 */
8992 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetCachesize(PCache *, int);
8993 #ifdef SQLCIPHER_TEST
8994 SQLCIPHER_PRIVATE int sqlcipher3PcacheGetCachesize(PCache *);
8995 #endif
8996
8997 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
8998 /* Try to return memory used by the pcache module to the main memory heap */
8999 SQLCIPHER_PRIVATE int sqlcipher3PcacheReleaseMemory(int);
9000 #endif
9001
9002 #ifdef SQLCIPHER_TEST
9003 SQLCIPHER_PRIVATE void sqlcipher3PcacheStats(int*,int*,int*,int*);
9004 #endif
9005
9006 SQLCIPHER_PRIVATE void sqlcipher3PCacheSetDefault(void);
9007
9008 #endif /* _PCACHE_H_ */
9009
9010 /************** End of pcache.h **********************************************/
9011 /************** Continuing where we left off in sqlcipherInt.h ******************/
9012
9013 /************** Include os.h in the middle of sqlcipherInt.h ********************/
9014 /************** Begin file os.h **********************************************/
9015 /*
9016 ** 2001 September 16
9017 **
9018 ** The author disclaims copyright to this source code.  In place of
9019 ** a legal notice, here is a blessing:
9020 **
9021 **    May you do good and not evil.
9022 **    May you find forgiveness for yourself and forgive others.
9023 **    May you share freely, never taking more than you give.
9024 **
9025 ******************************************************************************
9026 **
9027 ** This header file (together with is companion C source-code file
9028 ** "os.c") attempt to abstract the underlying operating system so that
9029 ** the SQLite library will work on both POSIX and windows systems.
9030 **
9031 ** This header file is #include-ed by sqlcipherInt.h and thus ends up
9032 ** being included by every source file.
9033 */
9034 #ifndef _SQLCIPHER_OS_H_
9035 #define _SQLCIPHER_OS_H_
9036
9037 /*
9038 ** Figure out if we are dealing with Unix, Windows, or some other
9039 ** operating system.  After the following block of preprocess macros,
9040 ** all of SQLCIPHER_OS_UNIX, SQLCIPHER_OS_WIN, SQLCIPHER_OS_OS2, and SQLCIPHER_OS_OTHER 
9041 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
9042 ** three will be 0.
9043 */
9044 #if defined(SQLCIPHER_OS_OTHER)
9045 # if SQLCIPHER_OS_OTHER==1
9046 #   undef SQLCIPHER_OS_UNIX
9047 #   define SQLCIPHER_OS_UNIX 0
9048 #   undef SQLCIPHER_OS_WIN
9049 #   define SQLCIPHER_OS_WIN 0
9050 #   undef SQLCIPHER_OS_OS2
9051 #   define SQLCIPHER_OS_OS2 0
9052 # else
9053 #   undef SQLCIPHER_OS_OTHER
9054 # endif
9055 #endif
9056 #if !defined(SQLCIPHER_OS_UNIX) && !defined(SQLCIPHER_OS_OTHER)
9057 # define SQLCIPHER_OS_OTHER 0
9058 # ifndef SQLCIPHER_OS_WIN
9059 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9060 #     define SQLCIPHER_OS_WIN 1
9061 #     define SQLCIPHER_OS_UNIX 0
9062 #     define SQLCIPHER_OS_OS2 0
9063 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9064 #     define SQLCIPHER_OS_WIN 0
9065 #     define SQLCIPHER_OS_UNIX 0
9066 #     define SQLCIPHER_OS_OS2 1
9067 #   else
9068 #     define SQLCIPHER_OS_WIN 0
9069 #     define SQLCIPHER_OS_UNIX 1
9070 #     define SQLCIPHER_OS_OS2 0
9071 #  endif
9072 # else
9073 #  define SQLCIPHER_OS_UNIX 0
9074 #  define SQLCIPHER_OS_OS2 0
9075 # endif
9076 #else
9077 # ifndef SQLCIPHER_OS_WIN
9078 #  define SQLCIPHER_OS_WIN 0
9079 # endif
9080 #endif
9081
9082 /*
9083 ** Determine if we are dealing with WindowsCE - which has a much
9084 ** reduced API.
9085 */
9086 #if defined(_WIN32_WCE)
9087 # define SQLCIPHER_OS_WINCE 1
9088 #else
9089 # define SQLCIPHER_OS_WINCE 0
9090 #endif
9091
9092
9093 /*
9094 ** Define the maximum size of a temporary filename
9095 */
9096 #if SQLCIPHER_OS_WIN
9097 # include <windows.h>
9098 # define SQLCIPHER_TEMPNAME_SIZE (MAX_PATH+50)
9099 #elif SQLCIPHER_OS_OS2
9100 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9101 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
9102 # endif
9103 # define INCL_DOSDATETIME
9104 # define INCL_DOSFILEMGR
9105 # define INCL_DOSERRORS
9106 # define INCL_DOSMISC
9107 # define INCL_DOSPROCESS
9108 # define INCL_DOSMODULEMGR
9109 # define INCL_DOSSEMAPHORES
9110 # include <os2.h>
9111 # include <uconv.h>
9112 # define SQLCIPHER_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9113 #else
9114 # define SQLCIPHER_TEMPNAME_SIZE 200
9115 #endif
9116
9117 /* If the SET_FULLSYNC macro is not defined above, then make it
9118 ** a no-op
9119 */
9120 #ifndef SET_FULLSYNC
9121 # define SET_FULLSYNC(x,y)
9122 #endif
9123
9124 /*
9125 ** The default size of a disk sector
9126 */
9127 #ifndef SQLCIPHER_DEFAULT_SECTOR_SIZE
9128 # define SQLCIPHER_DEFAULT_SECTOR_SIZE 512
9129 #endif
9130
9131 /*
9132 ** Temporary files are named starting with this prefix followed by 16 random
9133 ** alphanumeric characters, and no file extension. They are stored in the
9134 ** OS's standard temporary file directory, and are deleted prior to exit.
9135 ** If sqlcipher is being embedded in another program, you may wish to change the
9136 ** prefix to reflect your program's name, so that if your program exits
9137 ** prematurely, old temporary files can be easily identified. This can be done
9138 ** using -DSQLCIPHER_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9139 **
9140 ** 2006-10-31:  The default prefix used to be "sqlcipher_".  But then
9141 ** Mcafee started using SQLite in their anti-virus product and it
9142 ** started putting files with the "sqlcipher" name in the c:/temp folder.
9143 ** This annoyed many windows users.  Those users would then do a 
9144 ** Google search for "sqlcipher", find the telephone numbers of the
9145 ** developers and call to wake them up at night and complain.
9146 ** For this reason, the default name prefix is changed to be "sqlcipher" 
9147 ** spelled backwards.  So the temp files are still identified, but
9148 ** anybody smart enough to figure out the code is also likely smart
9149 ** enough to know that calling the developer will not help get rid
9150 ** of the file.
9151 */
9152 #ifndef SQLCIPHER_TEMP_FILE_PREFIX
9153 # define SQLCIPHER_TEMP_FILE_PREFIX "etilqs_"
9154 #endif
9155
9156 /*
9157 ** The following values may be passed as the second argument to
9158 ** sqlcipher3OsLock(). The various locks exhibit the following semantics:
9159 **
9160 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9161 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9162 **            any time. Other processes may hold and obtain new SHARED locks.
9163 ** PENDING:   A single process may hold a PENDING lock on a file at
9164 **            any one time. Existing SHARED locks may persist, but no new
9165 **            SHARED locks may be obtained by other processes.
9166 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9167 **
9168 ** PENDING_LOCK may not be passed directly to sqlcipher3OsLock(). Instead, a
9169 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9170 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9171 ** sqlcipher3OsLock().
9172 */
9173 #define NO_LOCK         0
9174 #define SHARED_LOCK     1
9175 #define RESERVED_LOCK   2
9176 #define PENDING_LOCK    3
9177 #define EXCLUSIVE_LOCK  4
9178
9179 /*
9180 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9181 **
9182 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9183 ** those functions are not available.  So we use only LockFile() and
9184 ** UnlockFile().
9185 **
9186 ** LockFile() prevents not just writing but also reading by other processes.
9187 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9188 ** byte out of a specific range of bytes. The lock byte is obtained at 
9189 ** random so two separate readers can probably access the file at the 
9190 ** same time, unless they are unlucky and choose the same lock byte.
9191 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9192 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9193 ** a single byte of the file that is designated as the reserved lock byte.
9194 ** A PENDING_LOCK is obtained by locking a designated byte different from
9195 ** the RESERVED_LOCK byte.
9196 **
9197 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9198 ** which means we can use reader/writer locks.  When reader/writer locks
9199 ** are used, the lock is placed on the same range of bytes that is used
9200 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9201 ** will support two or more Win95 readers or two or more WinNT readers.
9202 ** But a single Win95 reader will lock out all WinNT readers and a single
9203 ** WinNT reader will lock out all other Win95 readers.
9204 **
9205 ** The following #defines specify the range of bytes used for locking.
9206 ** SHARED_SIZE is the number of bytes available in the pool from which
9207 ** a random byte is selected for a shared lock.  The pool of bytes for
9208 ** shared locks begins at SHARED_FIRST. 
9209 **
9210 ** The same locking strategy and
9211 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9212 ** clients on win95, winNT, and unix all talking to the same shared file
9213 ** and all locking correctly.  To do so would require that samba (or whatever
9214 ** tool is being used for file sharing) implements locks correctly between
9215 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9216 ** using the same locking range we are at least open to the possibility.
9217 **
9218 ** Locking in windows is manditory.  For this reason, we cannot store
9219 ** actual data in the bytes used for locking.  The pager never allocates
9220 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9221 ** that all locks will fit on a single page even at the minimum page size.
9222 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9223 ** is set high so that we don't have to allocate an unused page except
9224 ** for very large databases.  But one should test the page skipping logic 
9225 ** by setting PENDING_BYTE low and running the entire regression suite.
9226 **
9227 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9228 ** file format.  Depending on how it is changed, you might not notice
9229 ** the incompatibility right away, even running a full regression test.
9230 ** The default location of PENDING_BYTE is the first byte past the
9231 ** 1GB boundary.
9232 **
9233 */
9234 #ifdef SQLCIPHER_OMIT_WSD
9235 # define PENDING_BYTE     (0x40000000)
9236 #else
9237 # define PENDING_BYTE      sqlcipher3PendingByte
9238 #endif
9239 #define RESERVED_BYTE     (PENDING_BYTE+1)
9240 #define SHARED_FIRST      (PENDING_BYTE+2)
9241 #define SHARED_SIZE       510
9242
9243 /*
9244 ** Wrapper around OS specific sqlcipher3_os_init() function.
9245 */
9246 SQLCIPHER_PRIVATE int sqlcipher3OsInit(void);
9247
9248 /* 
9249 ** Functions for accessing sqlcipher3_file methods 
9250 */
9251 SQLCIPHER_PRIVATE int sqlcipher3OsClose(sqlcipher3_file*);
9252 SQLCIPHER_PRIVATE int sqlcipher3OsRead(sqlcipher3_file*, void*, int amt, i64 offset);
9253 SQLCIPHER_PRIVATE int sqlcipher3OsWrite(sqlcipher3_file*, const void*, int amt, i64 offset);
9254 SQLCIPHER_PRIVATE int sqlcipher3OsTruncate(sqlcipher3_file*, i64 size);
9255 SQLCIPHER_PRIVATE int sqlcipher3OsSync(sqlcipher3_file*, int);
9256 SQLCIPHER_PRIVATE int sqlcipher3OsFileSize(sqlcipher3_file*, i64 *pSize);
9257 SQLCIPHER_PRIVATE int sqlcipher3OsLock(sqlcipher3_file*, int);
9258 SQLCIPHER_PRIVATE int sqlcipher3OsUnlock(sqlcipher3_file*, int);
9259 SQLCIPHER_PRIVATE int sqlcipher3OsCheckReservedLock(sqlcipher3_file *id, int *pResOut);
9260 SQLCIPHER_PRIVATE int sqlcipher3OsFileControl(sqlcipher3_file*,int,void*);
9261 #define SQLCIPHER_FCNTL_DB_UNCHANGED 0xca093fa0
9262 SQLCIPHER_PRIVATE int sqlcipher3OsSectorSize(sqlcipher3_file *id);
9263 SQLCIPHER_PRIVATE int sqlcipher3OsDeviceCharacteristics(sqlcipher3_file *id);
9264 SQLCIPHER_PRIVATE int sqlcipher3OsShmMap(sqlcipher3_file *,int,int,int,void volatile **);
9265 SQLCIPHER_PRIVATE int sqlcipher3OsShmLock(sqlcipher3_file *id, int, int, int);
9266 SQLCIPHER_PRIVATE void sqlcipher3OsShmBarrier(sqlcipher3_file *id);
9267 SQLCIPHER_PRIVATE int sqlcipher3OsShmUnmap(sqlcipher3_file *id, int);
9268
9269 /* 
9270 ** Functions for accessing sqlcipher3_vfs methods 
9271 */
9272 SQLCIPHER_PRIVATE int sqlcipher3OsOpen(sqlcipher3_vfs *, const char *, sqlcipher3_file*, int, int *);
9273 SQLCIPHER_PRIVATE int sqlcipher3OsDelete(sqlcipher3_vfs *, const char *, int);
9274 SQLCIPHER_PRIVATE int sqlcipher3OsAccess(sqlcipher3_vfs *, const char *, int, int *pResOut);
9275 SQLCIPHER_PRIVATE int sqlcipher3OsFullPathname(sqlcipher3_vfs *, const char *, int, char *);
9276 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
9277 SQLCIPHER_PRIVATE void *sqlcipher3OsDlOpen(sqlcipher3_vfs *, const char *);
9278 SQLCIPHER_PRIVATE void sqlcipher3OsDlError(sqlcipher3_vfs *, int, char *);
9279 SQLCIPHER_PRIVATE void (*sqlcipher3OsDlSym(sqlcipher3_vfs *, void *, const char *))(void);
9280 SQLCIPHER_PRIVATE void sqlcipher3OsDlClose(sqlcipher3_vfs *, void *);
9281 #endif /* SQLCIPHER_OMIT_LOAD_EXTENSION */
9282 SQLCIPHER_PRIVATE int sqlcipher3OsRandomness(sqlcipher3_vfs *, int, char *);
9283 SQLCIPHER_PRIVATE int sqlcipher3OsSleep(sqlcipher3_vfs *, int);
9284 SQLCIPHER_PRIVATE int sqlcipher3OsCurrentTimeInt64(sqlcipher3_vfs *, sqlcipher3_int64*);
9285
9286 /*
9287 ** Convenience functions for opening and closing files using 
9288 ** sqlcipher3_malloc() to obtain space for the file-handle structure.
9289 */
9290 SQLCIPHER_PRIVATE int sqlcipher3OsOpenMalloc(sqlcipher3_vfs *, const char *, sqlcipher3_file **, int,int*);
9291 SQLCIPHER_PRIVATE int sqlcipher3OsCloseFree(sqlcipher3_file *);
9292
9293 #endif /* _SQLCIPHER_OS_H_ */
9294
9295 /************** End of os.h **************************************************/
9296 /************** Continuing where we left off in sqlcipherInt.h ******************/
9297 /************** Include mutex.h in the middle of sqlcipherInt.h *****************/
9298 /************** Begin file mutex.h *******************************************/
9299 /*
9300 ** 2007 August 28
9301 **
9302 ** The author disclaims copyright to this source code.  In place of
9303 ** a legal notice, here is a blessing:
9304 **
9305 **    May you do good and not evil.
9306 **    May you find forgiveness for yourself and forgive others.
9307 **    May you share freely, never taking more than you give.
9308 **
9309 *************************************************************************
9310 **
9311 ** This file contains the common header for all mutex implementations.
9312 ** The sqlcipherInt.h header #includes this file so that it is available
9313 ** to all source files.  We break it out in an effort to keep the code
9314 ** better organized.
9315 **
9316 ** NOTE:  source files should *not* #include this header file directly.
9317 ** Source files should #include the sqlcipherInt.h file and let that file
9318 ** include this one indirectly.
9319 */
9320
9321
9322 /*
9323 ** Figure out what version of the code to use.  The choices are
9324 **
9325 **   SQLCIPHER_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9326 **                             mutexes implemention cannot be overridden
9327 **                             at start-time.
9328 **
9329 **   SQLCIPHER_MUTEX_NOOP         For single-threaded applications.  No
9330 **                             mutual exclusion is provided.  But this
9331 **                             implementation can be overridden at
9332 **                             start-time.
9333 **
9334 **   SQLCIPHER_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9335 **
9336 **   SQLCIPHER_MUTEX_W32          For multi-threaded applications on Win32.
9337 **
9338 **   SQLCIPHER_MUTEX_OS2          For multi-threaded applications on OS/2.
9339 */
9340 #if !SQLCIPHER_THREADSAFE
9341 # define SQLCIPHER_MUTEX_OMIT
9342 #endif
9343 #if SQLCIPHER_THREADSAFE && !defined(SQLCIPHER_MUTEX_NOOP)
9344 #  if SQLCIPHER_OS_UNIX
9345 #    define SQLCIPHER_MUTEX_PTHREADS
9346 #  elif SQLCIPHER_OS_WIN
9347 #    define SQLCIPHER_MUTEX_W32
9348 #  elif SQLCIPHER_OS_OS2
9349 #    define SQLCIPHER_MUTEX_OS2
9350 #  else
9351 #    define SQLCIPHER_MUTEX_NOOP
9352 #  endif
9353 #endif
9354
9355 #ifdef SQLCIPHER_MUTEX_OMIT
9356 /*
9357 ** If this is a no-op implementation, implement everything as macros.
9358 */
9359 #define sqlcipher3_mutex_alloc(X)    ((sqlcipher3_mutex*)8)
9360 #define sqlcipher3_mutex_free(X)
9361 #define sqlcipher3_mutex_enter(X)    
9362 #define sqlcipher3_mutex_try(X)      SQLCIPHER_OK
9363 #define sqlcipher3_mutex_leave(X)    
9364 #define sqlcipher3_mutex_held(X)     ((void)(X),1)
9365 #define sqlcipher3_mutex_notheld(X)  ((void)(X),1)
9366 #define sqlcipher3MutexAlloc(X)      ((sqlcipher3_mutex*)8)
9367 #define sqlcipher3MutexInit()        SQLCIPHER_OK
9368 #define sqlcipher3MutexEnd()
9369 #define MUTEX_LOGIC(X)
9370 #else
9371 #define MUTEX_LOGIC(X)            X
9372 #endif /* defined(SQLCIPHER_MUTEX_OMIT) */
9373
9374 /************** End of mutex.h ***********************************************/
9375 /************** Continuing where we left off in sqlcipherInt.h ******************/
9376
9377
9378 /*
9379 ** Each database file to be accessed by the system is an instance
9380 ** of the following structure.  There are normally two of these structures
9381 ** in the sqlcipher.aDb[] array.  aDb[0] is the main database file and
9382 ** aDb[1] is the database file used to hold temporary tables.  Additional
9383 ** databases may be attached.
9384 */
9385 struct Db {
9386   char *zName;         /* Name of this database */
9387   Btree *pBt;          /* The B*Tree structure for this database file */
9388   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9389   u8 safety_level;     /* How aggressive at syncing data to disk */
9390   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9391 };
9392
9393 /*
9394 ** An instance of the following structure stores a database schema.
9395 **
9396 ** Most Schema objects are associated with a Btree.  The exception is
9397 ** the Schema for the TEMP databaes (sqlcipher3.aDb[1]) which is free-standing.
9398 ** In shared cache mode, a single Schema object can be shared by multiple
9399 ** Btrees that refer to the same underlying BtShared object.
9400 ** 
9401 ** Schema objects are automatically deallocated when the last Btree that
9402 ** references them is destroyed.   The TEMP Schema is manually freed by
9403 ** sqlcipher3_close().
9404 *
9405 ** A thread must be holding a mutex on the corresponding Btree in order
9406 ** to access Schema content.  This implies that the thread must also be
9407 ** holding a mutex on the sqlcipher3 connection pointer that owns the Btree.
9408 ** For a TEMP Schema, only the connection mutex is required.
9409 */
9410 struct Schema {
9411   int schema_cookie;   /* Database schema version number for this file */
9412   int iGeneration;     /* Generation counter.  Incremented with each change */
9413   Hash tblHash;        /* All tables indexed by name */
9414   Hash idxHash;        /* All (named) indices indexed by name */
9415   Hash trigHash;       /* All triggers indexed by name */
9416   Hash fkeyHash;       /* All foreign keys by referenced table name */
9417   Table *pSeqTab;      /* The sqlcipher_sequence table used by AUTOINCREMENT */
9418   u8 file_format;      /* Schema format version for this file */
9419   u8 enc;              /* Text encoding used by this database */
9420   u16 flags;           /* Flags associated with this schema */
9421   int cache_size;      /* Number of pages to use in the cache */
9422 };
9423
9424 /*
9425 ** These macros can be used to test, set, or clear bits in the 
9426 ** Db.pSchema->flags field.
9427 */
9428 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9429 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9430 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9431 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9432
9433 /*
9434 ** Allowed values for the DB.pSchema->flags field.
9435 **
9436 ** The DB_SchemaLoaded flag is set after the database schema has been
9437 ** read into internal hash tables.
9438 **
9439 ** DB_UnresetViews means that one or more views have column names that
9440 ** have been filled out.  If the schema changes, these column names might
9441 ** changes and so the view will need to be reset.
9442 */
9443 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9444 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9445 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9446
9447 /*
9448 ** The number of different kinds of things that can be limited
9449 ** using the sqlcipher3_limit() interface.
9450 */
9451 #define SQLCIPHER_N_LIMIT (SQLCIPHER_LIMIT_TRIGGER_DEPTH+1)
9452
9453 /*
9454 ** Lookaside malloc is a set of fixed-size buffers that can be used
9455 ** to satisfy small transient memory allocation requests for objects
9456 ** associated with a particular database connection.  The use of
9457 ** lookaside malloc provides a significant performance enhancement
9458 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9459 ** SQL statements.
9460 **
9461 ** The Lookaside structure holds configuration information about the
9462 ** lookaside malloc subsystem.  Each available memory allocation in
9463 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9464 ** objects.
9465 **
9466 ** Lookaside allocations are only allowed for objects that are associated
9467 ** with a particular database connection.  Hence, schema information cannot
9468 ** be stored in lookaside because in shared cache mode the schema information
9469 ** is shared by multiple database connections.  Therefore, while parsing
9470 ** schema information, the Lookaside.bEnabled flag is cleared so that
9471 ** lookaside allocations are not used to construct the schema objects.
9472 */
9473 struct Lookaside {
9474   u16 sz;                 /* Size of each buffer in bytes */
9475   u8 bEnabled;            /* False to disable new lookaside allocations */
9476   u8 bMalloced;           /* True if pStart obtained from sqlcipher3_malloc() */
9477   int nOut;               /* Number of buffers currently checked out */
9478   int mxOut;              /* Highwater mark for nOut */
9479   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9480   LookasideSlot *pFree;   /* List of available buffers */
9481   void *pStart;           /* First byte of available memory space */
9482   void *pEnd;             /* First byte past end of available space */
9483 };
9484 struct LookasideSlot {
9485   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9486 };
9487
9488 /*
9489 ** A hash table for function definitions.
9490 **
9491 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9492 ** Collisions are on the FuncDef.pHash chain.
9493 */
9494 struct FuncDefHash {
9495   FuncDef *a[23];       /* Hash table for functions */
9496 };
9497
9498 /*
9499 ** Each database connection is an instance of the following structure.
9500 **
9501 ** The sqlcipher.lastRowid records the last insert rowid generated by an
9502 ** insert statement.  Inserts on views do not affect its value.  Each
9503 ** trigger has its own context, so that lastRowid can be updated inside
9504 ** triggers as usual.  The previous value will be restored once the trigger
9505 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9506 ** longer (since after version 2.8.12) reset to -1.
9507 **
9508 ** The sqlcipher.nChange does not count changes within triggers and keeps no
9509 ** context.  It is reset at start of sqlcipher3_exec.
9510 ** The sqlcipher.lsChange represents the number of changes made by the last
9511 ** insert, update, or delete statement.  It remains constant throughout the
9512 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9513 ** context stack just like lastRowid so that the count of changes
9514 ** within a trigger is not seen outside the trigger.  Changes to views do not
9515 ** affect the value of lsChange.
9516 ** The sqlcipher.csChange keeps track of the number of current changes (since
9517 ** the last statement) and is used to update sqlcipher_lsChange.
9518 **
9519 ** The member variables sqlcipher.errCode, sqlcipher.zErrMsg and sqlcipher.zErrMsg16
9520 ** store the most recent error code and, if applicable, string. The
9521 ** internal function sqlcipher3Error() is used to set these variables
9522 ** consistently.
9523 */
9524 struct sqlcipher3 {
9525   sqlcipher3_vfs *pVfs;            /* OS Interface */
9526   int nDb;                      /* Number of backends currently in use */
9527   Db *aDb;                      /* All backends */
9528   int flags;                    /* Miscellaneous flags. See below */
9529   unsigned int openFlags;       /* Flags passed to sqlcipher3_vfs.xOpen() */
9530   int errCode;                  /* Most recent error code (SQLCIPHER_*) */
9531   int errMask;                  /* & result codes with this before returning */
9532   u8 autoCommit;                /* The auto-commit flag. */
9533   u8 temp_store;                /* 1: file 2: memory 0: default */
9534   u8 mallocFailed;              /* True if we have seen a malloc failure */
9535   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9536   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9537   u8 suppressErr;               /* Do not issue error messages if true */
9538   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9539   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9540   int nTable;                   /* Number of tables in the database */
9541   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9542   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9543   u32 magic;                    /* Magic number for detect library misuse */
9544   int nChange;                  /* Value returned by sqlcipher3_changes() */
9545   int nTotalChange;             /* Value returned by sqlcipher3_total_changes() */
9546   sqlcipher3_mutex *mutex;         /* Connection mutex */
9547   int aLimit[SQLCIPHER_N_LIMIT];   /* Limits */
9548   struct sqlcipher3InitInfo {      /* Information used during initialization */
9549     int iDb;                    /* When back is being initialized */
9550     int newTnum;                /* Rootpage of table being initialized */
9551     u8 busy;                    /* TRUE if currently initializing */
9552     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9553   } init;
9554   int nExtension;               /* Number of loaded extensions */
9555   void **aExtension;            /* Array of shared library handles */
9556   struct Vdbe *pVdbe;           /* List of active virtual machines */
9557   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9558   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9559   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9560   void (*xTrace)(void*,const char*);        /* Trace function */
9561   void *pTraceArg;                          /* Argument to the trace function */
9562   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9563   void *pProfileArg;                        /* Argument to profile function */
9564   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9565   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9566   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9567   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9568   void *pUpdateArg;
9569   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlcipher_int64);
9570 #ifndef SQLCIPHER_OMIT_WAL
9571   int (*xWalCallback)(void *, sqlcipher3 *, const char *, int);
9572   void *pWalArg;
9573 #endif
9574   void(*xCollNeeded)(void*,sqlcipher3*,int eTextRep,const char*);
9575   void(*xCollNeeded16)(void*,sqlcipher3*,int eTextRep,const void*);
9576   void *pCollNeededArg;
9577   sqlcipher3_value *pErr;          /* Most recent error message */
9578   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9579   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9580   union {
9581     volatile int isInterrupted; /* True if sqlcipher3_interrupt has been called */
9582     double notUsed1;            /* Spacer */
9583   } u1;
9584   Lookaside lookaside;          /* Lookaside malloc configuration */
9585 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
9586   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9587                                 /* Access authorization function */
9588   void *pAuthArg;               /* 1st argument to the access auth function */
9589 #endif
9590 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
9591   int (*xProgress)(void *);     /* The progress callback */
9592   void *pProgressArg;           /* Argument to the progress callback */
9593   int nProgressOps;             /* Number of opcodes for progress callback */
9594 #endif
9595 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
9596   Hash aModule;                 /* populated by sqlcipher3_create_module() */
9597   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9598   VTable **aVTrans;             /* Virtual tables with open transactions */
9599   int nVTrans;                  /* Allocated size of aVTrans */
9600   VTable *pDisconnect;    /* Disconnect these in next sqlcipher3_prepare() */
9601 #endif
9602   FuncDefHash aFunc;            /* Hash table of connection functions */
9603   Hash aCollSeq;                /* All collating sequences */
9604   BusyHandler busyHandler;      /* Busy callback */
9605   int busyTimeout;              /* Busy handler timeout, in msec */
9606   Db aDbStatic[2];              /* Static space for the 2 default backends */
9607   Savepoint *pSavepoint;        /* List of active savepoints */
9608   int nSavepoint;               /* Number of non-transaction savepoints */
9609   int nStatement;               /* Number of nested statement-transactions  */
9610   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9611   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9612   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9613
9614 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
9615   /* The following variables are all protected by the STATIC_MASTER 
9616   ** mutex, not by sqlcipher3.mutex. They are used by code in notify.c. 
9617   **
9618   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9619   ** unlock so that it can proceed.
9620   **
9621   ** When X.pBlockingConnection==Y, that means that something that X tried
9622   ** tried to do recently failed with an SQLCIPHER_LOCKED error due to locks
9623   ** held by Y.
9624   */
9625   sqlcipher3 *pBlockingConnection; /* Connection that caused SQLCIPHER_LOCKED */
9626   sqlcipher3 *pUnlockConnection;           /* Connection to watch for unlock */
9627   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9628   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9629   sqlcipher3 *pNextBlocked;        /* Next in list of all blocked connections */
9630 #endif
9631 };
9632
9633 /*
9634 ** A macro to discover the encoding of a database.
9635 */
9636 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9637
9638 /*
9639 ** Possible values for the sqlcipher3.flags.
9640 */
9641 #define SQLCIPHER_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9642 #define SQLCIPHER_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9643 #define SQLCIPHER_FullColNames   0x00000400  /* Show full column names on SELECT */
9644 #define SQLCIPHER_ShortColNames  0x00000800  /* Show short columns names */
9645 #define SQLCIPHER_CountRows      0x00001000  /* Count rows changed by INSERT, */
9646                                           /*   DELETE, or UPDATE and return */
9647                                           /*   the count using a callback. */
9648 #define SQLCIPHER_NullCallback   0x00002000  /* Invoke the callback once if the */
9649                                           /*   result set is empty */
9650 #define SQLCIPHER_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9651 #define SQLCIPHER_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9652 #define SQLCIPHER_WriteSchema    0x00010000  /* OK to update SQLCIPHER_MASTER */
9653 #define SQLCIPHER_NoReadlock     0x00020000  /* Readlocks are omitted when 
9654                                           ** accessing read-only databases */
9655 #define SQLCIPHER_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9656 #define SQLCIPHER_ReadUncommitted 0x0080000  /* For shared-cache mode */
9657 #define SQLCIPHER_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9658 #define SQLCIPHER_FullFSync      0x00200000  /* Use full fsync on the backend */
9659 #define SQLCIPHER_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9660 #define SQLCIPHER_RecoveryMode   0x00800000  /* Ignore schema errors */
9661 #define SQLCIPHER_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9662 #define SQLCIPHER_RecTriggers    0x02000000  /* Enable recursive triggers */
9663 #define SQLCIPHER_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9664 #define SQLCIPHER_AutoIndex      0x08000000  /* Enable automatic indexes */
9665 #define SQLCIPHER_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9666 #define SQLCIPHER_LoadExtension  0x20000000  /* Enable load_extension */
9667 #define SQLCIPHER_EnableTrigger  0x40000000  /* True to enable triggers */
9668
9669 /*
9670 ** Bits of the sqlcipher3.flags field that are used by the
9671 ** sqlcipher3_test_control(SQLCIPHER_TESTCTRL_OPTIMIZATIONS,...) interface.
9672 ** These must be the low-order bits of the flags field.
9673 */
9674 #define SQLCIPHER_QueryFlattener 0x01        /* Disable query flattening */
9675 #define SQLCIPHER_ColumnCache    0x02        /* Disable the column cache */
9676 #define SQLCIPHER_IndexSort      0x04        /* Disable indexes for sorting */
9677 #define SQLCIPHER_IndexSearch    0x08        /* Disable indexes for searching */
9678 #define SQLCIPHER_IndexCover     0x10        /* Disable index covering table */
9679 #define SQLCIPHER_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9680 #define SQLCIPHER_FactorOutConst 0x40        /* Disable factoring out constants */
9681 #define SQLCIPHER_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9682 #define SQLCIPHER_DistinctOpt    0x80        /* DISTINCT using indexes */
9683 #define SQLCIPHER_OptMask        0xff        /* Mask of all disablable opts */
9684
9685 /*
9686 ** Possible values for the sqlcipher.magic field.
9687 ** The numbers are obtained at random and have no special meaning, other
9688 ** than being distinct from one another.
9689 */
9690 #define SQLCIPHER_MAGIC_OPEN     0xa029a697  /* Database is open */
9691 #define SQLCIPHER_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9692 #define SQLCIPHER_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9693 #define SQLCIPHER_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9694 #define SQLCIPHER_MAGIC_ERROR    0xb5357930  /* An SQLCIPHER_MISUSE error occurred */
9695
9696 /*
9697 ** Each SQL function is defined by an instance of the following
9698 ** structure.  A pointer to this structure is stored in the sqlcipher.aFunc
9699 ** hash table.  When multiple functions have the same name, the hash table
9700 ** points to a linked list of these structures.
9701 */
9702 struct FuncDef {
9703   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9704   u8 iPrefEnc;         /* Preferred text encoding (SQLCIPHER_UTF8, 16LE, 16BE) */
9705   u8 flags;            /* Some combination of SQLCIPHER_FUNC_* */
9706   void *pUserData;     /* User data parameter */
9707   FuncDef *pNext;      /* Next function with same name */
9708   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**); /* Regular function */
9709   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**); /* Aggregate step */
9710   void (*xFinalize)(sqlcipher3_context*);                /* Aggregate finalizer */
9711   char *zName;         /* SQL name of the function. */
9712   FuncDef *pHash;      /* Next with a different name but the same hash */
9713   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9714 };
9715
9716 /*
9717 ** This structure encapsulates a user-function destructor callback (as
9718 ** configured using create_function_v2()) and a reference counter. When
9719 ** create_function_v2() is called to create a function with a destructor,
9720 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9721 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9722 ** or not the specified encoding is SQLCIPHER_ANY). The FuncDef.pDestructor
9723 ** member of each of the new FuncDef objects is set to point to the allocated
9724 ** FuncDestructor.
9725 **
9726 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9727 ** count on this object is decremented. When it reaches 0, the destructor
9728 ** is invoked and the FuncDestructor structure freed.
9729 */
9730 struct FuncDestructor {
9731   int nRef;
9732   void (*xDestroy)(void *);
9733   void *pUserData;
9734 };
9735
9736 /*
9737 ** Possible values for FuncDef.flags
9738 */
9739 #define SQLCIPHER_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9740 #define SQLCIPHER_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9741 #define SQLCIPHER_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9742 #define SQLCIPHER_FUNC_NEEDCOLL 0x08 /* sqlcipher3GetFuncCollSeq() might be called */
9743 #define SQLCIPHER_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9744 #define SQLCIPHER_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9745 #define SQLCIPHER_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9746
9747 /*
9748 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9749 ** used to create the initializers for the FuncDef structures.
9750 **
9751 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9752 **     Used to create a scalar function definition of a function zName 
9753 **     implemented by C function xFunc that accepts nArg arguments. The
9754 **     value passed as iArg is cast to a (void*) and made available
9755 **     as the user-data (sqlcipher3_user_data()) for the function. If 
9756 **     argument bNC is true, then the SQLCIPHER_FUNC_NEEDCOLL flag is set.
9757 **
9758 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9759 **     Used to create an aggregate function definition implemented by
9760 **     the C functions xStep and xFinal. The first four parameters
9761 **     are interpreted in the same way as the first 4 parameters to
9762 **     FUNCTION().
9763 **
9764 **   LIKEFUNC(zName, nArg, pArg, flags)
9765 **     Used to create a scalar function definition of a function zName 
9766 **     that accepts nArg arguments and is implemented by a call to C 
9767 **     function likeFunc. Argument pArg is cast to a (void *) and made
9768 **     available as the function user-data (sqlcipher3_user_data()). The
9769 **     FuncDef.flags variable is set to the value passed as the flags
9770 **     parameter.
9771 */
9772 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9773   {nArg, SQLCIPHER_UTF8, bNC*SQLCIPHER_FUNC_NEEDCOLL, \
9774    SQLCIPHER_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9775 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9776   {nArg, SQLCIPHER_UTF8, bNC*SQLCIPHER_FUNC_NEEDCOLL, \
9777    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9778 #define LIKEFUNC(zName, nArg, arg, flags) \
9779   {nArg, SQLCIPHER_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9780 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9781   {nArg, SQLCIPHER_UTF8, nc*SQLCIPHER_FUNC_NEEDCOLL, \
9782    SQLCIPHER_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9783
9784 /*
9785 ** All current savepoints are stored in a linked list starting at
9786 ** sqlcipher3.pSavepoint. The first element in the list is the most recently
9787 ** opened savepoint. Savepoints are added to the list by the vdbe
9788 ** OP_Savepoint instruction.
9789 */
9790 struct Savepoint {
9791   char *zName;                        /* Savepoint name (nul-terminated) */
9792   i64 nDeferredCons;                  /* Number of deferred fk violations */
9793   Savepoint *pNext;                   /* Parent savepoint (if any) */
9794 };
9795
9796 /*
9797 ** The following are used as the second parameter to sqlcipher3Savepoint(),
9798 ** and as the P1 argument to the OP_Savepoint instruction.
9799 */
9800 #define SAVEPOINT_BEGIN      0
9801 #define SAVEPOINT_RELEASE    1
9802 #define SAVEPOINT_ROLLBACK   2
9803
9804
9805 /*
9806 ** Each SQLite module (virtual table definition) is defined by an
9807 ** instance of the following structure, stored in the sqlcipher3.aModule
9808 ** hash table.
9809 */
9810 struct Module {
9811   const sqlcipher3_module *pModule;       /* Callback pointers */
9812   const char *zName;                   /* Name passed to create_module() */
9813   void *pAux;                          /* pAux passed to create_module() */
9814   void (*xDestroy)(void *);            /* Module destructor function */
9815 };
9816
9817 /*
9818 ** information about each column of an SQL table is held in an instance
9819 ** of this structure.
9820 */
9821 struct Column {
9822   char *zName;     /* Name of this column */
9823   Expr *pDflt;     /* Default value of this column */
9824   char *zDflt;     /* Original text of the default value */
9825   char *zType;     /* Data type for this column */
9826   char *zColl;     /* Collating sequence.  If NULL, use the default */
9827   u8 notNull;      /* True if there is a NOT NULL constraint */
9828   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9829   char affinity;   /* One of the SQLCIPHER_AFF_... values */
9830 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
9831   u8 isHidden;     /* True if this column is 'hidden' */
9832 #endif
9833 };
9834
9835 /*
9836 ** A "Collating Sequence" is defined by an instance of the following
9837 ** structure. Conceptually, a collating sequence consists of a name and
9838 ** a comparison routine that defines the order of that sequence.
9839 **
9840 ** There may two separate implementations of the collation function, one
9841 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9842 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9843 ** native byte order. When a collation sequence is invoked, SQLite selects
9844 ** the version that will require the least expensive encoding
9845 ** translations, if any.
9846 **
9847 ** The CollSeq.pUser member variable is an extra parameter that passed in
9848 ** as the first argument to the UTF-8 comparison function, xCmp.
9849 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9850 ** xCmp16.
9851 **
9852 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9853 ** collating sequence is undefined.  Indices built on an undefined
9854 ** collating sequence may not be read or written.
9855 */
9856 struct CollSeq {
9857   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9858   u8 enc;               /* Text encoding handled by xCmp() */
9859   u8 type;              /* One of the SQLCIPHER_COLL_... values below */
9860   void *pUser;          /* First argument to xCmp() */
9861   int (*xCmp)(void*,int, const void*, int, const void*);
9862   void (*xDel)(void*);  /* Destructor for pUser */
9863 };
9864
9865 /*
9866 ** Allowed values of CollSeq.type:
9867 */
9868 #define SQLCIPHER_COLL_BINARY  1  /* The default memcmp() collating sequence */
9869 #define SQLCIPHER_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9870 #define SQLCIPHER_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9871 #define SQLCIPHER_COLL_USER    0  /* Any other user-defined collating sequence */
9872
9873 /*
9874 ** A sort order can be either ASC or DESC.
9875 */
9876 #define SQLCIPHER_SO_ASC       0  /* Sort in ascending order */
9877 #define SQLCIPHER_SO_DESC      1  /* Sort in ascending order */
9878
9879 /*
9880 ** Column affinity types.
9881 **
9882 ** These used to have mnemonic name like 'i' for SQLCIPHER_AFF_INTEGER and
9883 ** 't' for SQLCIPHER_AFF_TEXT.  But we can save a little space and improve
9884 ** the speed a little by numbering the values consecutively.  
9885 **
9886 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9887 ** when multiple affinity types are concatenated into a string and
9888 ** used as the P4 operand, they will be more readable.
9889 **
9890 ** Note also that the numeric types are grouped together so that testing
9891 ** for a numeric type is a single comparison.
9892 */
9893 #define SQLCIPHER_AFF_TEXT     'a'
9894 #define SQLCIPHER_AFF_NONE     'b'
9895 #define SQLCIPHER_AFF_NUMERIC  'c'
9896 #define SQLCIPHER_AFF_INTEGER  'd'
9897 #define SQLCIPHER_AFF_REAL     'e'
9898
9899 #define sqlcipher3IsNumericAffinity(X)  ((X)>=SQLCIPHER_AFF_NUMERIC)
9900
9901 /*
9902 ** The SQLCIPHER_AFF_MASK values masks off the significant bits of an
9903 ** affinity value. 
9904 */
9905 #define SQLCIPHER_AFF_MASK     0x67
9906
9907 /*
9908 ** Additional bit values that can be ORed with an affinity without
9909 ** changing the affinity.
9910 */
9911 #define SQLCIPHER_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9912 #define SQLCIPHER_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9913 #define SQLCIPHER_NULLEQ       0x80  /* NULL=NULL */
9914
9915 /*
9916 ** An object of this type is created for each virtual table present in
9917 ** the database schema. 
9918 **
9919 ** If the database schema is shared, then there is one instance of this
9920 ** structure for each database connection (sqlcipher3*) that uses the shared
9921 ** schema. This is because each database connection requires its own unique
9922 ** instance of the sqlcipher3_vtab* handle used to access the virtual table 
9923 ** implementation. sqlcipher3_vtab* handles can not be shared between 
9924 ** database connections, even when the rest of the in-memory database 
9925 ** schema is shared, as the implementation often stores the database
9926 ** connection handle passed to it via the xConnect() or xCreate() method
9927 ** during initialization internally. This database connection handle may
9928 ** then be used by the virtual table implementation to access real tables 
9929 ** within the database. So that they appear as part of the callers 
9930 ** transaction, these accesses need to be made via the same database 
9931 ** connection as that used to execute SQL operations on the virtual table.
9932 **
9933 ** All VTable objects that correspond to a single table in a shared
9934 ** database schema are initially stored in a linked-list pointed to by
9935 ** the Table.pVTable member variable of the corresponding Table object.
9936 ** When an sqlcipher3_prepare() operation is required to access the virtual
9937 ** table, it searches the list for the VTable that corresponds to the
9938 ** database connection doing the preparing so as to use the correct
9939 ** sqlcipher3_vtab* handle in the compiled query.
9940 **
9941 ** When an in-memory Table object is deleted (for example when the
9942 ** schema is being reloaded for some reason), the VTable objects are not 
9943 ** deleted and the sqlcipher3_vtab* handles are not xDisconnect()ed 
9944 ** immediately. Instead, they are moved from the Table.pVTable list to
9945 ** another linked list headed by the sqlcipher3.pDisconnect member of the
9946 ** corresponding sqlcipher3 structure. They are then deleted/xDisconnected 
9947 ** next time a statement is prepared using said sqlcipher3*. This is done
9948 ** to avoid deadlock issues involving multiple sqlcipher3.mutex mutexes.
9949 ** Refer to comments above function sqlcipher3VtabUnlockList() for an
9950 ** explanation as to why it is safe to add an entry to an sqlcipher3.pDisconnect
9951 ** list without holding the corresponding sqlcipher3.mutex mutex.
9952 **
9953 ** The memory for objects of this type is always allocated by 
9954 ** sqlcipher3DbMalloc(), using the connection handle stored in VTable.db as 
9955 ** the first argument.
9956 */
9957 struct VTable {
9958   sqlcipher3 *db;              /* Database connection associated with this table */
9959   Module *pMod;             /* Pointer to module implementation */
9960   sqlcipher3_vtab *pVtab;      /* Pointer to vtab instance */
9961   int nRef;                 /* Number of pointers to this structure */
9962   u8 bConstraint;           /* True if constraints are supported */
9963   int iSavepoint;           /* Depth of the SAVEPOINT stack */
9964   VTable *pNext;            /* Next in linked list (see above) */
9965 };
9966
9967 /*
9968 ** Each SQL table is represented in memory by an instance of the
9969 ** following structure.
9970 **
9971 ** Table.zName is the name of the table.  The case of the original
9972 ** CREATE TABLE statement is stored, but case is not significant for
9973 ** comparisons.
9974 **
9975 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9976 ** pointer to an array of Column structures, one for each column.
9977 **
9978 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9979 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9980 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9981 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9982 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9983 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9984 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9985 **
9986 ** Table.tnum is the page number for the root BTree page of the table in the
9987 ** database file.  If Table.iDb is the index of the database table backend
9988 ** in sqlcipher.aDb[].  0 is for the main database and 1 is for the file that
9989 ** holds temporary tables and indices.  If TF_Ephemeral is set
9990 ** then the table is stored in a file that is automatically deleted
9991 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9992 ** refers VDBE cursor number that holds the table open, not to the root
9993 ** page number.  Transient tables are used to hold the results of a
9994 ** sub-query that appears instead of a real table name in the FROM clause 
9995 ** of a SELECT statement.
9996 */
9997 struct Table {
9998   char *zName;         /* Name of the table or view */
9999   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10000   int nCol;            /* Number of columns in this table */
10001   Column *aCol;        /* Information about each column */
10002   Index *pIndex;       /* List of SQL indexes on this table. */
10003   int tnum;            /* Root BTree node for this table (see note above) */
10004   tRowcnt nRowEst;     /* Estimated rows in table - from sqlcipher_stat1 table */
10005   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10006   u16 nRef;            /* Number of pointers to this Table */
10007   u8 tabFlags;         /* Mask of TF_* values */
10008   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10009   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10010   char *zColAff;       /* String defining the affinity of each column */
10011 #ifndef SQLCIPHER_OMIT_CHECK
10012   Expr *pCheck;        /* The AND of all CHECK constraints */
10013 #endif
10014 #ifndef SQLCIPHER_OMIT_ALTERTABLE
10015   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10016 #endif
10017 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
10018   VTable *pVTable;     /* List of VTable objects. */
10019   int nModuleArg;      /* Number of arguments to the module */
10020   char **azModuleArg;  /* Text of all module args. [0] is module name */
10021 #endif
10022   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10023   Schema *pSchema;     /* Schema that contains this table */
10024   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10025 };
10026
10027 /*
10028 ** Allowed values for Tabe.tabFlags.
10029 */
10030 #define TF_Readonly        0x01    /* Read-only system table */
10031 #define TF_Ephemeral       0x02    /* An ephemeral table */
10032 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10033 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10034 #define TF_Virtual         0x10    /* Is a virtual table */
10035 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
10036
10037
10038
10039 /*
10040 ** Test to see whether or not a table is a virtual table.  This is
10041 ** done as a macro so that it will be optimized out when virtual
10042 ** table support is omitted from the build.
10043 */
10044 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
10045 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10046 #  define IsHiddenColumn(X) ((X)->isHidden)
10047 #else
10048 #  define IsVirtual(X)      0
10049 #  define IsHiddenColumn(X) 0
10050 #endif
10051
10052 /*
10053 ** Each foreign key constraint is an instance of the following structure.
10054 **
10055 ** A foreign key is associated with two tables.  The "from" table is
10056 ** the table that contains the REFERENCES clause that creates the foreign
10057 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10058 ** Consider this example:
10059 **
10060 **     CREATE TABLE ex1(
10061 **       a INTEGER PRIMARY KEY,
10062 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10063 **     );
10064 **
10065 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10066 **
10067 ** Each REFERENCES clause generates an instance of the following structure
10068 ** which is attached to the from-table.  The to-table need not exist when
10069 ** the from-table is created.  The existence of the to-table is not checked.
10070 */
10071 struct FKey {
10072   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10073   FKey *pNextFrom;  /* Next foreign key in pFrom */
10074   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10075   FKey *pNextTo;    /* Next foreign key on table named zTo */
10076   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10077   int nCol;         /* Number of columns in this key */
10078   /* EV: R-30323-21917 */
10079   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10080   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10081   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10082   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10083     int iFrom;         /* Index of column in pFrom */
10084     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10085   } aCol[1];        /* One entry for each of nCol column s */
10086 };
10087
10088 /*
10089 ** SQLite supports many different ways to resolve a constraint
10090 ** error.  ROLLBACK processing means that a constraint violation
10091 ** causes the operation in process to fail and for the current transaction
10092 ** to be rolled back.  ABORT processing means the operation in process
10093 ** fails and any prior changes from that one operation are backed out,
10094 ** but the transaction is not rolled back.  FAIL processing means that
10095 ** the operation in progress stops and returns an error code.  But prior
10096 ** changes due to the same operation are not backed out and no rollback
10097 ** occurs.  IGNORE means that the particular row that caused the constraint
10098 ** error is not inserted or updated.  Processing continues and no error
10099 ** is returned.  REPLACE means that preexisting database rows that caused
10100 ** a UNIQUE constraint violation are removed so that the new insert or
10101 ** update can proceed.  Processing continues and no error is reported.
10102 **
10103 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10104 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10105 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10106 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10107 ** referenced table row is propagated into the row that holds the
10108 ** foreign key.
10109 ** 
10110 ** The following symbolic values are used to record which type
10111 ** of action to take.
10112 */
10113 #define OE_None     0   /* There is no constraint to check */
10114 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10115 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10116 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10117 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10118 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10119
10120 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10121 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10122 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10123 #define OE_Cascade  9   /* Cascade the changes */
10124
10125 #define OE_Default  99  /* Do whatever the default action is */
10126
10127
10128 /*
10129 ** An instance of the following structure is passed as the first
10130 ** argument to sqlcipher3VdbeKeyCompare and is used to control the 
10131 ** comparison of the two index keys.
10132 */
10133 struct KeyInfo {
10134   sqlcipher3 *db;        /* The database connection */
10135   u8 enc;             /* Text encoding - one of the SQLCIPHER_UTF* values */
10136   u16 nField;         /* Number of entries in aColl[] */
10137   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10138   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10139 };
10140
10141 /*
10142 ** An instance of the following structure holds information about a
10143 ** single index record that has already been parsed out into individual
10144 ** values.
10145 **
10146 ** A record is an object that contains one or more fields of data.
10147 ** Records are used to store the content of a table row and to store
10148 ** the key of an index.  A blob encoding of a record is created by
10149 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10150 ** OP_Column opcode.
10151 **
10152 ** This structure holds a record that has already been disassembled
10153 ** into its constituent fields.
10154 */
10155 struct UnpackedRecord {
10156   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10157   u16 nField;         /* Number of entries in apMem[] */
10158   u16 flags;          /* Boolean settings.  UNPACKED_... below */
10159   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10160   Mem *aMem;          /* Values */
10161 };
10162
10163 /*
10164 ** Allowed values of UnpackedRecord.flags
10165 */
10166 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlcipher3Malloc() */
10167 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
10168 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
10169 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
10170 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
10171 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
10172
10173 /*
10174 ** Each SQL index is represented in memory by an
10175 ** instance of the following structure.
10176 **
10177 ** The columns of the table that are to be indexed are described
10178 ** by the aiColumn[] field of this structure.  For example, suppose
10179 ** we have the following table and index:
10180 **
10181 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10182 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10183 **
10184 ** In the Table structure describing Ex1, nCol==3 because there are
10185 ** three columns in the table.  In the Index structure describing
10186 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10187 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10188 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10189 ** The second column to be indexed (c1) has an index of 0 in
10190 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10191 **
10192 ** The Index.onError field determines whether or not the indexed columns
10193 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10194 ** it means this is not a unique index.  Otherwise it is a unique index
10195 ** and the value of Index.onError indicate the which conflict resolution 
10196 ** algorithm to employ whenever an attempt is made to insert a non-unique
10197 ** element.
10198 */
10199 struct Index {
10200   char *zName;     /* Name of this index */
10201   int nColumn;     /* Number of columns in the table used by this index */
10202   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10203   tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10204   Table *pTable;   /* The SQL table being indexed */
10205   int tnum;        /* Page containing root of this index in database file */
10206   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10207   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10208   u8 bUnordered;   /* Use this index for == or IN queries only */
10209   char *zColAff;   /* String defining the affinity of each column */
10210   Index *pNext;    /* The next index associated with the same table */
10211   Schema *pSchema; /* Schema containing this index */
10212   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10213   char **azColl;   /* Array of collation sequence names for index */
10214 #ifdef SQLCIPHER_ENABLE_STAT3
10215   int nSample;             /* Number of elements in aSample[] */
10216   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10217   IndexSample *aSample;    /* Samples of the left-most key */
10218 #endif
10219 };
10220
10221 /*
10222 ** Each sample stored in the sqlcipher_stat3 table is represented in memory 
10223 ** using a structure of this type.  See documentation at the top of the
10224 ** analyze.c source file for additional information.
10225 */
10226 struct IndexSample {
10227   union {
10228     char *z;        /* Value if eType is SQLCIPHER_TEXT or SQLCIPHER_BLOB */
10229     double r;       /* Value if eType is SQLCIPHER_FLOAT */
10230     i64 i;          /* Value if eType is SQLCIPHER_INTEGER */
10231   } u;
10232   u8 eType;         /* SQLCIPHER_NULL, SQLCIPHER_INTEGER ... etc. */
10233   int nByte;        /* Size in byte of text or blob. */
10234   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10235   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10236   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10237 };
10238
10239 /*
10240 ** Each token coming out of the lexer is an instance of
10241 ** this structure.  Tokens are also used as part of an expression.
10242 **
10243 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10244 ** may contain random values.  Do not make any assumptions about Token.dyn
10245 ** and Token.n when Token.z==0.
10246 */
10247 struct Token {
10248   const char *z;     /* Text of the token.  Not NULL-terminated! */
10249   unsigned int n;    /* Number of characters in this token */
10250 };
10251
10252 /*
10253 ** An instance of this structure contains information needed to generate
10254 ** code for a SELECT that contains aggregate functions.
10255 **
10256 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10257 ** pointer to this structure.  The Expr.iColumn field is the index in
10258 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10259 ** code for that node.
10260 **
10261 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10262 ** original Select structure that describes the SELECT statement.  These
10263 ** fields do not need to be freed when deallocating the AggInfo structure.
10264 */
10265 struct AggInfo {
10266   u8 directMode;          /* Direct rendering mode means take data directly
10267                           ** from source tables rather than from accumulators */
10268   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10269                           ** than the source table */
10270   int sortingIdx;         /* Cursor number of the sorting index */
10271   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10272   ExprList *pGroupBy;     /* The group by clause */
10273   int nSortingColumn;     /* Number of columns in the sorting index */
10274   struct AggInfo_col {    /* For each column used in source tables */
10275     Table *pTab;             /* Source table */
10276     int iTable;              /* Cursor number of the source table */
10277     int iColumn;             /* Column number within the source table */
10278     int iSorterColumn;       /* Column number in the sorting index */
10279     int iMem;                /* Memory location that acts as accumulator */
10280     Expr *pExpr;             /* The original expression */
10281   } *aCol;
10282   int nColumn;            /* Number of used entries in aCol[] */
10283   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
10284   int nAccumulator;       /* Number of columns that show through to the output.
10285                           ** Additional columns are used only as parameters to
10286                           ** aggregate functions */
10287   struct AggInfo_func {   /* For each aggregate function */
10288     Expr *pExpr;             /* Expression encoding the function */
10289     FuncDef *pFunc;          /* The aggregate function implementation */
10290     int iMem;                /* Memory location that acts as accumulator */
10291     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10292   } *aFunc;
10293   int nFunc;              /* Number of entries in aFunc[] */
10294   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
10295 };
10296
10297 /*
10298 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10299 ** Usually it is 16-bits.  But if SQLCIPHER_MAX_VARIABLE_NUMBER is greater
10300 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10301 ** it uses less memory in the Expr object, which is a big memory user
10302 ** in systems with lots of prepared statements.  And few applications
10303 ** need more than about 10 or 20 variables.  But some extreme users want
10304 ** to have prepared statements with over 32767 variables, and for them
10305 ** the option is available (at compile-time).
10306 */
10307 #if SQLCIPHER_MAX_VARIABLE_NUMBER<=32767
10308 typedef i16 ynVar;
10309 #else
10310 typedef int ynVar;
10311 #endif
10312
10313 /*
10314 ** Each node of an expression in the parse tree is an instance
10315 ** of this structure.
10316 **
10317 ** Expr.op is the opcode. The integer parser token codes are reused
10318 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10319 ** code representing the ">=" operator. This same integer code is reused
10320 ** to represent the greater-than-or-equal-to operator in the expression
10321 ** tree.
10322 **
10323 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10324 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10325 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10326 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10327 ** then Expr.token contains the name of the function.
10328 **
10329 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10330 ** binary operator. Either or both may be NULL.
10331 **
10332 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10333 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10334 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10335 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10336 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10337 ** valid.
10338 **
10339 ** An expression of the form ID or ID.ID refers to a column in a table.
10340 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10341 ** the integer cursor number of a VDBE cursor pointing to that table and
10342 ** Expr.iColumn is the column number for the specific column.  If the
10343 ** expression is used as a result in an aggregate SELECT, then the
10344 ** value is also stored in the Expr.iAgg column in the aggregate so that
10345 ** it can be accessed after all aggregates are computed.
10346 **
10347 ** If the expression is an unbound variable marker (a question mark 
10348 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10349 ** number for that variable.
10350 **
10351 ** If the expression is a subquery then Expr.iColumn holds an integer
10352 ** register number containing the result of the subquery.  If the
10353 ** subquery gives a constant result, then iTable is -1.  If the subquery
10354 ** gives a different answer at different times during statement processing
10355 ** then iTable is the address of a subroutine that computes the subquery.
10356 **
10357 ** If the Expr is of type OP_Column, and the table it is selecting from
10358 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10359 ** corresponding table definition.
10360 **
10361 ** ALLOCATION NOTES:
10362 **
10363 ** Expr objects can use a lot of memory space in database schema.  To
10364 ** help reduce memory requirements, sometimes an Expr object will be
10365 ** truncated.  And to reduce the number of memory allocations, sometimes
10366 ** two or more Expr objects will be stored in a single memory allocation,
10367 ** together with Expr.zToken strings.
10368 **
10369 ** If the EP_Reduced and EP_TokenOnly flags are set when
10370 ** an Expr object is truncated.  When EP_Reduced is set, then all
10371 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10372 ** are contained within the same memory allocation.  Note, however, that
10373 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10374 ** allocated, regardless of whether or not EP_Reduced is set.
10375 */
10376 struct Expr {
10377   u8 op;                 /* Operation performed by this node */
10378   char affinity;         /* The affinity of the column or 0 if not a column */
10379   u16 flags;             /* Various flags.  EP_* See below */
10380   union {
10381     char *zToken;          /* Token value. Zero terminated and dequoted */
10382     int iValue;            /* Non-negative integer value if EP_IntValue */
10383   } u;
10384
10385   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10386   ** space is allocated for the fields below this point. An attempt to
10387   ** access them will result in a segfault or malfunction. 
10388   *********************************************************************/
10389
10390   Expr *pLeft;           /* Left subnode */
10391   Expr *pRight;          /* Right subnode */
10392   union {
10393     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10394     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10395   } x;
10396   CollSeq *pColl;        /* The collation type of the column or 0 */
10397
10398   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10399   ** space is allocated for the fields below this point. An attempt to
10400   ** access them will result in a segfault or malfunction.
10401   *********************************************************************/
10402
10403   int iTable;            /* TK_COLUMN: cursor number of table holding column
10404                          ** TK_REGISTER: register number
10405                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10406   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10407                          ** TK_VARIABLE: variable number (always >= 1). */
10408   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10409   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10410   u8 flags2;             /* Second set of flags.  EP2_... */
10411   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10412   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10413   Table *pTab;           /* Table for TK_COLUMN expressions. */
10414 #if SQLCIPHER_MAX_EXPR_DEPTH>0
10415   int nHeight;           /* Height of the tree headed by this node */
10416 #endif
10417 };
10418
10419 /*
10420 ** The following are the meanings of bits in the Expr.flags field.
10421 */
10422 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10423 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10424 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10425 #define EP_Error      0x0008  /* Expression contains one or more errors */
10426 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10427 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10428 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10429 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10430 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10431 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10432 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10433 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10434
10435 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10436 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10437 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10438
10439 /*
10440 ** The following are the meanings of bits in the Expr.flags2 field.
10441 */
10442 #define EP2_MallocedToken  0x0001  /* Need to sqlcipher3DbFree() Expr.zToken */
10443 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10444
10445 /*
10446 ** The pseudo-routine sqlcipher3ExprSetIrreducible sets the EP2_Irreducible
10447 ** flag on an expression structure.  This flag is used for VV&A only.  The
10448 ** routine is implemented as a macro that only works when in debugging mode,
10449 ** so as not to burden production code.
10450 */
10451 #ifdef SQLCIPHER_DEBUG
10452 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10453 #else
10454 # define ExprSetIrreducible(X)
10455 #endif
10456
10457 /*
10458 ** These macros can be used to test, set, or clear bits in the 
10459 ** Expr.flags field.
10460 */
10461 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10462 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10463 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10464 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10465
10466 /*
10467 ** Macros to determine the number of bytes required by a normal Expr 
10468 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10469 ** and an Expr struct with the EP_TokenOnly flag set.
10470 */
10471 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10472 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10473 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10474
10475 /*
10476 ** Flags passed to the sqlcipher3ExprDup() function. See the header comment 
10477 ** above sqlcipher3ExprDup() for details.
10478 */
10479 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10480
10481 /*
10482 ** A list of expressions.  Each expression may optionally have a
10483 ** name.  An expr/name combination can be used in several ways, such
10484 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10485 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10486 ** also be used as the argument to a function, in which case the a.zName
10487 ** field is not used.
10488 */
10489 struct ExprList {
10490   int nExpr;             /* Number of expressions on the list */
10491   int nAlloc;            /* Number of entries allocated below */
10492   int iECursor;          /* VDBE Cursor associated with this ExprList */
10493   struct ExprList_item {
10494     Expr *pExpr;           /* The list of expressions */
10495     char *zName;           /* Token associated with this expression */
10496     char *zSpan;           /* Original text of the expression */
10497     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10498     u8 done;               /* A flag to indicate when processing is finished */
10499     u16 iCol;              /* For ORDER BY, column number in result set */
10500     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10501   } *a;                  /* One entry for each expression */
10502 };
10503
10504 /*
10505 ** An instance of this structure is used by the parser to record both
10506 ** the parse tree for an expression and the span of input text for an
10507 ** expression.
10508 */
10509 struct ExprSpan {
10510   Expr *pExpr;          /* The expression parse tree */
10511   const char *zStart;   /* First character of input text */
10512   const char *zEnd;     /* One character past the end of input text */
10513 };
10514
10515 /*
10516 ** An instance of this structure can hold a simple list of identifiers,
10517 ** such as the list "a,b,c" in the following statements:
10518 **
10519 **      INSERT INTO t(a,b,c) VALUES ...;
10520 **      CREATE INDEX idx ON t(a,b,c);
10521 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10522 **
10523 ** The IdList.a.idx field is used when the IdList represents the list of
10524 ** column names after a table name in an INSERT statement.  In the statement
10525 **
10526 **     INSERT INTO t(a,b,c) ...
10527 **
10528 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10529 */
10530 struct IdList {
10531   struct IdList_item {
10532     char *zName;      /* Name of the identifier */
10533     int idx;          /* Index in some Table.aCol[] of a column named zName */
10534   } *a;
10535   int nId;         /* Number of identifiers on the list */
10536   int nAlloc;      /* Number of entries allocated for a[] below */
10537 };
10538
10539 /*
10540 ** The bitmask datatype defined below is used for various optimizations.
10541 **
10542 ** Changing this from a 64-bit to a 32-bit type limits the number of
10543 ** tables in a join to 32 instead of 64.  But it also reduces the size
10544 ** of the library by 738 bytes on ix86.
10545 */
10546 typedef u64 Bitmask;
10547
10548 /*
10549 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10550 */
10551 #define BMS  ((int)(sizeof(Bitmask)*8))
10552
10553 /*
10554 ** The following structure describes the FROM clause of a SELECT statement.
10555 ** Each table or subquery in the FROM clause is a separate element of
10556 ** the SrcList.a[] array.
10557 **
10558 ** With the addition of multiple database support, the following structure
10559 ** can also be used to describe a particular table such as the table that
10560 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10561 ** such a table must be a simple name: ID.  But in SQLite, the table can
10562 ** now be identified by a database name, a dot, then the table name: ID.ID.
10563 **
10564 ** The jointype starts out showing the join type between the current table
10565 ** and the next table on the list.  The parser builds the list this way.
10566 ** But sqlcipher3SrcListShiftJoinType() later shifts the jointypes so that each
10567 ** jointype expresses the join between the table and the previous table.
10568 **
10569 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10570 ** contains more than 63 columns and the 64-th or later column is used.
10571 */
10572 struct SrcList {
10573   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10574   i16 nAlloc;      /* Number of entries allocated in a[] below */
10575   struct SrcList_item {
10576     char *zDatabase;  /* Name of database holding this table */
10577     char *zName;      /* Name of the table */
10578     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10579     Table *pTab;      /* An SQL table corresponding to zName */
10580     Select *pSelect;  /* A SELECT statement used in place of a table name */
10581     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10582     int regReturn;    /* Register holding return address of addrFillSub */
10583     u8 jointype;      /* Type of join between this able and the previous */
10584     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10585     u8 isCorrelated;  /* True if sub-query is correlated */
10586 #ifndef SQLCIPHER_OMIT_EXPLAIN
10587     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10588 #endif
10589     int iCursor;      /* The VDBE cursor number used to access this table */
10590     Expr *pOn;        /* The ON clause of a join */
10591     IdList *pUsing;   /* The USING clause of a join */
10592     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10593     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10594     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10595   } a[1];             /* One entry for each identifier on the list */
10596 };
10597
10598 /*
10599 ** Permitted values of the SrcList.a.jointype field
10600 */
10601 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10602 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10603 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10604 #define JT_LEFT      0x0008    /* Left outer join */
10605 #define JT_RIGHT     0x0010    /* Right outer join */
10606 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10607 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10608
10609
10610 /*
10611 ** A WherePlan object holds information that describes a lookup
10612 ** strategy.
10613 **
10614 ** This object is intended to be opaque outside of the where.c module.
10615 ** It is included here only so that that compiler will know how big it
10616 ** is.  None of the fields in this object should be used outside of
10617 ** the where.c module.
10618 **
10619 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10620 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10621 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10622 ** case that more than one of these conditions is true.
10623 */
10624 struct WherePlan {
10625   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10626   u32 nEq;                       /* Number of == constraints */
10627   double nRow;                   /* Estimated number of rows (for EQP) */
10628   union {
10629     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10630     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10631     sqlcipher3_index_info *pVtabIdx;  /* Virtual table index to use */
10632   } u;
10633 };
10634
10635 /*
10636 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10637 ** structure contains a single instance of this structure.  This structure
10638 ** is intended to be private the the where.c module and should not be
10639 ** access or modified by other modules.
10640 **
10641 ** The pIdxInfo field is used to help pick the best index on a
10642 ** virtual table.  The pIdxInfo pointer contains indexing
10643 ** information for the i-th table in the FROM clause before reordering.
10644 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10645 ** All other information in the i-th WhereLevel object for the i-th table
10646 ** after FROM clause ordering.
10647 */
10648 struct WhereLevel {
10649   WherePlan plan;       /* query plan for this element of the FROM clause */
10650   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10651   int iTabCur;          /* The VDBE cursor used to access the table */
10652   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10653   int addrBrk;          /* Jump here to break out of the loop */
10654   int addrNxt;          /* Jump here to start the next IN combination */
10655   int addrCont;         /* Jump here to continue with the next loop cycle */
10656   int addrFirst;        /* First instruction of interior of the loop */
10657   u8 iFrom;             /* Which entry in the FROM clause */
10658   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10659   int p1, p2;           /* Operands of the opcode used to ends the loop */
10660   union {               /* Information that depends on plan.wsFlags */
10661     struct {
10662       int nIn;              /* Number of entries in aInLoop[] */
10663       struct InLoop {
10664         int iCur;              /* The VDBE cursor used by this IN operator */
10665         int addrInTop;         /* Top of the IN loop */
10666       } *aInLoop;           /* Information about each nested IN operator */
10667     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10668   } u;
10669
10670   /* The following field is really not part of the current level.  But
10671   ** we need a place to cache virtual table index information for each
10672   ** virtual table in the FROM clause and the WhereLevel structure is
10673   ** a convenient place since there is one WhereLevel for each FROM clause
10674   ** element.
10675   */
10676   sqlcipher3_index_info *pIdxInfo;  /* Index info for n-th source table */
10677 };
10678
10679 /*
10680 ** Flags appropriate for the wctrlFlags parameter of sqlcipher3WhereBegin()
10681 ** and the WhereInfo.wctrlFlags member.
10682 */
10683 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10684 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10685 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10686 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10687 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10688 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
10689 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
10690 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
10691 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
10692
10693 /*
10694 ** The WHERE clause processing routine has two halves.  The
10695 ** first part does the start of the WHERE loop and the second
10696 ** half does the tail of the WHERE loop.  An instance of
10697 ** this structure is returned by the first half and passed
10698 ** into the second half to give some continuity.
10699 */
10700 struct WhereInfo {
10701   Parse *pParse;       /* Parsing and code generating context */
10702   u16 wctrlFlags;      /* Flags originally passed to sqlcipher3WhereBegin() */
10703   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10704   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10705   u8 eDistinct;
10706   SrcList *pTabList;             /* List of tables in the join */
10707   int iTop;                      /* The very beginning of the WHERE loop */
10708   int iContinue;                 /* Jump here to continue with next record */
10709   int iBreak;                    /* Jump here to break out of the loop */
10710   int nLevel;                    /* Number of nested loop */
10711   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10712   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10713   double nRowOut;                /* Estimated number of output rows */
10714   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10715 };
10716
10717 #define WHERE_DISTINCT_UNIQUE 1
10718 #define WHERE_DISTINCT_ORDERED 2
10719
10720 /*
10721 ** A NameContext defines a context in which to resolve table and column
10722 ** names.  The context consists of a list of tables (the pSrcList) field and
10723 ** a list of named expression (pEList).  The named expression list may
10724 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10725 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10726 ** pEList corresponds to the result set of a SELECT and is NULL for
10727 ** other statements.
10728 **
10729 ** NameContexts can be nested.  When resolving names, the inner-most 
10730 ** context is searched first.  If no match is found, the next outer
10731 ** context is checked.  If there is still no match, the next context
10732 ** is checked.  This process continues until either a match is found
10733 ** or all contexts are check.  When a match is found, the nRef member of
10734 ** the context containing the match is incremented. 
10735 **
10736 ** Each subquery gets a new NameContext.  The pNext field points to the
10737 ** NameContext in the parent query.  Thus the process of scanning the
10738 ** NameContext list corresponds to searching through successively outer
10739 ** subqueries looking for a match.
10740 */
10741 struct NameContext {
10742   Parse *pParse;       /* The parser */
10743   SrcList *pSrcList;   /* One or more tables used to resolve names */
10744   ExprList *pEList;    /* Optional list of named expressions */
10745   int nRef;            /* Number of names resolved by this context */
10746   int nErr;            /* Number of errors encountered while resolving names */
10747   u8 allowAgg;         /* Aggregate functions allowed here */
10748   u8 hasAgg;           /* True if aggregates are seen */
10749   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10750   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10751   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10752   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10753 };
10754
10755 /*
10756 ** An instance of the following structure contains all information
10757 ** needed to generate code for a single SELECT statement.
10758 **
10759 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10760 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10761 ** limit and nOffset to the value of the offset (or 0 if there is not
10762 ** offset).  But later on, nLimit and nOffset become the memory locations
10763 ** in the VDBE that record the limit and offset counters.
10764 **
10765 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10766 ** These addresses must be stored so that we can go back and fill in
10767 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10768 ** the number of columns in P2 can be computed at the same time
10769 ** as the OP_OpenEphm instruction is coded because not
10770 ** enough information about the compound query is known at that point.
10771 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10772 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10773 ** sequences for the ORDER BY clause.
10774 */
10775 struct Select {
10776   ExprList *pEList;      /* The fields of the result */
10777   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10778   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10779   u16 selFlags;          /* Various SF_* values */
10780   SrcList *pSrc;         /* The FROM clause */
10781   Expr *pWhere;          /* The WHERE clause */
10782   ExprList *pGroupBy;    /* The GROUP BY clause */
10783   Expr *pHaving;         /* The HAVING clause */
10784   ExprList *pOrderBy;    /* The ORDER BY clause */
10785   Select *pPrior;        /* Prior select in a compound select statement */
10786   Select *pNext;         /* Next select to the left in a compound */
10787   Select *pRightmost;    /* Right-most select in a compound select statement */
10788   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10789   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10790   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10791   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10792   double nSelectRow;     /* Estimated number of result rows */
10793 };
10794
10795 /*
10796 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10797 ** "Select Flag".
10798 */
10799 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10800 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10801 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10802 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10803 #define SF_Expanded        0x0010  /* sqlcipher3SelectExpand() called on this */
10804 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10805 #define SF_UseSorter       0x0040  /* Sort using a sorter */
10806
10807
10808 /*
10809 ** The results of a select can be distributed in several ways.  The
10810 ** "SRT" prefix means "SELECT Result Type".
10811 */
10812 #define SRT_Union        1  /* Store result as keys in an index */
10813 #define SRT_Except       2  /* Remove result from a UNION index */
10814 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10815 #define SRT_Discard      4  /* Do not save the results anywhere */
10816
10817 /* The ORDER BY clause is ignored for all of the above */
10818 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10819
10820 #define SRT_Output       5  /* Output each row of result */
10821 #define SRT_Mem          6  /* Store result in a memory cell */
10822 #define SRT_Set          7  /* Store results as keys in an index */
10823 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10824 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10825 #define SRT_Coroutine   10  /* Generate a single row of result */
10826
10827 /*
10828 ** A structure used to customize the behavior of sqlcipher3Select(). See
10829 ** comments above sqlcipher3Select() for details.
10830 */
10831 typedef struct SelectDest SelectDest;
10832 struct SelectDest {
10833   u8 eDest;         /* How to dispose of the results */
10834   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10835   int iParm;        /* A parameter used by the eDest disposal method */
10836   int iMem;         /* Base register where results are written */
10837   int nMem;         /* Number of registers allocated */
10838 };
10839
10840 /*
10841 ** During code generation of statements that do inserts into AUTOINCREMENT 
10842 ** tables, the following information is attached to the Table.u.autoInc.p
10843 ** pointer of each autoincrement table to record some side information that
10844 ** the code generator needs.  We have to keep per-table autoincrement
10845 ** information in case inserts are down within triggers.  Triggers do not
10846 ** normally coordinate their activities, but we do need to coordinate the
10847 ** loading and saving of autoincrement information.
10848 */
10849 struct AutoincInfo {
10850   AutoincInfo *pNext;   /* Next info block in a list of them all */
10851   Table *pTab;          /* Table this info block refers to */
10852   int iDb;              /* Index in sqlcipher3.aDb[] of database holding pTab */
10853   int regCtr;           /* Memory register holding the rowid counter */
10854 };
10855
10856 /*
10857 ** Size of the column cache
10858 */
10859 #ifndef SQLCIPHER_N_COLCACHE
10860 # define SQLCIPHER_N_COLCACHE 10
10861 #endif
10862
10863 /*
10864 ** At least one instance of the following structure is created for each 
10865 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10866 ** statement. All such objects are stored in the linked list headed at
10867 ** Parse.pTriggerPrg and deleted once statement compilation has been
10868 ** completed.
10869 **
10870 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10871 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10872 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10873 ** The Parse.pTriggerPrg list never contains two entries with the same
10874 ** values for both pTrigger and orconf.
10875 **
10876 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10877 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10878 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10879 ** a mask of new.* columns used by the program.
10880 */
10881 struct TriggerPrg {
10882   Trigger *pTrigger;      /* Trigger this program was coded from */
10883   int orconf;             /* Default ON CONFLICT policy */
10884   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10885   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10886   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10887 };
10888
10889 /*
10890 ** The yDbMask datatype for the bitmask of all attached databases.
10891 */
10892 #if SQLCIPHER_MAX_ATTACHED>30
10893   typedef sqlcipher3_uint64 yDbMask;
10894 #else
10895   typedef unsigned int yDbMask;
10896 #endif
10897
10898 /*
10899 ** An SQL parser context.  A copy of this structure is passed through
10900 ** the parser and down into all the parser action routine in order to
10901 ** carry around information that is global to the entire parse.
10902 **
10903 ** The structure is divided into two parts.  When the parser and code
10904 ** generate call themselves recursively, the first part of the structure
10905 ** is constant but the second part is reset at the beginning and end of
10906 ** each recursion.
10907 **
10908 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10909 ** feature is enabled (if sqlcipher3Tsd()->useSharedData is true). They are
10910 ** used to store the set of table-locks required by the statement being
10911 ** compiled. Function sqlcipher3TableLock() is used to add entries to the
10912 ** list.
10913 */
10914 struct Parse {
10915   sqlcipher3 *db;         /* The main database structure */
10916   int rc;              /* Return code from execution */
10917   char *zErrMsg;       /* An error message */
10918   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10919   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10920   u8 nameClash;        /* A permanent table name clashes with temp table name */
10921   u8 checkSchema;      /* Causes schema cookie check after an error */
10922   u8 nested;           /* Number of nested calls to the parser/code generator */
10923   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10924   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10925   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10926   int aTempReg[8];     /* Holding area for temporary registers */
10927   int nRangeReg;       /* Size of the temporary register block */
10928   int iRangeReg;       /* First register in temporary register block */
10929   int nErr;            /* Number of errors seen */
10930   int nTab;            /* Number of previously allocated VDBE cursors */
10931   int nMem;            /* Number of memory cells used so far */
10932   int nSet;            /* Number of sets used so far */
10933   int ckBase;          /* Base register of data during check constraints */
10934   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10935   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10936   u8 nColCache;        /* Number of entries in the column cache */
10937   u8 iColCache;        /* Next entry of the cache to replace */
10938   struct yColCache {
10939     int iTable;           /* Table cursor number */
10940     int iColumn;          /* Table column number */
10941     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10942     int iLevel;           /* Nesting level */
10943     int iReg;             /* Reg with value of this column. 0 means none. */
10944     int lru;              /* Least recently used entry has the smallest value */
10945   } aColCache[SQLCIPHER_N_COLCACHE];  /* One for each column cache entry */
10946   yDbMask writeMask;   /* Start a write transaction on these databases */
10947   yDbMask cookieMask;  /* Bitmask of schema verified databases */
10948   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10949   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10950   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10951   int cookieValue[SQLCIPHER_MAX_ATTACHED+2];  /* Values of cookies to verify */
10952 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
10953   int nTableLock;        /* Number of locks in aTableLock */
10954   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10955 #endif
10956   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10957   int regRoot;         /* Register holding root page number for new objects */
10958   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10959   int nMaxArg;         /* Max args passed to user function by sub-program */
10960
10961   /* Information used while coding trigger programs. */
10962   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10963   Table *pTriggerTab;  /* Table triggers are being coded for */
10964   u32 oldmask;         /* Mask of old.* columns referenced */
10965   u32 newmask;         /* Mask of new.* columns referenced */
10966   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10967   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10968   u8 disableTriggers;  /* True to disable triggers */
10969   double nQueryLoop;   /* Estimated number of iterations of a query */
10970
10971   /* Above is constant between recursions.  Below is reset before and after
10972   ** each recursion */
10973
10974   int nVar;            /* Number of '?' variables seen in the SQL so far */
10975   int nzVar;           /* Number of available slots in azVar[] */
10976   char **azVar;        /* Pointers to names of parameters */
10977   Vdbe *pReprepare;    /* VM being reprepared (sqlcipher3Reprepare()) */
10978   int nAlias;          /* Number of aliased result set columns */
10979   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10980   int *aAlias;         /* Register used to hold aliased result */
10981   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10982   Token sNameToken;    /* Token with unqualified schema object name */
10983   Token sLastToken;    /* The last token parsed */
10984   const char *zTail;   /* All SQL text past the last semicolon parsed */
10985   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10986   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10987   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10988 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
10989   Token sArg;                /* Complete text of a module argument */
10990   u8 declareVtab;            /* True if inside sqlcipher3_declare_vtab() */
10991   int nVtabLock;             /* Number of virtual tables to lock */
10992   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10993 #endif
10994   int nHeight;            /* Expression tree height of current sub-select */
10995   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10996   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10997
10998 #ifndef SQLCIPHER_OMIT_EXPLAIN
10999   int iSelectId;
11000   int iNextSelectId;
11001 #endif
11002 };
11003
11004 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
11005   #define IN_DECLARE_VTAB 0
11006 #else
11007   #define IN_DECLARE_VTAB (pParse->declareVtab)
11008 #endif
11009
11010 /*
11011 ** An instance of the following structure can be declared on a stack and used
11012 ** to save the Parse.zAuthContext value so that it can be restored later.
11013 */
11014 struct AuthContext {
11015   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11016   Parse *pParse;              /* The Parse structure */
11017 };
11018
11019 /*
11020 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
11021 */
11022 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11023 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11024 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11025 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11026 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11027 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11028
11029 /*
11030  * Each trigger present in the database schema is stored as an instance of
11031  * struct Trigger. 
11032  *
11033  * Pointers to instances of struct Trigger are stored in two ways.
11034  * 1. In the "trigHash" hash table (part of the sqlcipher3* that represents the 
11035  *    database). This allows Trigger structures to be retrieved by name.
11036  * 2. All triggers associated with a single table form a linked list, using the
11037  *    pNext member of struct Trigger. A pointer to the first element of the
11038  *    linked list is stored as the "pTrigger" member of the associated
11039  *    struct Table.
11040  *
11041  * The "step_list" member points to the first element of a linked list
11042  * containing the SQL statements specified as the trigger program.
11043  */
11044 struct Trigger {
11045   char *zName;            /* The name of the trigger                        */
11046   char *table;            /* The table or view to which the trigger applies */
11047   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11048   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11049   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11050   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11051                              the <column-list> is stored here */
11052   Schema *pSchema;        /* Schema containing the trigger */
11053   Schema *pTabSchema;     /* Schema containing the table */
11054   TriggerStep *step_list; /* Link list of trigger program steps             */
11055   Trigger *pNext;         /* Next trigger associated with the table */
11056 };
11057
11058 /*
11059 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11060 ** determine which. 
11061 **
11062 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11063 ** In that cases, the constants below can be ORed together.
11064 */
11065 #define TRIGGER_BEFORE  1
11066 #define TRIGGER_AFTER   2
11067
11068 /*
11069  * An instance of struct TriggerStep is used to store a single SQL statement
11070  * that is a part of a trigger-program. 
11071  *
11072  * Instances of struct TriggerStep are stored in a singly linked list (linked
11073  * using the "pNext" member) referenced by the "step_list" member of the 
11074  * associated struct Trigger instance. The first element of the linked list is
11075  * the first step of the trigger-program.
11076  * 
11077  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11078  * "SELECT" statement. The meanings of the other members is determined by the 
11079  * value of "op" as follows:
11080  *
11081  * (op == TK_INSERT)
11082  * orconf    -> stores the ON CONFLICT algorithm
11083  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11084  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11085  * target    -> A token holding the quoted name of the table to insert into.
11086  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11087  *              this stores values to be inserted. Otherwise NULL.
11088  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11089  *              statement, then this stores the column-names to be
11090  *              inserted into.
11091  *
11092  * (op == TK_DELETE)
11093  * target    -> A token holding the quoted name of the table to delete from.
11094  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11095  *              Otherwise NULL.
11096  * 
11097  * (op == TK_UPDATE)
11098  * target    -> A token holding the quoted name of the table to update rows of.
11099  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11100  *              Otherwise NULL.
11101  * pExprList -> A list of the columns to update and the expressions to update
11102  *              them to. See sqlcipher3Update() documentation of "pChanges"
11103  *              argument.
11104  * 
11105  */
11106 struct TriggerStep {
11107   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11108   u8 orconf;           /* OE_Rollback etc. */
11109   Trigger *pTrig;      /* The trigger that this step is a part of */
11110   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11111   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11112   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11113   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11114   IdList *pIdList;     /* Column names for INSERT */
11115   TriggerStep *pNext;  /* Next in the link-list */
11116   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11117 };
11118
11119 /*
11120 ** The following structure contains information used by the sqlcipherFix...
11121 ** routines as they walk the parse tree to make database references
11122 ** explicit.  
11123 */
11124 typedef struct DbFixer DbFixer;
11125 struct DbFixer {
11126   Parse *pParse;      /* The parsing context.  Error messages written here */
11127   const char *zDb;    /* Make sure all objects are contained in this database */
11128   const char *zType;  /* Type of the container - used for error messages */
11129   const Token *pName; /* Name of the container - used for error messages */
11130 };
11131
11132 /*
11133 ** An objected used to accumulate the text of a string where we
11134 ** do not necessarily know how big the string will be in the end.
11135 */
11136 struct StrAccum {
11137   sqlcipher3 *db;         /* Optional database for lookaside.  Can be NULL */
11138   char *zBase;         /* A base allocation.  Not from malloc. */
11139   char *zText;         /* The string collected so far */
11140   int  nChar;          /* Length of the string so far */
11141   int  nAlloc;         /* Amount of space allocated in zText */
11142   int  mxAlloc;        /* Maximum allowed string length */
11143   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11144   u8   useMalloc;      /* 0: none,  1: sqlcipher3DbMalloc,  2: sqlcipher3_malloc */
11145   u8   tooBig;         /* Becomes true if string size exceeds limits */
11146 };
11147
11148 /*
11149 ** A pointer to this structure is used to communicate information
11150 ** from sqlcipher3Init and OP_ParseSchema into the sqlcipher3InitCallback.
11151 */
11152 typedef struct {
11153   sqlcipher3 *db;        /* The database being initialized */
11154   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11155   char **pzErrMsg;    /* Error message stored here */
11156   int rc;             /* Result code stored here */
11157 } InitData;
11158
11159 /*
11160 ** Structure containing global configuration data for the SQLite library.
11161 **
11162 ** This structure also contains some state information.
11163 */
11164 struct Sqlite3Config {
11165   int bMemstat;                     /* True to enable memory status */
11166   int bCoreMutex;                   /* True to enable core mutexing */
11167   int bFullMutex;                   /* True to enable full mutexing */
11168   int bOpenUri;                     /* True to interpret filenames as URIs */
11169   int mxStrlen;                     /* Maximum string length */
11170   int szLookaside;                  /* Default lookaside buffer size */
11171   int nLookaside;                   /* Default lookaside buffer count */
11172   sqlcipher3_mem_methods m;            /* Low-level memory allocation interface */
11173   sqlcipher3_mutex_methods mutex;      /* Low-level mutex interface */
11174   sqlcipher3_pcache_methods pcache;    /* Low-level page-cache interface */
11175   void *pHeap;                      /* Heap storage space */
11176   int nHeap;                        /* Size of pHeap[] */
11177   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11178   void *pScratch;                   /* Scratch memory */
11179   int szScratch;                    /* Size of each scratch buffer */
11180   int nScratch;                     /* Number of scratch buffers */
11181   void *pPage;                      /* Page cache memory */
11182   int szPage;                       /* Size of each page in pPage[] */
11183   int nPage;                        /* Number of pages in pPage[] */
11184   int mxParserStack;                /* maximum depth of the parser stack */
11185   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11186   /* The above might be initialized to non-zero.  The following need to always
11187   ** initially be zero, however. */
11188   int isInit;                       /* True after initialization has finished */
11189   int inProgress;                   /* True while initialization in progress */
11190   int isMutexInit;                  /* True after mutexes are initialized */
11191   int isMallocInit;                 /* True after malloc is initialized */
11192   int isPCacheInit;                 /* True after malloc is initialized */
11193   sqlcipher3_mutex *pInitMutex;        /* Mutex used by sqlcipher3_initialize() */
11194   int nRefInitMutex;                /* Number of users of pInitMutex */
11195   void (*xLog)(void*,int,const char*); /* Function for logging */
11196   void *pLogArg;                       /* First argument to xLog() */
11197   int bLocaltimeFault;              /* True to fail localtime() calls */
11198 };
11199
11200 /*
11201 ** Context pointer passed down through the tree-walk.
11202 */
11203 struct Walker {
11204   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11205   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11206   Parse *pParse;                            /* Parser context.  */
11207   union {                                   /* Extra data for callback */
11208     NameContext *pNC;                          /* Naming context */
11209     int i;                                     /* Integer value */
11210   } u;
11211 };
11212
11213 /* Forward declarations */
11214 SQLCIPHER_PRIVATE int sqlcipher3WalkExpr(Walker*, Expr*);
11215 SQLCIPHER_PRIVATE int sqlcipher3WalkExprList(Walker*, ExprList*);
11216 SQLCIPHER_PRIVATE int sqlcipher3WalkSelect(Walker*, Select*);
11217 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectExpr(Walker*, Select*);
11218 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectFrom(Walker*, Select*);
11219
11220 /*
11221 ** Return code from the parse-tree walking primitives and their
11222 ** callbacks.
11223 */
11224 #define WRC_Continue    0   /* Continue down into children */
11225 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11226 #define WRC_Abort       2   /* Abandon the tree walk */
11227
11228 /*
11229 ** Assuming zIn points to the first byte of a UTF-8 character,
11230 ** advance zIn to point to the first byte of the next UTF-8 character.
11231 */
11232 #define SQLCIPHER_SKIP_UTF8(zIn) {                        \
11233   if( (*(zIn++))>=0xc0 ){                              \
11234     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11235   }                                                    \
11236 }
11237
11238 /*
11239 ** The SQLCIPHER_*_BKPT macros are substitutes for the error codes with
11240 ** the same name but without the _BKPT suffix.  These macros invoke
11241 ** routines that report the line-number on which the error originated
11242 ** using sqlcipher3_log().  The routines also provide a convenient place
11243 ** to set a debugger breakpoint.
11244 */
11245 SQLCIPHER_PRIVATE int sqlcipher3CorruptError(int);
11246 SQLCIPHER_PRIVATE int sqlcipher3MisuseError(int);
11247 SQLCIPHER_PRIVATE int sqlcipher3CantopenError(int);
11248 #define SQLCIPHER_CORRUPT_BKPT sqlcipher3CorruptError(__LINE__)
11249 #define SQLCIPHER_MISUSE_BKPT sqlcipher3MisuseError(__LINE__)
11250 #define SQLCIPHER_CANTOPEN_BKPT sqlcipher3CantopenError(__LINE__)
11251
11252
11253 /*
11254 ** FTS4 is really an extension for FTS3.  It is enabled using the
11255 ** SQLCIPHER_ENABLE_FTS3 macro.  But to avoid confusion we also all
11256 ** the SQLCIPHER_ENABLE_FTS4 macro to serve as an alisse for SQLCIPHER_ENABLE_FTS3.
11257 */
11258 #if defined(SQLCIPHER_ENABLE_FTS4) && !defined(SQLCIPHER_ENABLE_FTS3)
11259 # define SQLCIPHER_ENABLE_FTS3
11260 #endif
11261
11262 /*
11263 ** The ctype.h header is needed for non-ASCII systems.  It is also
11264 ** needed by FTS3 when FTS3 is included in the amalgamation.
11265 */
11266 #if !defined(SQLCIPHER_ASCII) || \
11267     (defined(SQLCIPHER_ENABLE_FTS3) && defined(SQLCIPHER_AMALGAMATION))
11268 # include <ctype.h>
11269 #endif
11270
11271 /*
11272 ** The following macros mimic the standard library functions toupper(),
11273 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11274 ** sqlcipher versions only work for ASCII characters, regardless of locale.
11275 */
11276 #ifdef SQLCIPHER_ASCII
11277 # define sqlcipher3Toupper(x)  ((x)&~(sqlcipher3CtypeMap[(unsigned char)(x)]&0x20))
11278 # define sqlcipher3Isspace(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x01)
11279 # define sqlcipher3Isalnum(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x06)
11280 # define sqlcipher3Isalpha(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x02)
11281 # define sqlcipher3Isdigit(x)   (sqlcipher3CtypeMap[(unsigned char)(x)]&0x04)
11282 # define sqlcipher3Isxdigit(x)  (sqlcipher3CtypeMap[(unsigned char)(x)]&0x08)
11283 # define sqlcipher3Tolower(x)   (sqlcipher3UpperToLower[(unsigned char)(x)])
11284 #else
11285 # define sqlcipher3Toupper(x)   toupper((unsigned char)(x))
11286 # define sqlcipher3Isspace(x)   isspace((unsigned char)(x))
11287 # define sqlcipher3Isalnum(x)   isalnum((unsigned char)(x))
11288 # define sqlcipher3Isalpha(x)   isalpha((unsigned char)(x))
11289 # define sqlcipher3Isdigit(x)   isdigit((unsigned char)(x))
11290 # define sqlcipher3Isxdigit(x)  isxdigit((unsigned char)(x))
11291 # define sqlcipher3Tolower(x)   tolower((unsigned char)(x))
11292 #endif
11293
11294 /*
11295 ** Internal function prototypes
11296 */
11297 SQLCIPHER_PRIVATE int sqlcipher3StrICmp(const char *, const char *);
11298 SQLCIPHER_PRIVATE int sqlcipher3Strlen30(const char*);
11299 #define sqlcipher3StrNICmp sqlcipher3_strnicmp
11300
11301 SQLCIPHER_PRIVATE int sqlcipher3MallocInit(void);
11302 SQLCIPHER_PRIVATE void sqlcipher3MallocEnd(void);
11303 SQLCIPHER_PRIVATE void *sqlcipher3Malloc(int);
11304 SQLCIPHER_PRIVATE void *sqlcipher3MallocZero(int);
11305 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocZero(sqlcipher3*, int);
11306 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocRaw(sqlcipher3*, int);
11307 SQLCIPHER_PRIVATE char *sqlcipher3DbStrDup(sqlcipher3*,const char*);
11308 SQLCIPHER_PRIVATE char *sqlcipher3DbStrNDup(sqlcipher3*,const char*, int);
11309 SQLCIPHER_PRIVATE void *sqlcipher3Realloc(void*, int);
11310 SQLCIPHER_PRIVATE void *sqlcipher3DbReallocOrFree(sqlcipher3 *, void *, int);
11311 SQLCIPHER_PRIVATE void *sqlcipher3DbRealloc(sqlcipher3 *, void *, int);
11312 SQLCIPHER_PRIVATE void sqlcipher3DbFree(sqlcipher3*, void*);
11313 SQLCIPHER_PRIVATE int sqlcipher3MallocSize(void*);
11314 SQLCIPHER_PRIVATE int sqlcipher3DbMallocSize(sqlcipher3*, void*);
11315 SQLCIPHER_PRIVATE void *sqlcipher3ScratchMalloc(int);
11316 SQLCIPHER_PRIVATE void sqlcipher3ScratchFree(void*);
11317 SQLCIPHER_PRIVATE void *sqlcipher3PageMalloc(int);
11318 SQLCIPHER_PRIVATE void sqlcipher3PageFree(void*);
11319 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void);
11320 SQLCIPHER_PRIVATE void sqlcipher3BenignMallocHooks(void (*)(void), void (*)(void));
11321 SQLCIPHER_PRIVATE int sqlcipher3HeapNearlyFull(void);
11322
11323 /*
11324 ** On systems with ample stack space and that support alloca(), make
11325 ** use of alloca() to obtain space for large automatic objects.  By default,
11326 ** obtain space from malloc().
11327 **
11328 ** The alloca() routine never returns NULL.  This will cause code paths
11329 ** that deal with sqlcipher3StackAlloc() failures to be unreachable.
11330 */
11331 #ifdef SQLCIPHER_USE_ALLOCA
11332 # define sqlcipher3StackAllocRaw(D,N)   alloca(N)
11333 # define sqlcipher3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11334 # define sqlcipher3StackFree(D,P)       
11335 #else
11336 # define sqlcipher3StackAllocRaw(D,N)   sqlcipher3DbMallocRaw(D,N)
11337 # define sqlcipher3StackAllocZero(D,N)  sqlcipher3DbMallocZero(D,N)
11338 # define sqlcipher3StackFree(D,P)       sqlcipher3DbFree(D,P)
11339 #endif
11340
11341 #ifdef SQLCIPHER_ENABLE_MEMSYS3
11342 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys3(void);
11343 #endif
11344 #ifdef SQLCIPHER_ENABLE_MEMSYS5
11345 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys5(void);
11346 #endif
11347
11348
11349 #ifndef SQLCIPHER_MUTEX_OMIT
11350 SQLCIPHER_PRIVATE   sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void);
11351 SQLCIPHER_PRIVATE   sqlcipher3_mutex_methods const *sqlcipher3NoopMutex(void);
11352 SQLCIPHER_PRIVATE   sqlcipher3_mutex *sqlcipher3MutexAlloc(int);
11353 SQLCIPHER_PRIVATE   int sqlcipher3MutexInit(void);
11354 SQLCIPHER_PRIVATE   int sqlcipher3MutexEnd(void);
11355 #endif
11356
11357 SQLCIPHER_PRIVATE int sqlcipher3StatusValue(int);
11358 SQLCIPHER_PRIVATE void sqlcipher3StatusAdd(int, int);
11359 SQLCIPHER_PRIVATE void sqlcipher3StatusSet(int, int);
11360
11361 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
11362 SQLCIPHER_PRIVATE   int sqlcipher3IsNaN(double);
11363 #else
11364 # define sqlcipher3IsNaN(X)  0
11365 #endif
11366
11367 SQLCIPHER_PRIVATE void sqlcipher3VXPrintf(StrAccum*, int, const char*, va_list);
11368 #ifndef SQLCIPHER_OMIT_TRACE
11369 SQLCIPHER_PRIVATE void sqlcipher3XPrintf(StrAccum*, const char*, ...);
11370 #endif
11371 SQLCIPHER_PRIVATE char *sqlcipher3MPrintf(sqlcipher3*,const char*, ...);
11372 SQLCIPHER_PRIVATE char *sqlcipher3VMPrintf(sqlcipher3*,const char*, va_list);
11373 SQLCIPHER_PRIVATE char *sqlcipher3MAppendf(sqlcipher3*,char*,const char*,...);
11374 #if defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG)
11375 SQLCIPHER_PRIVATE   void sqlcipher3DebugPrintf(const char*, ...);
11376 #endif
11377 #if defined(SQLCIPHER_TEST)
11378 SQLCIPHER_PRIVATE   void *sqlcipher3TestTextToPtr(const char*);
11379 #endif
11380 SQLCIPHER_PRIVATE void sqlcipher3SetString(char **, sqlcipher3*, const char*, ...);
11381 SQLCIPHER_PRIVATE void sqlcipher3ErrorMsg(Parse*, const char*, ...);
11382 SQLCIPHER_PRIVATE int sqlcipher3Dequote(char*);
11383 SQLCIPHER_PRIVATE int sqlcipher3KeywordCode(const unsigned char*, int);
11384 SQLCIPHER_PRIVATE int sqlcipher3RunParser(Parse*, const char*, char **);
11385 SQLCIPHER_PRIVATE void sqlcipher3FinishCoding(Parse*);
11386 SQLCIPHER_PRIVATE int sqlcipher3GetTempReg(Parse*);
11387 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempReg(Parse*,int);
11388 SQLCIPHER_PRIVATE int sqlcipher3GetTempRange(Parse*,int);
11389 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempRange(Parse*,int,int);
11390 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAlloc(sqlcipher3*,int,const Token*,int);
11391 SQLCIPHER_PRIVATE Expr *sqlcipher3Expr(sqlcipher3*,int,const char*);
11392 SQLCIPHER_PRIVATE void sqlcipher3ExprAttachSubtrees(sqlcipher3*,Expr*,Expr*,Expr*);
11393 SQLCIPHER_PRIVATE Expr *sqlcipher3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11394 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAnd(sqlcipher3*,Expr*, Expr*);
11395 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprFunction(Parse*,ExprList*, Token*);
11396 SQLCIPHER_PRIVATE void sqlcipher3ExprAssignVarNumber(Parse*, Expr*);
11397 SQLCIPHER_PRIVATE void sqlcipher3ExprDelete(sqlcipher3*, Expr*);
11398 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListAppend(Parse*,ExprList*,Expr*);
11399 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetName(Parse*,ExprList*,Token*,int);
11400 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11401 SQLCIPHER_PRIVATE void sqlcipher3ExprListDelete(sqlcipher3*, ExprList*);
11402 SQLCIPHER_PRIVATE int sqlcipher3Init(sqlcipher3*, char**);
11403 SQLCIPHER_PRIVATE int sqlcipher3InitCallback(void*, int, char**, char**);
11404 SQLCIPHER_PRIVATE void sqlcipher3Pragma(Parse*,Token*,Token*,Token*,int);
11405 SQLCIPHER_PRIVATE void sqlcipher3ResetInternalSchema(sqlcipher3*, int);
11406 SQLCIPHER_PRIVATE void sqlcipher3BeginParse(Parse*,int);
11407 SQLCIPHER_PRIVATE void sqlcipher3CommitInternalChanges(sqlcipher3*);
11408 SQLCIPHER_PRIVATE Table *sqlcipher3ResultSetOfSelect(Parse*,Select*);
11409 SQLCIPHER_PRIVATE void sqlcipher3OpenMasterTable(Parse *, int);
11410 SQLCIPHER_PRIVATE void sqlcipher3StartTable(Parse*,Token*,Token*,int,int,int,int);
11411 SQLCIPHER_PRIVATE void sqlcipher3AddColumn(Parse*,Token*);
11412 SQLCIPHER_PRIVATE void sqlcipher3AddNotNull(Parse*, int);
11413 SQLCIPHER_PRIVATE void sqlcipher3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11414 SQLCIPHER_PRIVATE void sqlcipher3AddCheckConstraint(Parse*, Expr*);
11415 SQLCIPHER_PRIVATE void sqlcipher3AddColumnType(Parse*,Token*);
11416 SQLCIPHER_PRIVATE void sqlcipher3AddDefaultValue(Parse*,ExprSpan*);
11417 SQLCIPHER_PRIVATE void sqlcipher3AddCollateType(Parse*, Token*);
11418 SQLCIPHER_PRIVATE void sqlcipher3EndTable(Parse*,Token*,Token*,Select*);
11419 SQLCIPHER_PRIVATE int sqlcipher3ParseUri(const char*,const char*,unsigned int*,
11420                     sqlcipher3_vfs**,char**,char **);
11421
11422 SQLCIPHER_PRIVATE Bitvec *sqlcipher3BitvecCreate(u32);
11423 SQLCIPHER_PRIVATE int sqlcipher3BitvecTest(Bitvec*, u32);
11424 SQLCIPHER_PRIVATE int sqlcipher3BitvecSet(Bitvec*, u32);
11425 SQLCIPHER_PRIVATE void sqlcipher3BitvecClear(Bitvec*, u32, void*);
11426 SQLCIPHER_PRIVATE void sqlcipher3BitvecDestroy(Bitvec*);
11427 SQLCIPHER_PRIVATE u32 sqlcipher3BitvecSize(Bitvec*);
11428 SQLCIPHER_PRIVATE int sqlcipher3BitvecBuiltinTest(int,int*);
11429
11430 SQLCIPHER_PRIVATE RowSet *sqlcipher3RowSetInit(sqlcipher3*, void*, unsigned int);
11431 SQLCIPHER_PRIVATE void sqlcipher3RowSetClear(RowSet*);
11432 SQLCIPHER_PRIVATE void sqlcipher3RowSetInsert(RowSet*, i64);
11433 SQLCIPHER_PRIVATE int sqlcipher3RowSetTest(RowSet*, u8 iBatch, i64);
11434 SQLCIPHER_PRIVATE int sqlcipher3RowSetNext(RowSet*, i64*);
11435
11436 SQLCIPHER_PRIVATE void sqlcipher3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11437
11438 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE)
11439 SQLCIPHER_PRIVATE   int sqlcipher3ViewGetColumnNames(Parse*,Table*);
11440 #else
11441 # define sqlcipher3ViewGetColumnNames(A,B) 0
11442 #endif
11443
11444 SQLCIPHER_PRIVATE void sqlcipher3DropTable(Parse*, SrcList*, int, int);
11445 SQLCIPHER_PRIVATE void sqlcipher3CodeDropTable(Parse*, Table*, int, int);
11446 SQLCIPHER_PRIVATE void sqlcipher3DeleteTable(sqlcipher3*, Table*);
11447 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
11448 SQLCIPHER_PRIVATE   void sqlcipher3AutoincrementBegin(Parse *pParse);
11449 SQLCIPHER_PRIVATE   void sqlcipher3AutoincrementEnd(Parse *pParse);
11450 #else
11451 # define sqlcipher3AutoincrementBegin(X)
11452 # define sqlcipher3AutoincrementEnd(X)
11453 #endif
11454 SQLCIPHER_PRIVATE void sqlcipher3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11455 SQLCIPHER_PRIVATE void *sqlcipher3ArrayAllocate(sqlcipher3*,void*,int,int,int*,int*,int*);
11456 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListAppend(sqlcipher3*, IdList*, Token*);
11457 SQLCIPHER_PRIVATE int sqlcipher3IdListIndex(IdList*,const char*);
11458 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListEnlarge(sqlcipher3*, SrcList*, int, int);
11459 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppend(sqlcipher3*, SrcList*, Token*, Token*);
11460 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11461                                       Token*, Select*, Expr*, IdList*);
11462 SQLCIPHER_PRIVATE void sqlcipher3SrcListIndexedBy(Parse *, SrcList *, Token *);
11463 SQLCIPHER_PRIVATE int sqlcipher3IndexedByLookup(Parse *, struct SrcList_item *);
11464 SQLCIPHER_PRIVATE void sqlcipher3SrcListShiftJoinType(SrcList*);
11465 SQLCIPHER_PRIVATE void sqlcipher3SrcListAssignCursors(Parse*, SrcList*);
11466 SQLCIPHER_PRIVATE void sqlcipher3IdListDelete(sqlcipher3*, IdList*);
11467 SQLCIPHER_PRIVATE void sqlcipher3SrcListDelete(sqlcipher3*, SrcList*);
11468 SQLCIPHER_PRIVATE Index *sqlcipher3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11469                         Token*, int, int);
11470 SQLCIPHER_PRIVATE void sqlcipher3DropIndex(Parse*, SrcList*, int);
11471 SQLCIPHER_PRIVATE int sqlcipher3Select(Parse*, Select*, SelectDest*);
11472 SQLCIPHER_PRIVATE Select *sqlcipher3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11473                          Expr*,ExprList*,int,Expr*,Expr*);
11474 SQLCIPHER_PRIVATE void sqlcipher3SelectDelete(sqlcipher3*, Select*);
11475 SQLCIPHER_PRIVATE Table *sqlcipher3SrcListLookup(Parse*, SrcList*);
11476 SQLCIPHER_PRIVATE int sqlcipher3IsReadOnly(Parse*, Table*, int);
11477 SQLCIPHER_PRIVATE void sqlcipher3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11478 #if defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY)
11479 SQLCIPHER_PRIVATE Expr *sqlcipher3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11480 #endif
11481 SQLCIPHER_PRIVATE void sqlcipher3DeleteFrom(Parse*, SrcList*, Expr*);
11482 SQLCIPHER_PRIVATE void sqlcipher3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11483 SQLCIPHER_PRIVATE WhereInfo *sqlcipher3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11484 SQLCIPHER_PRIVATE void sqlcipher3WhereEnd(WhereInfo*);
11485 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11486 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11487 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeMove(Parse*, int, int, int);
11488 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeCopy(Parse*, int, int, int);
11489 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheStore(Parse*, int, int, int);
11490 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePush(Parse*);
11491 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePop(Parse*, int);
11492 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheRemove(Parse*, int, int);
11493 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheClear(Parse*);
11494 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheAffinityChange(Parse*, int, int);
11495 SQLCIPHER_PRIVATE int sqlcipher3ExprCode(Parse*, Expr*, int);
11496 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTemp(Parse*, Expr*, int*);
11497 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTarget(Parse*, Expr*, int);
11498 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeAndCache(Parse*, Expr*, int);
11499 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeConstants(Parse*, Expr*);
11500 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeExprList(Parse*, ExprList*, int, int);
11501 SQLCIPHER_PRIVATE void sqlcipher3ExprIfTrue(Parse*, Expr*, int, int);
11502 SQLCIPHER_PRIVATE void sqlcipher3ExprIfFalse(Parse*, Expr*, int, int);
11503 SQLCIPHER_PRIVATE Table *sqlcipher3FindTable(sqlcipher3*,const char*, const char*);
11504 SQLCIPHER_PRIVATE Table *sqlcipher3LocateTable(Parse*,int isView,const char*, const char*);
11505 SQLCIPHER_PRIVATE Index *sqlcipher3FindIndex(sqlcipher3*,const char*, const char*);
11506 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteTable(sqlcipher3*,int,const char*);
11507 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteIndex(sqlcipher3*,int,const char*);
11508 SQLCIPHER_PRIVATE void sqlcipher3Vacuum(Parse*);
11509 SQLCIPHER_PRIVATE int sqlcipher3RunVacuum(char**, sqlcipher3*);
11510 SQLCIPHER_PRIVATE char *sqlcipher3NameFromToken(sqlcipher3*, Token*);
11511 SQLCIPHER_PRIVATE int sqlcipher3ExprCompare(Expr*, Expr*);
11512 SQLCIPHER_PRIVATE int sqlcipher3ExprListCompare(ExprList*, ExprList*);
11513 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggregates(NameContext*, Expr*);
11514 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggList(NameContext*,ExprList*);
11515 SQLCIPHER_PRIVATE Vdbe *sqlcipher3GetVdbe(Parse*);
11516 SQLCIPHER_PRIVATE void sqlcipher3PrngSaveState(void);
11517 SQLCIPHER_PRIVATE void sqlcipher3PrngRestoreState(void);
11518 SQLCIPHER_PRIVATE void sqlcipher3PrngResetState(void);
11519 SQLCIPHER_PRIVATE void sqlcipher3RollbackAll(sqlcipher3*);
11520 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifySchema(Parse*, int);
11521 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifyNamedSchema(Parse*, const char *zDb);
11522 SQLCIPHER_PRIVATE void sqlcipher3BeginTransaction(Parse*, int);
11523 SQLCIPHER_PRIVATE void sqlcipher3CommitTransaction(Parse*);
11524 SQLCIPHER_PRIVATE void sqlcipher3RollbackTransaction(Parse*);
11525 SQLCIPHER_PRIVATE void sqlcipher3Savepoint(Parse*, int, Token*);
11526 SQLCIPHER_PRIVATE void sqlcipher3CloseSavepoints(sqlcipher3 *);
11527 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstant(Expr*);
11528 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantNotJoin(Expr*);
11529 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantOrFunction(Expr*);
11530 SQLCIPHER_PRIVATE int sqlcipher3ExprIsInteger(Expr*, int*);
11531 SQLCIPHER_PRIVATE int sqlcipher3ExprCanBeNull(const Expr*);
11532 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11533 SQLCIPHER_PRIVATE int sqlcipher3ExprNeedsNoAffinityChange(const Expr*, char);
11534 SQLCIPHER_PRIVATE int sqlcipher3IsRowid(const char*);
11535 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11536 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11537 SQLCIPHER_PRIVATE int sqlcipher3GenerateIndexKey(Parse*, Index*, int, int, int);
11538 SQLCIPHER_PRIVATE void sqlcipher3GenerateConstraintChecks(Parse*,Table*,int,int,
11539                                      int*,int,int,int,int,int*);
11540 SQLCIPHER_PRIVATE void sqlcipher3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11541 SQLCIPHER_PRIVATE int sqlcipher3OpenTableAndIndices(Parse*, Table*, int, int);
11542 SQLCIPHER_PRIVATE void sqlcipher3BeginWriteOperation(Parse*, int, int);
11543 SQLCIPHER_PRIVATE void sqlcipher3MultiWrite(Parse*);
11544 SQLCIPHER_PRIVATE void sqlcipher3MayAbort(Parse*);
11545 SQLCIPHER_PRIVATE void sqlcipher3HaltConstraint(Parse*, int, char*, int);
11546 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprDup(sqlcipher3*,Expr*,int);
11547 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListDup(sqlcipher3*,ExprList*,int);
11548 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListDup(sqlcipher3*,SrcList*,int);
11549 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListDup(sqlcipher3*,IdList*);
11550 SQLCIPHER_PRIVATE Select *sqlcipher3SelectDup(sqlcipher3*,Select*,int);
11551 SQLCIPHER_PRIVATE void sqlcipher3FuncDefInsert(FuncDefHash*, FuncDef*);
11552 SQLCIPHER_PRIVATE FuncDef *sqlcipher3FindFunction(sqlcipher3*,const char*,int,int,u8,int);
11553 SQLCIPHER_PRIVATE void sqlcipher3RegisterBuiltinFunctions(sqlcipher3*);
11554 SQLCIPHER_PRIVATE void sqlcipher3RegisterDateTimeFunctions(void);
11555 SQLCIPHER_PRIVATE void sqlcipher3RegisterGlobalFunctions(void);
11556 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckOk(sqlcipher3*);
11557 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckSickOrOk(sqlcipher3*);
11558 SQLCIPHER_PRIVATE void sqlcipher3ChangeCookie(Parse*, int);
11559
11560 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
11561 SQLCIPHER_PRIVATE void sqlcipher3MaterializeView(Parse*, Table*, Expr*, int);
11562 #endif
11563
11564 #ifndef SQLCIPHER_OMIT_TRIGGER
11565 SQLCIPHER_PRIVATE   void sqlcipher3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11566                            Expr*,int, int);
11567 SQLCIPHER_PRIVATE   void sqlcipher3FinishTrigger(Parse*, TriggerStep*, Token*);
11568 SQLCIPHER_PRIVATE   void sqlcipher3DropTrigger(Parse*, SrcList*, int);
11569 SQLCIPHER_PRIVATE   void sqlcipher3DropTriggerPtr(Parse*, Trigger*);
11570 SQLCIPHER_PRIVATE   Trigger *sqlcipher3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11571 SQLCIPHER_PRIVATE   Trigger *sqlcipher3TriggerList(Parse *, Table *);
11572 SQLCIPHER_PRIVATE   void sqlcipher3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11573                             int, int, int);
11574 SQLCIPHER_PRIVATE   void sqlcipher3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11575   void sqlcipherViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11576 SQLCIPHER_PRIVATE   void sqlcipher3DeleteTriggerStep(sqlcipher3*, TriggerStep*);
11577 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerSelectStep(sqlcipher3*,Select*);
11578 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerInsertStep(sqlcipher3*,Token*, IdList*,
11579                                         ExprList*,Select*,u8);
11580 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerUpdateStep(sqlcipher3*,Token*,ExprList*, Expr*, u8);
11581 SQLCIPHER_PRIVATE   TriggerStep *sqlcipher3TriggerDeleteStep(sqlcipher3*,Token*, Expr*);
11582 SQLCIPHER_PRIVATE   void sqlcipher3DeleteTrigger(sqlcipher3*, Trigger*);
11583 SQLCIPHER_PRIVATE   void sqlcipher3UnlinkAndDeleteTrigger(sqlcipher3*,int,const char*);
11584 SQLCIPHER_PRIVATE   u32 sqlcipher3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11585 # define sqlcipher3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11586 #else
11587 # define sqlcipher3TriggersExist(B,C,D,E,F) 0
11588 # define sqlcipher3DeleteTrigger(A,B)
11589 # define sqlcipher3DropTriggerPtr(A,B)
11590 # define sqlcipher3UnlinkAndDeleteTrigger(A,B,C)
11591 # define sqlcipher3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11592 # define sqlcipher3CodeRowTriggerDirect(A,B,C,D,E,F)
11593 # define sqlcipher3TriggerList(X, Y) 0
11594 # define sqlcipher3ParseToplevel(p) p
11595 # define sqlcipher3TriggerColmask(A,B,C,D,E,F,G) 0
11596 #endif
11597
11598 SQLCIPHER_PRIVATE int sqlcipher3JoinType(Parse*, Token*, Token*, Token*);
11599 SQLCIPHER_PRIVATE void sqlcipher3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11600 SQLCIPHER_PRIVATE void sqlcipher3DeferForeignKey(Parse*, int);
11601 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
11602 SQLCIPHER_PRIVATE   void sqlcipher3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11603 SQLCIPHER_PRIVATE   int sqlcipher3AuthCheck(Parse*,int, const char*, const char*, const char*);
11604 SQLCIPHER_PRIVATE   void sqlcipher3AuthContextPush(Parse*, AuthContext*, const char*);
11605 SQLCIPHER_PRIVATE   void sqlcipher3AuthContextPop(AuthContext*);
11606 SQLCIPHER_PRIVATE   int sqlcipher3AuthReadCol(Parse*, const char *, const char *, int);
11607 #else
11608 # define sqlcipher3AuthRead(a,b,c,d)
11609 # define sqlcipher3AuthCheck(a,b,c,d,e)    SQLCIPHER_OK
11610 # define sqlcipher3AuthContextPush(a,b,c)
11611 # define sqlcipher3AuthContextPop(a)  ((void)(a))
11612 #endif
11613 SQLCIPHER_PRIVATE void sqlcipher3Attach(Parse*, Expr*, Expr*, Expr*);
11614 SQLCIPHER_PRIVATE void sqlcipher3Detach(Parse*, Expr*);
11615 SQLCIPHER_PRIVATE int sqlcipher3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11616 SQLCIPHER_PRIVATE int sqlcipher3FixSrcList(DbFixer*, SrcList*);
11617 SQLCIPHER_PRIVATE int sqlcipher3FixSelect(DbFixer*, Select*);
11618 SQLCIPHER_PRIVATE int sqlcipher3FixExpr(DbFixer*, Expr*);
11619 SQLCIPHER_PRIVATE int sqlcipher3FixExprList(DbFixer*, ExprList*);
11620 SQLCIPHER_PRIVATE int sqlcipher3FixTriggerStep(DbFixer*, TriggerStep*);
11621 SQLCIPHER_PRIVATE int sqlcipher3AtoF(const char *z, double*, int, u8);
11622 SQLCIPHER_PRIVATE int sqlcipher3GetInt32(const char *, int*);
11623 SQLCIPHER_PRIVATE int sqlcipher3Atoi(const char*);
11624 SQLCIPHER_PRIVATE int sqlcipher3Utf16ByteLen(const void *pData, int nChar);
11625 SQLCIPHER_PRIVATE int sqlcipher3Utf8CharLen(const char *pData, int nByte);
11626 SQLCIPHER_PRIVATE u32 sqlcipher3Utf8Read(const u8*, const u8**);
11627
11628 /*
11629 ** Routines to read and write variable-length integers.  These used to
11630 ** be defined locally, but now we use the varint routines in the util.c
11631 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11632 ** are coded to assume the single byte case is already handled (which 
11633 ** the MACRO form does).
11634 */
11635 SQLCIPHER_PRIVATE int sqlcipher3PutVarint(unsigned char*, u64);
11636 SQLCIPHER_PRIVATE int sqlcipher3PutVarint32(unsigned char*, u32);
11637 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint(const unsigned char *, u64 *);
11638 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint32(const unsigned char *, u32 *);
11639 SQLCIPHER_PRIVATE int sqlcipher3VarintLen(u64 v);
11640
11641 /*
11642 ** The header of a record consists of a sequence variable-length integers.
11643 ** These integers are almost always small and are encoded as a single byte.
11644 ** The following macros take advantage this fact to provide a fast encode
11645 ** and decode of the integers in a record header.  It is faster for the common
11646 ** case where the integer is a single byte.  It is a little slower when the
11647 ** integer is two or more bytes.  But overall it is faster.
11648 **
11649 ** The following expressions are equivalent:
11650 **
11651 **     x = sqlcipher3GetVarint32( A, &B );
11652 **     x = sqlcipher3PutVarint32( A, B );
11653 **
11654 **     x = getVarint32( A, B );
11655 **     x = putVarint32( A, B );
11656 **
11657 */
11658 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlcipher3GetVarint32((A), (u32 *)&(B)))
11659 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlcipher3PutVarint32((A), (B)))
11660 #define getVarint    sqlcipher3GetVarint
11661 #define putVarint    sqlcipher3PutVarint
11662
11663
11664 SQLCIPHER_PRIVATE const char *sqlcipher3IndexAffinityStr(Vdbe *, Index *);
11665 SQLCIPHER_PRIVATE void sqlcipher3TableAffinityStr(Vdbe *, Table *);
11666 SQLCIPHER_PRIVATE char sqlcipher3CompareAffinity(Expr *pExpr, char aff2);
11667 SQLCIPHER_PRIVATE int sqlcipher3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11668 SQLCIPHER_PRIVATE char sqlcipher3ExprAffinity(Expr *pExpr);
11669 SQLCIPHER_PRIVATE int sqlcipher3Atoi64(const char*, i64*, int, u8);
11670 SQLCIPHER_PRIVATE void sqlcipher3Error(sqlcipher3*, int, const char*,...);
11671 SQLCIPHER_PRIVATE void *sqlcipher3HexToBlob(sqlcipher3*, const char *z, int n);
11672 SQLCIPHER_PRIVATE u8 sqlcipher3HexToInt(int h);
11673 SQLCIPHER_PRIVATE int sqlcipher3TwoPartName(Parse *, Token *, Token *, Token **);
11674 SQLCIPHER_PRIVATE const char *sqlcipher3ErrStr(int);
11675 SQLCIPHER_PRIVATE int sqlcipher3ReadSchema(Parse *pParse);
11676 SQLCIPHER_PRIVATE CollSeq *sqlcipher3FindCollSeq(sqlcipher3*,u8 enc, const char*,int);
11677 SQLCIPHER_PRIVATE CollSeq *sqlcipher3LocateCollSeq(Parse *pParse, const char*zName);
11678 SQLCIPHER_PRIVATE CollSeq *sqlcipher3ExprCollSeq(Parse *pParse, Expr *pExpr);
11679 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetColl(Expr*, CollSeq*);
11680 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11681 SQLCIPHER_PRIVATE int sqlcipher3CheckCollSeq(Parse *, CollSeq *);
11682 SQLCIPHER_PRIVATE int sqlcipher3CheckObjectName(Parse *, const char *);
11683 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetChanges(sqlcipher3 *, int);
11684 SQLCIPHER_PRIVATE int sqlcipher3AddInt64(i64*,i64);
11685 SQLCIPHER_PRIVATE int sqlcipher3SubInt64(i64*,i64);
11686 SQLCIPHER_PRIVATE int sqlcipher3MulInt64(i64*,i64);
11687 SQLCIPHER_PRIVATE int sqlcipher3AbsInt32(int);
11688 #ifdef SQLCIPHER_ENABLE_8_3_NAMES
11689 SQLCIPHER_PRIVATE void sqlcipher3FileSuffix3(const char*, char*);
11690 #else
11691 # define sqlcipher3FileSuffix3(X,Y)
11692 #endif
11693 SQLCIPHER_PRIVATE u8 sqlcipher3GetBoolean(const char *z);
11694
11695 SQLCIPHER_PRIVATE const void *sqlcipher3ValueText(sqlcipher3_value*, u8);
11696 SQLCIPHER_PRIVATE int sqlcipher3ValueBytes(sqlcipher3_value*, u8);
11697 SQLCIPHER_PRIVATE void sqlcipher3ValueSetStr(sqlcipher3_value*, int, const void *,u8, 
11698                         void(*)(void*));
11699 SQLCIPHER_PRIVATE void sqlcipher3ValueFree(sqlcipher3_value*);
11700 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3ValueNew(sqlcipher3 *);
11701 SQLCIPHER_PRIVATE char *sqlcipher3Utf16to8(sqlcipher3 *, const void*, int, u8);
11702 #ifdef SQLCIPHER_ENABLE_STAT3
11703 SQLCIPHER_PRIVATE char *sqlcipher3Utf8to16(sqlcipher3 *, u8, char *, int, int *);
11704 #endif
11705 SQLCIPHER_PRIVATE int sqlcipher3ValueFromExpr(sqlcipher3 *, Expr *, u8, u8, sqlcipher3_value **);
11706 SQLCIPHER_PRIVATE void sqlcipher3ValueApplyAffinity(sqlcipher3_value *, u8, u8);
11707 #ifndef SQLCIPHER_AMALGAMATION
11708 SQLCIPHER_PRIVATE const unsigned char sqlcipher3OpcodeProperty[];
11709 SQLCIPHER_PRIVATE const unsigned char sqlcipher3UpperToLower[];
11710 SQLCIPHER_PRIVATE const unsigned char sqlcipher3CtypeMap[];
11711 SQLCIPHER_PRIVATE const Token sqlcipher3IntTokens[];
11712 SQLCIPHER_PRIVATE SQLCIPHER_WSD struct Sqlite3Config sqlcipher3Config;
11713 SQLCIPHER_PRIVATE SQLCIPHER_WSD FuncDefHash sqlcipher3GlobalFunctions;
11714 #ifndef SQLCIPHER_OMIT_WSD
11715 SQLCIPHER_PRIVATE int sqlcipher3PendingByte;
11716 #endif
11717 #endif
11718 SQLCIPHER_PRIVATE void sqlcipher3RootPageMoved(sqlcipher3*, int, int, int);
11719 SQLCIPHER_PRIVATE void sqlcipher3Reindex(Parse*, Token*, Token*);
11720 SQLCIPHER_PRIVATE void sqlcipher3AlterFunctions(void);
11721 SQLCIPHER_PRIVATE void sqlcipher3AlterRenameTable(Parse*, SrcList*, Token*);
11722 SQLCIPHER_PRIVATE int sqlcipher3GetToken(const unsigned char *, int *);
11723 SQLCIPHER_PRIVATE void sqlcipher3NestedParse(Parse*, const char*, ...);
11724 SQLCIPHER_PRIVATE void sqlcipher3ExpirePreparedStatements(sqlcipher3*);
11725 SQLCIPHER_PRIVATE int sqlcipher3CodeSubselect(Parse *, Expr *, int, int);
11726 SQLCIPHER_PRIVATE void sqlcipher3SelectPrep(Parse*, Select*, NameContext*);
11727 SQLCIPHER_PRIVATE int sqlcipher3ResolveExprNames(NameContext*, Expr*);
11728 SQLCIPHER_PRIVATE void sqlcipher3ResolveSelectNames(Parse*, Select*, NameContext*);
11729 SQLCIPHER_PRIVATE int sqlcipher3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11730 SQLCIPHER_PRIVATE void sqlcipher3ColumnDefault(Vdbe *, Table *, int, int);
11731 SQLCIPHER_PRIVATE void sqlcipher3AlterFinishAddColumn(Parse *, Token *);
11732 SQLCIPHER_PRIVATE void sqlcipher3AlterBeginAddColumn(Parse *, SrcList *);
11733 SQLCIPHER_PRIVATE CollSeq *sqlcipher3GetCollSeq(sqlcipher3*, u8, CollSeq *, const char*);
11734 SQLCIPHER_PRIVATE char sqlcipher3AffinityType(const char*);
11735 SQLCIPHER_PRIVATE void sqlcipher3Analyze(Parse*, Token*, Token*);
11736 SQLCIPHER_PRIVATE int sqlcipher3InvokeBusyHandler(BusyHandler*);
11737 SQLCIPHER_PRIVATE int sqlcipher3FindDb(sqlcipher3*, Token*);
11738 SQLCIPHER_PRIVATE int sqlcipher3FindDbName(sqlcipher3 *, const char *);
11739 SQLCIPHER_PRIVATE int sqlcipher3AnalysisLoad(sqlcipher3*,int iDB);
11740 SQLCIPHER_PRIVATE void sqlcipher3DeleteIndexSamples(sqlcipher3*,Index*);
11741 SQLCIPHER_PRIVATE void sqlcipher3DefaultRowEst(Index*);
11742 SQLCIPHER_PRIVATE void sqlcipher3RegisterLikeFunctions(sqlcipher3*, int);
11743 SQLCIPHER_PRIVATE int sqlcipher3IsLikeFunction(sqlcipher3*,Expr*,int*,char*);
11744 SQLCIPHER_PRIVATE void sqlcipher3MinimumFileFormat(Parse*, int, int);
11745 SQLCIPHER_PRIVATE void sqlcipher3SchemaClear(void *);
11746 SQLCIPHER_PRIVATE Schema *sqlcipher3SchemaGet(sqlcipher3 *, Btree *);
11747 SQLCIPHER_PRIVATE int sqlcipher3SchemaToIndex(sqlcipher3 *db, Schema *);
11748 SQLCIPHER_PRIVATE KeyInfo *sqlcipher3IndexKeyinfo(Parse *, Index *);
11749 SQLCIPHER_PRIVATE int sqlcipher3CreateFunc(sqlcipher3 *, const char *, int, int, void *, 
11750   void (*)(sqlcipher3_context*,int,sqlcipher3_value **),
11751   void (*)(sqlcipher3_context*,int,sqlcipher3_value **), void (*)(sqlcipher3_context*),
11752   FuncDestructor *pDestructor
11753 );
11754 SQLCIPHER_PRIVATE int sqlcipher3ApiExit(sqlcipher3 *db, int);
11755 SQLCIPHER_PRIVATE int sqlcipher3OpenTempDatabase(Parse *);
11756
11757 SQLCIPHER_PRIVATE void sqlcipher3StrAccumInit(StrAccum*, char*, int, int);
11758 SQLCIPHER_PRIVATE void sqlcipher3StrAccumAppend(StrAccum*,const char*,int);
11759 SQLCIPHER_PRIVATE char *sqlcipher3StrAccumFinish(StrAccum*);
11760 SQLCIPHER_PRIVATE void sqlcipher3StrAccumReset(StrAccum*);
11761 SQLCIPHER_PRIVATE void sqlcipher3SelectDestInit(SelectDest*,int,int);
11762 SQLCIPHER_PRIVATE Expr *sqlcipher3CreateColumnExpr(sqlcipher3 *, SrcList *, int, int);
11763
11764 SQLCIPHER_PRIVATE void sqlcipher3BackupRestart(sqlcipher3_backup *);
11765 SQLCIPHER_PRIVATE void sqlcipher3BackupUpdate(sqlcipher3_backup *, Pgno, const u8 *);
11766
11767 /*
11768 ** The interface to the LEMON-generated parser
11769 */
11770 SQLCIPHER_PRIVATE void *sqlcipher3ParserAlloc(void*(*)(size_t));
11771 SQLCIPHER_PRIVATE void sqlcipher3ParserFree(void*, void(*)(void*));
11772 SQLCIPHER_PRIVATE void sqlcipher3Parser(void*, int, Token, Parse*);
11773 #ifdef YYTRACKMAXSTACKDEPTH
11774 SQLCIPHER_PRIVATE   int sqlcipher3ParserStackPeak(void*);
11775 #endif
11776
11777 SQLCIPHER_PRIVATE void sqlcipher3AutoLoadExtensions(sqlcipher3*);
11778 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
11779 SQLCIPHER_PRIVATE   void sqlcipher3CloseExtensions(sqlcipher3*);
11780 #else
11781 # define sqlcipher3CloseExtensions(X)
11782 #endif
11783
11784 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
11785 SQLCIPHER_PRIVATE   void sqlcipher3TableLock(Parse *, int, int, u8, const char *);
11786 #else
11787   #define sqlcipher3TableLock(v,w,x,y,z)
11788 #endif
11789
11790 #ifdef SQLCIPHER_TEST
11791 SQLCIPHER_PRIVATE   int sqlcipher3Utf8To8(unsigned char*);
11792 #endif
11793
11794 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
11795 #  define sqlcipher3VtabClear(Y)
11796 #  define sqlcipher3VtabSync(X,Y) SQLCIPHER_OK
11797 #  define sqlcipher3VtabRollback(X)
11798 #  define sqlcipher3VtabCommit(X)
11799 #  define sqlcipher3VtabInSync(db) 0
11800 #  define sqlcipher3VtabLock(X) 
11801 #  define sqlcipher3VtabUnlock(X)
11802 #  define sqlcipher3VtabUnlockList(X)
11803 #  define sqlcipher3VtabSavepoint(X, Y, Z) SQLCIPHER_OK
11804 #  define sqlcipher3GetVTable(X,Y)  ((VTable*)0)
11805 #else
11806 SQLCIPHER_PRIVATE    void sqlcipher3VtabClear(sqlcipher3 *db, Table*);
11807 SQLCIPHER_PRIVATE    int sqlcipher3VtabSync(sqlcipher3 *db, char **);
11808 SQLCIPHER_PRIVATE    int sqlcipher3VtabRollback(sqlcipher3 *db);
11809 SQLCIPHER_PRIVATE    int sqlcipher3VtabCommit(sqlcipher3 *db);
11810 SQLCIPHER_PRIVATE    void sqlcipher3VtabLock(VTable *);
11811 SQLCIPHER_PRIVATE    void sqlcipher3VtabUnlock(VTable *);
11812 SQLCIPHER_PRIVATE    void sqlcipher3VtabUnlockList(sqlcipher3*);
11813 SQLCIPHER_PRIVATE    int sqlcipher3VtabSavepoint(sqlcipher3 *, int, int);
11814 SQLCIPHER_PRIVATE    VTable *sqlcipher3GetVTable(sqlcipher3*, Table*);
11815 #  define sqlcipher3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11816 #endif
11817 SQLCIPHER_PRIVATE void sqlcipher3VtabMakeWritable(Parse*,Table*);
11818 SQLCIPHER_PRIVATE void sqlcipher3VtabBeginParse(Parse*, Token*, Token*, Token*);
11819 SQLCIPHER_PRIVATE void sqlcipher3VtabFinishParse(Parse*, Token*);
11820 SQLCIPHER_PRIVATE void sqlcipher3VtabArgInit(Parse*);
11821 SQLCIPHER_PRIVATE void sqlcipher3VtabArgExtend(Parse*, Token*);
11822 SQLCIPHER_PRIVATE int sqlcipher3VtabCallCreate(sqlcipher3*, int, const char *, char **);
11823 SQLCIPHER_PRIVATE int sqlcipher3VtabCallConnect(Parse*, Table*);
11824 SQLCIPHER_PRIVATE int sqlcipher3VtabCallDestroy(sqlcipher3*, int, const char *);
11825 SQLCIPHER_PRIVATE int sqlcipher3VtabBegin(sqlcipher3 *, VTable *);
11826 SQLCIPHER_PRIVATE FuncDef *sqlcipher3VtabOverloadFunction(sqlcipher3 *,FuncDef*, int nArg, Expr*);
11827 SQLCIPHER_PRIVATE void sqlcipher3InvalidFunction(sqlcipher3_context*,int,sqlcipher3_value**);
11828 SQLCIPHER_PRIVATE int sqlcipher3VdbeParameterIndex(Vdbe*, const char*, int);
11829 SQLCIPHER_PRIVATE int sqlcipher3TransferBindings(sqlcipher3_stmt *, sqlcipher3_stmt *);
11830 SQLCIPHER_PRIVATE int sqlcipher3Reprepare(Vdbe*);
11831 SQLCIPHER_PRIVATE void sqlcipher3ExprListCheckLength(Parse*, ExprList*, const char*);
11832 SQLCIPHER_PRIVATE CollSeq *sqlcipher3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11833 SQLCIPHER_PRIVATE int sqlcipher3TempInMemory(const sqlcipher3*);
11834 SQLCIPHER_PRIVATE const char *sqlcipher3JournalModename(int);
11835 SQLCIPHER_PRIVATE int sqlcipher3Checkpoint(sqlcipher3*, int, int, int*, int*);
11836 SQLCIPHER_PRIVATE int sqlcipher3WalDefaultHook(void*,sqlcipher3*,const char*,int);
11837
11838 /* Declarations for functions in fkey.c. All of these are replaced by
11839 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11840 ** key functionality is available. If OMIT_TRIGGER is defined but
11841 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11842 ** this case foreign keys are parsed, but no other functionality is 
11843 ** provided (enforcement of FK constraints requires the triggers sub-system).
11844 */
11845 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
11846 SQLCIPHER_PRIVATE   void sqlcipher3FkCheck(Parse*, Table*, int, int);
11847 SQLCIPHER_PRIVATE   void sqlcipher3FkDropTable(Parse*, SrcList *, Table*);
11848 SQLCIPHER_PRIVATE   void sqlcipher3FkActions(Parse*, Table*, ExprList*, int);
11849 SQLCIPHER_PRIVATE   int sqlcipher3FkRequired(Parse*, Table*, int*, int);
11850 SQLCIPHER_PRIVATE   u32 sqlcipher3FkOldmask(Parse*, Table*);
11851 SQLCIPHER_PRIVATE   FKey *sqlcipher3FkReferences(Table *);
11852 #else
11853   #define sqlcipher3FkActions(a,b,c,d)
11854   #define sqlcipher3FkCheck(a,b,c,d)
11855   #define sqlcipher3FkDropTable(a,b,c)
11856   #define sqlcipher3FkOldmask(a,b)      0
11857   #define sqlcipher3FkRequired(a,b,c,d) 0
11858 #endif
11859 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
11860 SQLCIPHER_PRIVATE   void sqlcipher3FkDelete(sqlcipher3 *, Table*);
11861 #else
11862   #define sqlcipher3FkDelete(a,b)
11863 #endif
11864
11865
11866 /*
11867 ** Available fault injectors.  Should be numbered beginning with 0.
11868 */
11869 #define SQLCIPHER_FAULTINJECTOR_MALLOC     0
11870 #define SQLCIPHER_FAULTINJECTOR_COUNT      1
11871
11872 /*
11873 ** The interface to the code in fault.c used for identifying "benign"
11874 ** malloc failures. This is only present if SQLCIPHER_OMIT_BUILTIN_TEST
11875 ** is not defined.
11876 */
11877 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
11878 SQLCIPHER_PRIVATE   void sqlcipher3BeginBenignMalloc(void);
11879 SQLCIPHER_PRIVATE   void sqlcipher3EndBenignMalloc(void);
11880 #else
11881   #define sqlcipher3BeginBenignMalloc()
11882   #define sqlcipher3EndBenignMalloc()
11883 #endif
11884
11885 #define IN_INDEX_ROWID           1
11886 #define IN_INDEX_EPH             2
11887 #define IN_INDEX_INDEX           3
11888 SQLCIPHER_PRIVATE int sqlcipher3FindInIndex(Parse *, Expr *, int*);
11889
11890 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
11891 SQLCIPHER_PRIVATE   int sqlcipher3JournalOpen(sqlcipher3_vfs *, const char *, sqlcipher3_file *, int, int);
11892 SQLCIPHER_PRIVATE   int sqlcipher3JournalSize(sqlcipher3_vfs *);
11893 SQLCIPHER_PRIVATE   int sqlcipher3JournalCreate(sqlcipher3_file *);
11894 #else
11895   #define sqlcipher3JournalSize(pVfs) ((pVfs)->szOsFile)
11896 #endif
11897
11898 SQLCIPHER_PRIVATE void sqlcipher3MemJournalOpen(sqlcipher3_file *);
11899 SQLCIPHER_PRIVATE int sqlcipher3MemJournalSize(void);
11900 SQLCIPHER_PRIVATE int sqlcipher3IsMemJournal(sqlcipher3_file *);
11901
11902 #if SQLCIPHER_MAX_EXPR_DEPTH>0
11903 SQLCIPHER_PRIVATE   void sqlcipher3ExprSetHeight(Parse *pParse, Expr *p);
11904 SQLCIPHER_PRIVATE   int sqlcipher3SelectExprHeight(Select *);
11905 SQLCIPHER_PRIVATE   int sqlcipher3ExprCheckHeight(Parse*, int);
11906 #else
11907   #define sqlcipher3ExprSetHeight(x,y)
11908   #define sqlcipher3SelectExprHeight(x) 0
11909   #define sqlcipher3ExprCheckHeight(x,y)
11910 #endif
11911
11912 SQLCIPHER_PRIVATE u32 sqlcipher3Get4byte(const u8*);
11913 SQLCIPHER_PRIVATE void sqlcipher3Put4byte(u8*, u32);
11914
11915 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
11916 SQLCIPHER_PRIVATE   void sqlcipher3ConnectionBlocked(sqlcipher3 *, sqlcipher3 *);
11917 SQLCIPHER_PRIVATE   void sqlcipher3ConnectionUnlocked(sqlcipher3 *db);
11918 SQLCIPHER_PRIVATE   void sqlcipher3ConnectionClosed(sqlcipher3 *db);
11919 #else
11920   #define sqlcipher3ConnectionBlocked(x,y)
11921   #define sqlcipher3ConnectionUnlocked(x)
11922   #define sqlcipher3ConnectionClosed(x)
11923 #endif
11924
11925 #ifdef SQLCIPHER_DEBUG
11926 SQLCIPHER_PRIVATE   void sqlcipher3ParserTrace(FILE*, char *);
11927 #endif
11928
11929 /*
11930 ** If the SQLCIPHER_ENABLE IOTRACE exists then the global variable
11931 ** sqlcipher3IoTrace is a pointer to a printf-like routine used to
11932 ** print I/O tracing messages. 
11933 */
11934 #ifdef SQLCIPHER_ENABLE_IOTRACE
11935 # define IOTRACE(A)  if( sqlcipher3IoTrace ){ sqlcipher3IoTrace A; }
11936 SQLCIPHER_PRIVATE   void sqlcipher3VdbeIOTraceSql(Vdbe*);
11937 SQLCIPHER_PRIVATE void (*sqlcipher3IoTrace)(const char*,...);
11938 #else
11939 # define IOTRACE(A)
11940 # define sqlcipher3VdbeIOTraceSql(X)
11941 #endif
11942
11943 /*
11944 ** These routines are available for the mem2.c debugging memory allocator
11945 ** only.  They are used to verify that different "types" of memory
11946 ** allocations are properly tracked by the system.
11947 **
11948 ** sqlcipher3MemdebugSetType() sets the "type" of an allocation to one of
11949 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11950 ** a single bit set.
11951 **
11952 ** sqlcipher3MemdebugHasType() returns true if any of the bits in its second
11953 ** argument match the type set by the previous sqlcipher3MemdebugSetType().
11954 ** sqlcipher3MemdebugHasType() is intended for use inside assert() statements.
11955 **
11956 ** sqlcipher3MemdebugNoType() returns true if none of the bits in its second
11957 ** argument match the type set by the previous sqlcipher3MemdebugSetType().
11958 **
11959 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11960 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11961 ** it might have been allocated by lookaside, except the allocation was
11962 ** too large or lookaside was already full.  It is important to verify
11963 ** that allocations that might have been satisfied by lookaside are not
11964 ** passed back to non-lookaside free() routines.  Asserts such as the
11965 ** example above are placed on the non-lookaside free() routines to verify
11966 ** this constraint. 
11967 **
11968 ** All of this is no-op for a production build.  It only comes into
11969 ** play when the SQLCIPHER_MEMDEBUG compile-time option is used.
11970 */
11971 #ifdef SQLCIPHER_MEMDEBUG
11972 SQLCIPHER_PRIVATE   void sqlcipher3MemdebugSetType(void*,u8);
11973 SQLCIPHER_PRIVATE   int sqlcipher3MemdebugHasType(void*,u8);
11974 SQLCIPHER_PRIVATE   int sqlcipher3MemdebugNoType(void*,u8);
11975 #else
11976 # define sqlcipher3MemdebugSetType(X,Y)  /* no-op */
11977 # define sqlcipher3MemdebugHasType(X,Y)  1
11978 # define sqlcipher3MemdebugNoType(X,Y)   1
11979 #endif
11980 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11981 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11982 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11983 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11984 #define MEMTYPE_DB         0x10  /* Uses sqlcipher3DbMalloc, not sqlcipher_malloc */
11985
11986 #endif /* _SQLCIPHERINT_H_ */
11987
11988 /************** End of sqlcipherInt.h *******************************************/
11989 /************** Begin file crypto.c ******************************************/
11990 /* 
11991 ** SQLCipher
11992 ** crypto.c developed by Stephen Lombardo (Zetetic LLC) 
11993 ** sjlombardo at zetetic dot net
11994 ** http://zetetic.net
11995 ** 
11996 ** Copyright (c) 2009, ZETETIC LLC
11997 ** All rights reserved.
11998 ** 
11999 ** Redistribution and use in source and binary forms, with or without
12000 ** modification, are permitted provided that the following conditions are met:
12001 **     * Redistributions of source code must retain the above copyright
12002 **       notice, this list of conditions and the following disclaimer.
12003 **     * Redistributions in binary form must reproduce the above copyright
12004 **       notice, this list of conditions and the following disclaimer in the
12005 **       documentation and/or other materials provided with the distribution.
12006 **     * Neither the name of the ZETETIC LLC nor the
12007 **       names of its contributors may be used to endorse or promote products
12008 **       derived from this software without specific prior written permission.
12009 ** 
12010 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
12011 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12012 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12013 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
12014 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
12015 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
12016 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
12017 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12018 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
12019 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12020 **  
12021 */
12022 /* BEGIN CRYPTO */
12023 #ifdef SQLCIPHER_HAS_CODEC
12024
12025 /* #include <assert.h> */
12026 /************** Include btreeInt.h in the middle of crypto.c *****************/
12027 /************** Begin file btreeInt.h ****************************************/
12028 /*
12029 ** 2004 April 6
12030 **
12031 ** The author disclaims copyright to this source code.  In place of
12032 ** a legal notice, here is a blessing:
12033 **
12034 **    May you do good and not evil.
12035 **    May you find forgiveness for yourself and forgive others.
12036 **    May you share freely, never taking more than you give.
12037 **
12038 *************************************************************************
12039 ** This file implements a external (disk-based) database using BTrees.
12040 ** For a detailed discussion of BTrees, refer to
12041 **
12042 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
12043 **     "Sorting And Searching", pages 473-480. Addison-Wesley
12044 **     Publishing Company, Reading, Massachusetts.
12045 **
12046 ** The basic idea is that each page of the file contains N database
12047 ** entries and N+1 pointers to subpages.
12048 **
12049 **   ----------------------------------------------------------------
12050 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
12051 **   ----------------------------------------------------------------
12052 **
12053 ** All of the keys on the page that Ptr(0) points to have values less
12054 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
12055 ** values greater than Key(0) and less than Key(1).  All of the keys
12056 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
12057 ** so forth.
12058 **
12059 ** Finding a particular key requires reading O(log(M)) pages from the 
12060 ** disk where M is the number of entries in the tree.
12061 **
12062 ** In this implementation, a single file can hold one or more separate 
12063 ** BTrees.  Each BTree is identified by the index of its root page.  The
12064 ** key and data for any entry are combined to form the "payload".  A
12065 ** fixed amount of payload can be carried directly on the database
12066 ** page.  If the payload is larger than the preset amount then surplus
12067 ** bytes are stored on overflow pages.  The payload for an entry
12068 ** and the preceding pointer are combined to form a "Cell".  Each 
12069 ** page has a small header which contains the Ptr(N) pointer and other
12070 ** information such as the size of key and data.
12071 **
12072 ** FORMAT DETAILS
12073 **
12074 ** The file is divided into pages.  The first page is called page 1,
12075 ** the second is page 2, and so forth.  A page number of zero indicates
12076 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
12077 ** Each page can be either a btree page, a freelist page, an overflow
12078 ** page, or a pointer-map page.
12079 **
12080 ** The first page is always a btree page.  The first 100 bytes of the first
12081 ** page contain a special header (the "file header") that describes the file.
12082 ** The format of the file header is as follows:
12083 **
12084 **   OFFSET   SIZE    DESCRIPTION
12085 **      0      16     Header string: "SQLite format 3\000"
12086 **     16       2     Page size in bytes.  
12087 **     18       1     File format write version
12088 **     19       1     File format read version
12089 **     20       1     Bytes of unused space at the end of each page
12090 **     21       1     Max embedded payload fraction
12091 **     22       1     Min embedded payload fraction
12092 **     23       1     Min leaf payload fraction
12093 **     24       4     File change counter
12094 **     28       4     Reserved for future use
12095 **     32       4     First freelist page
12096 **     36       4     Number of freelist pages in the file
12097 **     40      60     15 4-byte meta values passed to higher layers
12098 **
12099 **     40       4     Schema cookie
12100 **     44       4     File format of schema layer
12101 **     48       4     Size of page cache
12102 **     52       4     Largest root-page (auto/incr_vacuum)
12103 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
12104 **     60       4     User version
12105 **     64       4     Incremental vacuum mode
12106 **     68       4     unused
12107 **     72       4     unused
12108 **     76       4     unused
12109 **
12110 ** All of the integer values are big-endian (most significant byte first).
12111 **
12112 ** The file change counter is incremented when the database is changed
12113 ** This counter allows other processes to know when the file has changed
12114 ** and thus when they need to flush their cache.
12115 **
12116 ** The max embedded payload fraction is the amount of the total usable
12117 ** space in a page that can be consumed by a single cell for standard
12118 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
12119 ** is to limit the maximum cell size so that at least 4 cells will fit
12120 ** on one page.  Thus the default max embedded payload fraction is 64.
12121 **
12122 ** If the payload for a cell is larger than the max payload, then extra
12123 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
12124 ** as many bytes as possible are moved into the overflow pages without letting
12125 ** the cell size drop below the min embedded payload fraction.
12126 **
12127 ** The min leaf payload fraction is like the min embedded payload fraction
12128 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
12129 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
12130 ** not specified in the header.
12131 **
12132 ** Each btree pages is divided into three sections:  The header, the
12133 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
12134 ** file header that occurs before the page header.
12135 **
12136 **      |----------------|
12137 **      | file header    |   100 bytes.  Page 1 only.
12138 **      |----------------|
12139 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
12140 **      |----------------|
12141 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
12142 **      | array          |   |  Grows downward
12143 **      |                |   v
12144 **      |----------------|
12145 **      | unallocated    |
12146 **      | space          |
12147 **      |----------------|   ^  Grows upwards
12148 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
12149 **      | area           |   |  and free space fragments.
12150 **      |----------------|
12151 **
12152 ** The page headers looks like this:
12153 **
12154 **   OFFSET   SIZE     DESCRIPTION
12155 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
12156 **      1       2      byte offset to the first freeblock
12157 **      3       2      number of cells on this page
12158 **      5       2      first byte of the cell content area
12159 **      7       1      number of fragmented free bytes
12160 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
12161 **
12162 ** The flags define the format of this btree page.  The leaf flag means that
12163 ** this page has no children.  The zerodata flag means that this page carries
12164 ** only keys and no data.  The intkey flag means that the key is a integer
12165 ** which is stored in the key size entry of the cell header rather than in
12166 ** the payload area.
12167 **
12168 ** The cell pointer array begins on the first byte after the page header.
12169 ** The cell pointer array contains zero or more 2-byte numbers which are
12170 ** offsets from the beginning of the page to the cell content in the cell
12171 ** content area.  The cell pointers occur in sorted order.  The system strives
12172 ** to keep free space after the last cell pointer so that new cells can
12173 ** be easily added without having to defragment the page.
12174 **
12175 ** Cell content is stored at the very end of the page and grows toward the
12176 ** beginning of the page.
12177 **
12178 ** Unused space within the cell content area is collected into a linked list of
12179 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
12180 ** to the first freeblock is given in the header.  Freeblocks occur in
12181 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
12182 ** any group of 3 or fewer unused bytes in the cell content area cannot
12183 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
12184 ** a fragment.  The total number of bytes in all fragments is recorded.
12185 ** in the page header at offset 7.
12186 **
12187 **    SIZE    DESCRIPTION
12188 **      2     Byte offset of the next freeblock
12189 **      2     Bytes in this freeblock
12190 **
12191 ** Cells are of variable length.  Cells are stored in the cell content area at
12192 ** the end of the page.  Pointers to the cells are in the cell pointer array
12193 ** that immediately follows the page header.  Cells is not necessarily
12194 ** contiguous or in order, but cell pointers are contiguous and in order.
12195 **
12196 ** Cell content makes use of variable length integers.  A variable
12197 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
12198 ** byte are used.  The integer consists of all bytes that have bit 8 set and
12199 ** the first byte with bit 8 clear.  The most significant byte of the integer
12200 ** appears first.  A variable-length integer may not be more than 9 bytes long.
12201 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
12202 ** allows a 64-bit integer to be encoded in 9 bytes.
12203 **
12204 **    0x00                      becomes  0x00000000
12205 **    0x7f                      becomes  0x0000007f
12206 **    0x81 0x00                 becomes  0x00000080
12207 **    0x82 0x00                 becomes  0x00000100
12208 **    0x80 0x7f                 becomes  0x0000007f
12209 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
12210 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
12211 **
12212 ** Variable length integers are used for rowids and to hold the number of
12213 ** bytes of key and data in a btree cell.
12214 **
12215 ** The content of a cell looks like this:
12216 **
12217 **    SIZE    DESCRIPTION
12218 **      4     Page number of the left child. Omitted if leaf flag is set.
12219 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
12220 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
12221 **      *     Payload
12222 **      4     First page of the overflow chain.  Omitted if no overflow
12223 **
12224 ** Overflow pages form a linked list.  Each page except the last is completely
12225 ** filled with data (pagesize - 4 bytes).  The last page can have as little
12226 ** as 1 byte of data.
12227 **
12228 **    SIZE    DESCRIPTION
12229 **      4     Page number of next overflow page
12230 **      *     Data
12231 **
12232 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
12233 ** file header points to the first in a linked list of trunk page.  Each trunk
12234 ** page points to multiple leaf pages.  The content of a leaf page is
12235 ** unspecified.  A trunk page looks like this:
12236 **
12237 **    SIZE    DESCRIPTION
12238 **      4     Page number of next trunk page
12239 **      4     Number of leaf pointers on this page
12240 **      *     zero or more pages numbers of leaves
12241 */
12242
12243
12244 /* The following value is the maximum cell size assuming a maximum page
12245 ** size give above.
12246 */
12247 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
12248
12249 /* The maximum number of cells on a single page of the database.  This
12250 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
12251 ** plus 2 bytes for the index to the cell in the page header).  Such
12252 ** small cells will be rare, but they are possible.
12253 */
12254 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
12255
12256 /* Forward declarations */
12257 typedef struct MemPage MemPage;
12258 typedef struct BtLock BtLock;
12259
12260 /*
12261 ** This is a magic string that appears at the beginning of every
12262 ** SQLite database in order to identify the file as a real database.
12263 **
12264 ** You can change this value at compile-time by specifying a
12265 ** -DSQLCIPHER_FILE_HEADER="..." on the compiler command-line.  The
12266 ** header must be exactly 16 bytes including the zero-terminator so
12267 ** the string itself should be 15 characters long.  If you change
12268 ** the header, then your custom library will not be able to read 
12269 ** databases generated by the standard tools and the standard tools
12270 ** will not be able to read databases created by your custom library.
12271 */
12272 #ifndef SQLCIPHER_FILE_HEADER /* 123456789 123456 */
12273 #  define SQLCIPHER_FILE_HEADER "SQLite format 3"
12274 #endif
12275
12276 /*
12277 ** Page type flags.  An ORed combination of these flags appear as the
12278 ** first byte of on-disk image of every BTree page.
12279 */
12280 #define PTF_INTKEY    0x01
12281 #define PTF_ZERODATA  0x02
12282 #define PTF_LEAFDATA  0x04
12283 #define PTF_LEAF      0x08
12284
12285 /*
12286 ** As each page of the file is loaded into memory, an instance of the following
12287 ** structure is appended and initialized to zero.  This structure stores
12288 ** information about the page that is decoded from the raw file page.
12289 **
12290 ** The pParent field points back to the parent page.  This allows us to
12291 ** walk up the BTree from any leaf to the root.  Care must be taken to
12292 ** unref() the parent page pointer when this page is no longer referenced.
12293 ** The pageDestructor() routine handles that chore.
12294 **
12295 ** Access to all fields of this structure is controlled by the mutex
12296 ** stored in MemPage.pBt->mutex.
12297 */
12298 struct MemPage {
12299   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
12300   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
12301   u8 intKey;           /* True if intkey flag is set */
12302   u8 leaf;             /* True if leaf flag is set */
12303   u8 hasData;          /* True if this page stores data */
12304   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
12305   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
12306   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
12307   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
12308   u16 cellOffset;      /* Index in aData of first cell pointer */
12309   u16 nFree;           /* Number of free bytes on the page */
12310   u16 nCell;           /* Number of cells on this page, local and ovfl */
12311   u16 maskPage;        /* Mask for page offset */
12312   struct _OvflCell {   /* Cells that will not fit on aData[] */
12313     u8 *pCell;          /* Pointers to the body of the overflow cell */
12314     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
12315   } aOvfl[5];
12316   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
12317   u8 *aData;           /* Pointer to disk image of the page data */
12318   DbPage *pDbPage;     /* Pager page handle */
12319   Pgno pgno;           /* Page number for this page */
12320 };
12321
12322 /*
12323 ** The in-memory image of a disk page has the auxiliary information appended
12324 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
12325 ** that extra information.
12326 */
12327 #define EXTRA_SIZE sizeof(MemPage)
12328
12329 /*
12330 ** A linked list of the following structures is stored at BtShared.pLock.
12331 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
12332 ** is opened on the table with root page BtShared.iTable. Locks are removed
12333 ** from this list when a transaction is committed or rolled back, or when
12334 ** a btree handle is closed.
12335 */
12336 struct BtLock {
12337   Btree *pBtree;        /* Btree handle holding this lock */
12338   Pgno iTable;          /* Root page of table */
12339   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
12340   BtLock *pNext;        /* Next in BtShared.pLock list */
12341 };
12342
12343 /* Candidate values for BtLock.eLock */
12344 #define READ_LOCK     1
12345 #define WRITE_LOCK    2
12346
12347 /* A Btree handle
12348 **
12349 ** A database connection contains a pointer to an instance of
12350 ** this object for every database file that it has open.  This structure
12351 ** is opaque to the database connection.  The database connection cannot
12352 ** see the internals of this structure and only deals with pointers to
12353 ** this structure.
12354 **
12355 ** For some database files, the same underlying database cache might be 
12356 ** shared between multiple connections.  In that case, each connection
12357 ** has it own instance of this object.  But each instance of this object
12358 ** points to the same BtShared object.  The database cache and the
12359 ** schema associated with the database file are all contained within
12360 ** the BtShared object.
12361 **
12362 ** All fields in this structure are accessed under sqlcipher3.mutex.
12363 ** The pBt pointer itself may not be changed while there exists cursors 
12364 ** in the referenced BtShared that point back to this Btree since those
12365 ** cursors have to go through this Btree to find their BtShared and
12366 ** they often do so without holding sqlcipher3.mutex.
12367 */
12368 struct Btree {
12369   sqlcipher3 *db;       /* The database connection holding this btree */
12370   BtShared *pBt;     /* Sharable content of this btree */
12371   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
12372   u8 sharable;       /* True if we can share pBt with another db */
12373   u8 locked;         /* True if db currently has pBt locked */
12374   int wantToLock;    /* Number of nested calls to sqlcipher3BtreeEnter() */
12375   int nBackup;       /* Number of backup operations reading this btree */
12376   Btree *pNext;      /* List of other sharable Btrees from the same db */
12377   Btree *pPrev;      /* Back pointer of the same list */
12378 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
12379   BtLock lock;       /* Object used to lock page 1 */
12380 #endif
12381 };
12382
12383 /*
12384 ** Btree.inTrans may take one of the following values.
12385 **
12386 ** If the shared-data extension is enabled, there may be multiple users
12387 ** of the Btree structure. At most one of these may open a write transaction,
12388 ** but any number may have active read transactions.
12389 */
12390 #define TRANS_NONE  0
12391 #define TRANS_READ  1
12392 #define TRANS_WRITE 2
12393
12394 /*
12395 ** An instance of this object represents a single database file.
12396 ** 
12397 ** A single database file can be in use as the same time by two
12398 ** or more database connections.  When two or more connections are
12399 ** sharing the same database file, each connection has it own
12400 ** private Btree object for the file and each of those Btrees points
12401 ** to this one BtShared object.  BtShared.nRef is the number of
12402 ** connections currently sharing this database file.
12403 **
12404 ** Fields in this structure are accessed under the BtShared.mutex
12405 ** mutex, except for nRef and pNext which are accessed under the
12406 ** global SQLCIPHER_MUTEX_STATIC_MASTER mutex.  The pPager field
12407 ** may not be modified once it is initially set as long as nRef>0.
12408 ** The pSchema field may be set once under BtShared.mutex and
12409 ** thereafter is unchanged as long as nRef>0.
12410 **
12411 ** isPending:
12412 **
12413 **   If a BtShared client fails to obtain a write-lock on a database
12414 **   table (because there exists one or more read-locks on the table),
12415 **   the shared-cache enters 'pending-lock' state and isPending is
12416 **   set to true.
12417 **
12418 **   The shared-cache leaves the 'pending lock' state when either of
12419 **   the following occur:
12420 **
12421 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
12422 **     2) The number of locks held by other connections drops to zero.
12423 **
12424 **   while in the 'pending-lock' state, no connection may start a new
12425 **   transaction.
12426 **
12427 **   This feature is included to help prevent writer-starvation.
12428 */
12429 struct BtShared {
12430   Pager *pPager;        /* The page cache */
12431   sqlcipher3 *db;          /* Database connection currently using this Btree */
12432   BtCursor *pCursor;    /* A list of all open cursors */
12433   MemPage *pPage1;      /* First page of the database */
12434   u8 readOnly;          /* True if the underlying file is readonly */
12435   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
12436   u8 secureDelete;      /* True if secure_delete is enabled */
12437   u8 initiallyEmpty;    /* Database is empty at start of transaction */
12438   u8 openFlags;         /* Flags to sqlcipher3BtreeOpen() */
12439 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
12440   u8 autoVacuum;        /* True if auto-vacuum is enabled */
12441   u8 incrVacuum;        /* True if incr-vacuum is enabled */
12442 #endif
12443   u8 inTransaction;     /* Transaction state */
12444   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
12445   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
12446   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
12447   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
12448   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
12449   u32 pageSize;         /* Total number of bytes on a page */
12450   u32 usableSize;       /* Number of usable bytes on each page */
12451   int nTransaction;     /* Number of open transactions (read + write) */
12452   u32 nPage;            /* Number of pages in the database */
12453   void *pSchema;        /* Pointer to space allocated by sqlcipher3BtreeSchema() */
12454   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
12455   sqlcipher3_mutex *mutex; /* Non-recursive mutex required to access this object */
12456   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
12457 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
12458   int nRef;             /* Number of references to this structure */
12459   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
12460   BtLock *pLock;        /* List of locks held on this shared-btree struct */
12461   Btree *pWriter;       /* Btree with currently open write transaction */
12462   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
12463   u8 isPending;         /* If waiting for read-locks to clear */
12464 #endif
12465   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
12466 };
12467
12468 /*
12469 ** An instance of the following structure is used to hold information
12470 ** about a cell.  The parseCellPtr() function fills in this structure
12471 ** based on information extract from the raw disk page.
12472 */
12473 typedef struct CellInfo CellInfo;
12474 struct CellInfo {
12475   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
12476   u8 *pCell;     /* Pointer to the start of cell content */
12477   u32 nData;     /* Number of bytes of data */
12478   u32 nPayload;  /* Total amount of payload */
12479   u16 nHeader;   /* Size of the cell content header in bytes */
12480   u16 nLocal;    /* Amount of payload held locally */
12481   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
12482   u16 nSize;     /* Size of the cell content on the main b-tree page */
12483 };
12484
12485 /*
12486 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
12487 ** this will be declared corrupt. This value is calculated based on a
12488 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
12489 ** root-node and 3 for all other internal nodes.
12490 **
12491 ** If a tree that appears to be taller than this is encountered, it is
12492 ** assumed that the database is corrupt.
12493 */
12494 #define BTCURSOR_MAX_DEPTH 20
12495
12496 /*
12497 ** A cursor is a pointer to a particular entry within a particular
12498 ** b-tree within a database file.
12499 **
12500 ** The entry is identified by its MemPage and the index in
12501 ** MemPage.aCell[] of the entry.
12502 **
12503 ** A single database file can shared by two more database connections,
12504 ** but cursors cannot be shared.  Each cursor is associated with a
12505 ** particular database connection identified BtCursor.pBtree.db.
12506 **
12507 ** Fields in this structure are accessed under the BtShared.mutex
12508 ** found at self->pBt->mutex. 
12509 */
12510 struct BtCursor {
12511   Btree *pBtree;            /* The Btree to which this cursor belongs */
12512   BtShared *pBt;            /* The BtShared this cursor points to */
12513   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
12514   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
12515   Pgno pgnoRoot;            /* The root page of this tree */
12516   sqlcipher3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
12517   CellInfo info;            /* A parse of the cell we are pointing at */
12518   i64 nKey;        /* Size of pKey, or last integer key */
12519   void *pKey;      /* Saved key that was cursor's last known position */
12520   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
12521   u8 wrFlag;                /* True if writable */
12522   u8 atLast;                /* Cursor pointing to the last entry */
12523   u8 validNKey;             /* True if info.nKey is valid */
12524   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
12525 #ifndef SQLCIPHER_OMIT_INCRBLOB
12526   Pgno *aOverflow;          /* Cache of overflow page locations */
12527   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
12528 #endif
12529   i16 iPage;                            /* Index of current page in apPage */
12530   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
12531   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
12532 };
12533
12534 /*
12535 ** Potential values for BtCursor.eState.
12536 **
12537 ** CURSOR_VALID:
12538 **   Cursor points to a valid entry. getPayload() etc. may be called.
12539 **
12540 ** CURSOR_INVALID:
12541 **   Cursor does not point to a valid entry. This can happen (for example) 
12542 **   because the table is empty or because BtreeCursorFirst() has not been
12543 **   called.
12544 **
12545 ** CURSOR_REQUIRESEEK:
12546 **   The table that this cursor was opened on still exists, but has been 
12547 **   modified since the cursor was last used. The cursor position is saved
12548 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
12549 **   this state, restoreCursorPosition() can be called to attempt to
12550 **   seek the cursor to the saved position.
12551 **
12552 ** CURSOR_FAULT:
12553 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
12554 **   on a different connection that shares the BtShared cache with this
12555 **   cursor.  The error has left the cache in an inconsistent state.
12556 **   Do nothing else with this cursor.  Any attempt to use the cursor
12557 **   should return the error code stored in BtCursor.skip
12558 */
12559 #define CURSOR_INVALID           0
12560 #define CURSOR_VALID             1
12561 #define CURSOR_REQUIRESEEK       2
12562 #define CURSOR_FAULT             3
12563
12564 /* 
12565 ** The database page the PENDING_BYTE occupies. This page is never used.
12566 */
12567 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
12568
12569 /*
12570 ** These macros define the location of the pointer-map entry for a 
12571 ** database page. The first argument to each is the number of usable
12572 ** bytes on each page of the database (often 1024). The second is the
12573 ** page number to look up in the pointer map.
12574 **
12575 ** PTRMAP_PAGENO returns the database page number of the pointer-map
12576 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
12577 ** the offset of the requested map entry.
12578 **
12579 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
12580 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
12581 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
12582 ** this test.
12583 */
12584 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
12585 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
12586 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
12587
12588 /*
12589 ** The pointer map is a lookup table that identifies the parent page for
12590 ** each child page in the database file.  The parent page is the page that
12591 ** contains a pointer to the child.  Every page in the database contains
12592 ** 0 or 1 parent pages.  (In this context 'database page' refers
12593 ** to any page that is not part of the pointer map itself.)  Each pointer map
12594 ** entry consists of a single byte 'type' and a 4 byte parent page number.
12595 ** The PTRMAP_XXX identifiers below are the valid types.
12596 **
12597 ** The purpose of the pointer map is to facility moving pages from one
12598 ** position in the file to another as part of autovacuum.  When a page
12599 ** is moved, the pointer in its parent must be updated to point to the
12600 ** new location.  The pointer map is used to locate the parent page quickly.
12601 **
12602 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
12603 **                  used in this case.
12604 **
12605 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
12606 **                  is not used in this case.
12607 **
12608 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
12609 **                   overflow pages. The page number identifies the page that
12610 **                   contains the cell with a pointer to this overflow page.
12611 **
12612 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
12613 **                   overflow pages. The page-number identifies the previous
12614 **                   page in the overflow page list.
12615 **
12616 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
12617 **               identifies the parent page in the btree.
12618 */
12619 #define PTRMAP_ROOTPAGE 1
12620 #define PTRMAP_FREEPAGE 2
12621 #define PTRMAP_OVERFLOW1 3
12622 #define PTRMAP_OVERFLOW2 4
12623 #define PTRMAP_BTREE 5
12624
12625 /* A bunch of assert() statements to check the transaction state variables
12626 ** of handle p (type Btree*) are internally consistent.
12627 */
12628 #define btreeIntegrity(p) \
12629   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
12630   assert( p->pBt->inTransaction>=p->inTrans ); 
12631
12632
12633 /*
12634 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
12635 ** if the database supports auto-vacuum or not. Because it is used
12636 ** within an expression that is an argument to another macro 
12637 ** (sqlcipherMallocRaw), it is not possible to use conditional compilation.
12638 ** So, this macro is defined instead.
12639 */
12640 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
12641 #define ISAUTOVACUUM (pBt->autoVacuum)
12642 #else
12643 #define ISAUTOVACUUM 0
12644 #endif
12645
12646
12647 /*
12648 ** This structure is passed around through all the sanity checking routines
12649 ** in order to keep track of some global state information.
12650 */
12651 typedef struct IntegrityCk IntegrityCk;
12652 struct IntegrityCk {
12653   BtShared *pBt;    /* The tree being checked out */
12654   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
12655   Pgno nPage;       /* Number of pages in the database */
12656   int *anRef;       /* Number of times each page is referenced */
12657   int mxErr;        /* Stop accumulating errors when this reaches zero */
12658   int nErr;         /* Number of messages written to zErrMsg so far */
12659   int mallocFailed; /* A memory allocation error has occurred */
12660   StrAccum errMsg;  /* Accumulate the error message text here */
12661 };
12662
12663 /*
12664 ** Read or write a two- and four-byte big-endian integer values.
12665 */
12666 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
12667 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
12668 #define get4byte sqlcipher3Get4byte
12669 #define put4byte sqlcipher3Put4byte
12670
12671 /************** End of btreeInt.h ********************************************/
12672 /************** Continuing where we left off in crypto.c *********************/
12673 /************** Include crypto.h in the middle of crypto.c *******************/
12674 /************** Begin file crypto.h ******************************************/
12675 /* 
12676 ** SQLCipher
12677 ** crypto.h developed by Stephen Lombardo (Zetetic LLC) 
12678 ** sjlombardo at zetetic dot net
12679 ** http://zetetic.net
12680 ** 
12681 ** Copyright (c) 2008, ZETETIC LLC
12682 ** All rights reserved.
12683 ** 
12684 ** Redistribution and use in source and binary forms, with or without
12685 ** modification, are permitted provided that the following conditions are met:
12686 **     * Redistributions of source code must retain the above copyright
12687 **       notice, this list of conditions and the following disclaimer.
12688 **     * Redistributions in binary form must reproduce the above copyright
12689 **       notice, this list of conditions and the following disclaimer in the
12690 **       documentation and/or other materials provided with the distribution.
12691 **     * Neither the name of the ZETETIC LLC nor the
12692 **       names of its contributors may be used to endorse or promote products
12693 **       derived from this software without specific prior written permission.
12694 ** 
12695 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
12696 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12697 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12698 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
12699 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
12700 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
12701 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
12702 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12703 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
12704 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12705 **  
12706 */
12707 /* BEGIN CRYPTO */
12708 #ifdef SQLCIPHER_HAS_CODEC
12709 #ifndef CRYPTO_H
12710 #define CRYPTO_H
12711
12712 #define FILE_HEADER_SZ 16
12713
12714 #ifndef CIPHER
12715 #define CIPHER "aes-256-cbc"
12716 #endif
12717
12718 #define CIPHER_DECRYPT 0
12719 #define CIPHER_ENCRYPT 1
12720
12721 #define CIPHER_READ_CTX 0
12722 #define CIPHER_WRITE_CTX 1
12723 #define CIPHER_READWRITE_CTX 2
12724
12725 #ifndef PBKDF2_ITER
12726 #define PBKDF2_ITER 4000
12727 #endif
12728
12729 #ifndef DEFAULT_USE_HMAC
12730 #define DEFAULT_USE_HMAC 1
12731 #endif
12732
12733 /* by default, sqlcipher will use a reduced number of iterations to generate
12734    the HMAC key / or transform a raw cipher key 
12735    */
12736 #ifndef FAST_PBKDF2_ITER
12737 #define FAST_PBKDF2_ITER 2
12738 #endif
12739
12740 /* this if a fixed random array that will be xor'd with the database salt to ensure that the
12741    salt passed to the HMAC key derivation function is not the same as that used to derive
12742    the encryption key. This can be overridden at compile time but it will make the resulting
12743    binary incompatible with the default builds when using HMAC. A future version of SQLcipher
12744    will likely allow this to be defined at runtime via pragma */ 
12745 #ifndef HMAC_SALT_MASK
12746 #define HMAC_SALT_MASK 0x3a
12747 #endif
12748
12749 #ifdef CODEC_DEBUG
12750 #define CODEC_TRACE(X)  {printf X;fflush(stdout);}
12751 #else
12752 #define CODEC_TRACE(X)
12753 #endif
12754
12755
12756 /* extensions defined in pragma.c */ 
12757    
12758 SQLCIPHER_PRIVATE void sqlcipher3pager_get_codec(Pager *pPager, void **ctx);
12759 SQLCIPHER_PRIVATE int sqlcipher3pager_is_mj_pgno(Pager *pPager, Pgno pgno);
12760 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3Pager_get_fd(Pager *pPager);
12761 SQLCIPHER_PRIVATE void sqlcipher3pager_sqlcipher3PagerSetCodec(
12762   Pager *pPager,
12763   void *(*xCodec)(void*,void*,Pgno,int),
12764   void (*xCodecSizeChng)(void*,int,int),
12765   void (*xCodecFree)(void*),
12766   void *pCodec
12767 );
12768 /* end extensions defined in pragma.c */
12769  
12770 /*
12771 **  Simple shared routines for converting hex char strings to binary data
12772  */
12773 static int cipher_hex2int(char c) {
12774   return (c>='0' && c<='9') ? (c)-'0' :
12775          (c>='A' && c<='F') ? (c)-'A'+10 :
12776          (c>='a' && c<='f') ? (c)-'a'+10 : 0;
12777 }
12778
12779 static void cipher_hex2bin(const char *hex, int sz, unsigned char *out){
12780   int i;
12781   for(i = 0; i < sz; i += 2){
12782     out[i/2] = (cipher_hex2int(hex[i])<<4) | cipher_hex2int(hex[i+1]);
12783   }
12784 }
12785
12786 /* extensions defined in crypto_impl.c */
12787
12788 typedef struct codec_ctx codec_ctx;
12789
12790 /* utility functions */
12791 int sqlcipher_memcmp(const unsigned char *a0, const unsigned char *a1, int len);
12792 int sqlcipher_pseudorandom(void *, int);
12793 void sqlcipher_free(void *, int);
12794
12795 /* activation and initialization */
12796 void sqlcipher_activate();
12797 int sqlcipher_codec_ctx_init(codec_ctx **, Db *, Pager *, sqlcipher3_file *, const void *, int);
12798 void sqlcipher_codec_ctx_free(codec_ctx **);
12799 int sqlcipher_codec_key_derive(codec_ctx *);
12800 int sqlcipher_codec_key_copy(codec_ctx *, int);
12801
12802 /* page cipher implementation */
12803 int sqlcipher_page_cipher(codec_ctx *, int, Pgno, int, int, unsigned char *, unsigned char *);
12804
12805 /* context setters & getters */
12806 void sqlcipher_codec_ctx_set_error(codec_ctx *, int);
12807
12808 int sqlcipher_codec_ctx_set_pass(codec_ctx *, const void *, int, int);
12809 void sqlcipher_codec_get_pass(codec_ctx *, void **zKey, int *nKey);
12810
12811 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *, int);
12812 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *);
12813 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *);
12814
12815 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *, int, int);
12816 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx);
12817
12818 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *, int, int);
12819
12820 int sqlcipher_codec_ctx_set_cipher(codec_ctx *, const char *, int);
12821
12822 void* sqlcipher_codec_ctx_get_data(codec_ctx *);
12823
12824 void sqlcipher_exportFunc(sqlcipher3_context *, int, sqlcipher3_value **);
12825
12826 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use);
12827 /* end extensions defined in crypto_impl.c */
12828
12829 #endif
12830 #endif
12831 /* END CRYPTO */
12832
12833 /************** End of crypto.h **********************************************/
12834 /************** Continuing where we left off in crypto.c *********************/
12835
12836 int codec_set_kdf_iter(sqlcipher3* db, int nDb, int kdf_iter, int for_ctx) {
12837   struct Db *pDb = &db->aDb[nDb];
12838   CODEC_TRACE(("codec_set_kdf_iter: entered db=%d nDb=%d kdf_iter=%d for_ctx=%d\n", db, nDb, kdf_iter, for_ctx));
12839
12840   if(pDb->pBt) {
12841     codec_ctx *ctx;
12842     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12843     if(ctx) return sqlcipher_codec_ctx_set_kdf_iter(ctx, kdf_iter, for_ctx);
12844   }
12845   return SQLCIPHER_ERROR;
12846 }
12847
12848 int codec_set_fast_kdf_iter(sqlcipher3* db, int nDb, int kdf_iter, int for_ctx) {
12849   struct Db *pDb = &db->aDb[nDb];
12850   CODEC_TRACE(("codec_set_kdf_iter: entered db=%d nDb=%d kdf_iter=%d for_ctx=%d\n", db, nDb, kdf_iter, for_ctx));
12851
12852   if(pDb->pBt) {
12853     codec_ctx *ctx;
12854     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12855     if(ctx) return sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, kdf_iter, for_ctx);
12856   }
12857   return SQLCIPHER_ERROR;
12858 }
12859
12860 static int codec_set_btree_to_codec_pagesize(sqlcipher3 *db, Db *pDb, codec_ctx *ctx) {
12861   int rc, page_sz, reserve_sz; 
12862
12863   page_sz = sqlcipher_codec_ctx_get_pagesize(ctx);
12864   reserve_sz = sqlcipher_codec_ctx_get_reservesize(ctx);
12865
12866   sqlcipher3_mutex_enter(db->mutex);
12867   db->nextPagesize = page_sz; 
12868   pDb->pBt->pBt->pageSizeFixed = 0; 
12869   CODEC_TRACE(("codec_set_btree_to_codec_pagesize: sqlcipher3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz));
12870   rc = sqlcipher3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0);
12871   sqlcipher3_mutex_leave(db->mutex);
12872   return rc;
12873 }
12874
12875 int codec_set_use_hmac(sqlcipher3* db, int nDb, int use) {
12876   struct Db *pDb = &db->aDb[nDb];
12877
12878   CODEC_TRACE(("codec_set_use_hmac: entered db=%d nDb=%d use=%d\n", db, nDb, use));
12879
12880   if(pDb->pBt) {
12881     int rc;
12882     codec_ctx *ctx;
12883     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12884     if(ctx) {
12885       rc = sqlcipher_codec_ctx_set_use_hmac(ctx, use);
12886       if(rc != SQLCIPHER_OK) return rc;
12887       /* since the use of hmac has changed, the page size may also change */
12888       /* Note: before forcing the page size we need to force pageSizeFixed to 0, else  
12889              sqlcipherBtreeSetPageSize will block the change  */
12890       return codec_set_btree_to_codec_pagesize(db, pDb, ctx);
12891     }
12892   }
12893   return SQLCIPHER_ERROR;
12894 }
12895
12896 int codec_set_page_size(sqlcipher3* db, int nDb, int size) {
12897   struct Db *pDb = &db->aDb[nDb];
12898   CODEC_TRACE(("codec_set_page_size: entered db=%d nDb=%d size=%d\n", db, nDb, size));
12899
12900   if(pDb->pBt) {
12901     int rc;
12902     codec_ctx *ctx;
12903     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12904
12905     if(ctx) {
12906       rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
12907       if(rc != SQLCIPHER_OK) return rc;
12908       return codec_set_btree_to_codec_pagesize(db, pDb, ctx);
12909     }
12910   }
12911   return SQLCIPHER_ERROR;
12912 }
12913
12914 /**
12915   * 
12916   * when for_ctx == 0 then it will change for read
12917   * when for_ctx == 1 then it will change for write
12918   * when for_ctx == 2 then it will change for both
12919   */
12920 int codec_set_cipher_name(sqlcipher3* db, int nDb, const char *cipher_name, int for_ctx) {
12921   struct Db *pDb = &db->aDb[nDb];
12922   CODEC_TRACE(("codec_set_cipher_name: entered db=%d nDb=%d cipher_name=%s for_ctx=%d\n", db, nDb, cipher_name, for_ctx));
12923
12924   if(pDb->pBt) {
12925     codec_ctx *ctx;
12926     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12927     if(ctx) return sqlcipher_codec_ctx_set_cipher(ctx, cipher_name, for_ctx);
12928   }
12929   return SQLCIPHER_ERROR;
12930 }
12931
12932 int codec_set_pass_key(sqlcipher3* db, int nDb, const void *zKey, int nKey, int for_ctx) {
12933   struct Db *pDb = &db->aDb[nDb];
12934   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));
12935   if(pDb->pBt) {
12936     codec_ctx *ctx;
12937     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
12938     if(ctx) return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx);
12939   }
12940   return SQLCIPHER_ERROR;
12941
12942
12943 /*
12944  * sqlcipher3Codec can be called in multiple modes.
12945  * encrypt mode - expected to return a pointer to the 
12946  *   encrypted data without altering pData.
12947  * decrypt mode - expected to return a pointer to pData, with
12948  *   the data decrypted in the input buffer
12949  */
12950 void* sqlcipher3Codec(void *iCtx, void *data, Pgno pgno, int mode) {
12951   codec_ctx *ctx = (codec_ctx *) iCtx;
12952   int offset = 0, rc = 0;
12953   int page_sz = sqlcipher_codec_ctx_get_pagesize(ctx); 
12954   unsigned char *pData = (unsigned char *) data;
12955   void *buffer = sqlcipher_codec_ctx_get_data(ctx);
12956   void *kdf_salt = sqlcipher_codec_ctx_get_kdf_salt(ctx);
12957   CODEC_TRACE(("sqlcipher3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz));
12958
12959   /* call to derive keys if not present yet */
12960   if((rc = sqlcipher_codec_key_derive(ctx)) != SQLCIPHER_OK) {
12961    sqlcipher_codec_ctx_set_error(ctx, rc); 
12962    return NULL;
12963   }
12964
12965   if(pgno == 1) offset = FILE_HEADER_SZ; /* adjust starting pointers in data page for header offset on first page*/
12966
12967   CODEC_TRACE(("sqlcipher3Codec: switch mode=%d offset=%d\n",  mode, offset));
12968   switch(mode) {
12969     case 0: /* decrypt */
12970     case 2:
12971     case 3:
12972       if(pgno == 1) memcpy(buffer, SQLCIPHER_FILE_HEADER, FILE_HEADER_SZ); /* copy file header to the first 16 bytes of the page */ 
12973       rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
12974       if(rc != SQLCIPHER_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
12975       memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */
12976       return pData;
12977       break;
12978     case 6: /* encrypt */
12979       if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ 
12980       rc = sqlcipher_page_cipher(ctx, CIPHER_WRITE_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
12981       if(rc != SQLCIPHER_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
12982       return buffer; /* return persistent buffer data, pData remains intact */
12983       break;
12984     case 7:
12985       if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ 
12986       rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
12987       if(rc != SQLCIPHER_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
12988       return buffer; /* return persistent buffer data, pData remains intact */
12989       break;
12990     default:
12991       return pData;
12992       break;
12993   }
12994 }
12995
12996 SQLCIPHER_PRIVATE void sqlcipher3FreeCodecArg(void *pCodecArg) {
12997   codec_ctx *ctx = (codec_ctx *) pCodecArg;
12998   if(pCodecArg == NULL) return;
12999   sqlcipher_codec_ctx_free(&ctx); // wipe and free allocated memory for the context 
13000 }
13001
13002 SQLCIPHER_PRIVATE int sqlcipher3CodecAttach(sqlcipher3* db, int nDb, const void *zKey, int nKey) {
13003   struct Db *pDb = &db->aDb[nDb];
13004
13005   CODEC_TRACE(("sqlcipher3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey));
13006
13007   sqlcipher_activate();
13008
13009   if(nKey && zKey && pDb->pBt) {
13010     Pager *pPager = pDb->pBt->pBt->pPager;
13011     sqlcipher3_file *fd = sqlcipher3Pager_get_fd(pPager);
13012     codec_ctx *ctx;
13013
13014     /* point the internal codec argument against the contet to be prepared */
13015     sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, fd, zKey, nKey); 
13016
13017     sqlcipher3pager_sqlcipher3PagerSetCodec(sqlcipher3BtreePager(pDb->pBt), sqlcipher3Codec, NULL, sqlcipher3FreeCodecArg, (void *) ctx);
13018
13019     codec_set_btree_to_codec_pagesize(db, pDb, ctx);
13020
13021     /* if fd is null, then this is an in-memory database and
13022        we dont' want to overwrite the AutoVacuum settings
13023        if not null, then set to the default */
13024     sqlcipher3_mutex_enter(db->mutex);
13025     if(fd != NULL) { 
13026       sqlcipher3BtreeSetAutoVacuum(pDb->pBt, SQLCIPHER_DEFAULT_AUTOVACUUM);
13027     }
13028     sqlcipher3_mutex_leave(db->mutex);
13029   }
13030   return SQLCIPHER_OK;
13031 }
13032
13033 SQLCIPHER_API void sqlcipher3_activate_see(const char* in) {
13034     (void) in;
13035   /* do nothing, security enhancements are always active */
13036 }
13037
13038 SQLCIPHER_API int sqlcipher3_key(sqlcipher3 *db, const void *pKey, int nKey) {
13039   CODEC_TRACE(("sqlcipher3_key: entered db=%d pKey=%s nKey=%d\n", db, pKey, nKey));
13040   /* attach key if db and pKey are not null and nKey is > 0 */
13041   if(db && pKey && nKey) {
13042     sqlcipher3CodecAttach(db, 0, pKey, nKey); // operate only on the main db 
13043     return SQLCIPHER_OK;
13044   }
13045   return SQLCIPHER_ERROR;
13046 }
13047
13048 /* sqlcipher3_rekey 
13049 ** Given a database, this will reencrypt the database using a new key.
13050 ** There is only one possible modes of operation - to encrypt a database
13051 ** that is already encrpyted. If the database is not already encrypted
13052 ** this should do nothing
13053 ** The proposed logic for this function follows:
13054 ** 1. Determine if the database is already encryptped
13055 ** 2. If there is NOT already a key present do nothing
13056 ** 3. If there is a key present, re-encrypt the database with the new key
13057 */
13058 SQLCIPHER_API int sqlcipher3_rekey(sqlcipher3 *db, const void *pKey, int nKey) {
13059   CODEC_TRACE(("sqlcipher3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey));
13060   sqlcipher_activate();
13061   if(db && pKey && nKey) {
13062     struct Db *pDb = &db->aDb[0];
13063     CODEC_TRACE(("sqlcipher3_rekey: database pDb=%d\n", pDb));
13064     if(pDb->pBt) {
13065       codec_ctx *ctx;
13066       int rc, page_count;
13067       Pgno pgno;
13068       PgHdr *page;
13069       Pager *pPager = pDb->pBt->pBt->pPager;
13070
13071       sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13072      
13073       if(ctx == NULL) { 
13074         /* there was no codec attached to this database, so this should do nothing! */ 
13075         CODEC_TRACE(("sqlcipher3_rekey: no codec attached to db, exiting\n"));
13076         return SQLCIPHER_OK;
13077       }
13078
13079       sqlcipher3_mutex_enter(db->mutex);
13080
13081       codec_set_pass_key(db, 0, pKey, nKey, CIPHER_WRITE_CTX);
13082     
13083       /* do stuff here to rewrite the database 
13084       ** 1. Create a transaction on the database
13085       ** 2. Iterate through each page, reading it and then writing it.
13086       ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
13087       **    note: don't deallocate rekey since it may be used in a subsequent iteration 
13088       */
13089       rc = sqlcipher3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */
13090       sqlcipher3PagerPagecount(pPager, &page_count);
13091       for(pgno = 1; rc == SQLCIPHER_OK && (int)pgno <= page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
13092         if(!sqlcipher3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
13093           rc = sqlcipher3PagerGet(pPager, pgno, &page);
13094           if(rc == SQLCIPHER_OK) { /* write page see pager_incr_changecounter for example */
13095             rc = sqlcipher3PagerWrite(page);
13096             //printf("sqlcipher3PagerWrite(%d)\n", pgno);
13097             if(rc == SQLCIPHER_OK) {
13098               sqlcipher3PagerUnref(page);
13099             } 
13100           } 
13101         } 
13102       }
13103
13104       /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
13105       if(rc == SQLCIPHER_OK) { 
13106         CODEC_TRACE(("sqlcipher3_rekey: committing\n"));
13107         rc = sqlcipher3BtreeCommit(pDb->pBt); 
13108         sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
13109       } else {
13110         CODEC_TRACE(("sqlcipher3_rekey: rollback\n"));
13111         sqlcipher3BtreeRollback(pDb->pBt);
13112       }
13113
13114       sqlcipher3_mutex_leave(db->mutex);
13115     }
13116     return SQLCIPHER_OK;
13117   }
13118   return SQLCIPHER_ERROR;
13119 }
13120
13121 SQLCIPHER_PRIVATE void sqlcipher3CodecGetKey(sqlcipher3* db, int nDb, void **zKey, int *nKey) {
13122   struct Db *pDb = &db->aDb[nDb];
13123   CODEC_TRACE(("sqlcipher3CodecGetKey: entered db=%d, nDb=%d\n", db, nDb));
13124   
13125   if( pDb->pBt ) {
13126     codec_ctx *ctx;
13127     sqlcipher3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13128
13129     if(ctx) { /* if the codec has an attached codec_context user the raw key data */
13130       sqlcipher_codec_get_pass(ctx, zKey, nKey);
13131     } else {
13132       *zKey = NULL;
13133       *nKey = 0;
13134     }
13135   }
13136 }
13137
13138
13139 /* END CRYPTO */
13140 #endif
13141
13142 /************** End of crypto.c **********************************************/
13143 /************** Begin file crypto_impl.c *************************************/
13144 /* 
13145 ** SQLCipher
13146 ** crypto_impl.c developed by Stephen Lombardo (Zetetic LLC) 
13147 ** sjlombardo at zetetic dot net
13148 ** http://zetetic.net
13149 ** 
13150 ** Copyright (c) 2011, ZETETIC LLC
13151 ** All rights reserved.
13152 ** 
13153 ** Redistribution and use in source and binary forms, with or without
13154 ** modification, are permitted provided that the following conditions are met:
13155 **     * Redistributions of source code must retain the above copyright
13156 **       notice, this list of conditions and the following disclaimer.
13157 **     * Redistributions in binary form must reproduce the above copyright
13158 **       notice, this list of conditions and the following disclaimer in the
13159 **       documentation and/or other materials provided with the distribution.
13160 **     * Neither the name of the ZETETIC LLC nor the
13161 **       names of its contributors may be used to endorse or promote products
13162 **       derived from this software without specific prior written permission.
13163 ** 
13164 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
13165 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
13166 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13167 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
13168 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
13169 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
13170 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
13171 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13172 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
13173 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13174 **  
13175 */
13176 /* BEGIN CRYPTO */
13177 #ifdef SQLCIPHER_HAS_CODEC
13178
13179 #include <openssl/rand.h>
13180 #include <openssl/evp.h>
13181 #include <openssl/hmac.h>
13182 #ifndef OMIT_MEMLOCK
13183 #if defined(__unix__) || defined(__APPLE__) 
13184 #include <sys/mman.h>
13185 #elif defined(_WIN32)
13186 /* # include <windows.h> */
13187 #endif
13188 #endif
13189
13190 /* the default implementation of SQLCipher uses a cipher_ctx
13191    to keep track of read / write state separately. The following
13192    struct and associated functions are defined here */
13193 typedef struct {
13194   int derive_key;
13195   EVP_CIPHER *evp_cipher;
13196   EVP_CIPHER_CTX *ectx;
13197   HMAC_CTX *hctx;
13198   int kdf_iter;
13199   int fast_kdf_iter;
13200   int key_sz;
13201   int iv_sz;
13202   int block_sz;
13203   int pass_sz;
13204   int reserve_sz;
13205   int hmac_sz;
13206   int use_hmac;
13207   unsigned char *key;
13208   unsigned char *hmac_key;
13209   char *pass;
13210 } cipher_ctx;
13211
13212 void sqlcipher_cipher_ctx_free(cipher_ctx **);
13213 int sqlcipher_cipher_ctx_cmp(cipher_ctx *, cipher_ctx *);
13214 int sqlcipher_cipher_ctx_copy(cipher_ctx *, cipher_ctx *);
13215 int sqlcipher_cipher_ctx_init(cipher_ctx **);
13216 int sqlcipher_cipher_ctx_set_pass(cipher_ctx *, const void *, int);
13217 int sqlcipher_cipher_ctx_key_derive(codec_ctx *, cipher_ctx *);
13218
13219 /* prototype for pager HMAC function */
13220 int sqlcipher_page_hmac(cipher_ctx *, Pgno, unsigned char *, int, unsigned char *);
13221
13222 struct codec_ctx {
13223   int kdf_salt_sz;
13224   int page_sz;
13225   unsigned char *kdf_salt;
13226   unsigned char *hmac_kdf_salt;
13227   unsigned char *buffer;
13228   Btree *pBt;
13229   cipher_ctx *read_ctx;
13230   cipher_ctx *write_ctx;
13231 };
13232
13233 void sqlcipher_activate() {
13234   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
13235   if(EVP_get_cipherbyname(CIPHER) == NULL) {
13236     OpenSSL_add_all_algorithms();
13237   } 
13238   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
13239 }
13240
13241 /* fixed time memory comparison routine */
13242 int sqlcipher_memcmp(const unsigned char *a0, const unsigned char *a1, int len) {
13243   int i = 0, noMatch = 0;
13244
13245   for(i = 0; i < len; i++) {
13246     noMatch = (noMatch || (a0[i] != a1[i]));
13247   }
13248   
13249   return noMatch;
13250 }
13251
13252 /* generate a defined number of pseudorandom bytes */
13253 int sqlcipher_random (void *buffer, int length) {
13254   return RAND_bytes((unsigned char *)buffer, length);
13255 }
13256
13257 /**
13258   * Free and wipe memory. Uses SQLites internal sqlcipher3_free so that memory
13259   * can be countend and memory leak detection works in the tet suite. 
13260   * If ptr is not null memory will be freed. 
13261   * If sz is greater than zero, the memory will be overwritten with zero before it is freed
13262   * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the
13263   * memory segment so it can be paged
13264   */
13265 void sqlcipher_free(void *ptr, int sz) {
13266   if(ptr) {
13267     if(sz > 0) {
13268       memset(ptr, 0, sz);
13269 #ifndef OMIT_MEMLOCK
13270 #if defined(__unix__) || defined(__APPLE__) 
13271       munlock(ptr, sz);
13272 #elif defined(_WIN32)
13273       VirtualUnlock(ptr, sz);
13274 #endif
13275 #endif
13276     }
13277     sqlcipher3_free(ptr);
13278   }
13279 }
13280
13281 /**
13282   * allocate memory. Uses sqlcipher's internall malloc wrapper so memory can be 
13283   * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK
13284   * attempts to lock the memory pages so sensitive information won't be swapped
13285   */
13286 void* sqlcipher_malloc(int sz) {
13287   void *ptr = sqlcipher3Malloc(sz);
13288 #ifndef OMIT_MEMLOCK
13289   if(ptr) {
13290 #if defined(__unix__) || defined(__APPLE__) 
13291     mlock(ptr, sz);
13292 #elif defined(_WIN32)
13293     VirtualLock(ptr, sz);
13294 #endif
13295   }
13296 #endif
13297   return ptr;
13298 }
13299
13300
13301 /**
13302   * Initialize a a new cipher_ctx struct. This function will allocate memory
13303   * for the cipher context and for the key
13304   * 
13305   * returns SQLCIPHER_OK if initialization was successful
13306   * returns SQLCIPHER_NOMEM if an error occured allocating memory
13307   */
13308 int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) {
13309   cipher_ctx *ctx;
13310   *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx));
13311   ctx = *iCtx;
13312   if(ctx == NULL) return SQLCIPHER_NOMEM;
13313   memset(ctx, 0, sizeof(cipher_ctx)); 
13314   ctx->key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH);
13315   ctx->hmac_key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH);
13316   if(ctx->key == NULL) return SQLCIPHER_NOMEM;
13317   if(ctx->hmac_key == NULL) return SQLCIPHER_NOMEM;
13318   return SQLCIPHER_OK;
13319 }
13320
13321 /**
13322   * Free and wipe memory associated with a cipher_ctx
13323   */
13324 void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) {
13325   cipher_ctx *ctx = *iCtx;
13326   CODEC_TRACE(("cipher_ctx_free: entered iCtx=%d\n", iCtx));
13327   sqlcipher_free(ctx->key, ctx->key_sz);
13328   sqlcipher_free(ctx->hmac_key, ctx->key_sz);
13329   sqlcipher_free(ctx->pass, ctx->pass_sz);
13330   sqlcipher_free(ctx, sizeof(cipher_ctx)); 
13331 }
13332
13333 /**
13334   * Compare one cipher_ctx to another.
13335   *
13336   * returns 0 if all the parameters (except the derived key data) are the same
13337   * returns 1 otherwise
13338   */
13339 int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) {
13340   CODEC_TRACE(("sqlcipher_cipher_ctx_cmp: entered c1=%d c2=%d\n", c1, c2));
13341
13342   if(
13343     c1->evp_cipher == c2->evp_cipher
13344     && c1->iv_sz == c2->iv_sz
13345     && c1->kdf_iter == c2->kdf_iter
13346     && c1->fast_kdf_iter == c2->fast_kdf_iter
13347     && c1->key_sz == c2->key_sz
13348     && c1->pass_sz == c2->pass_sz
13349     && (
13350       c1->pass == c2->pass
13351       || !sqlcipher_memcmp((const unsigned char*)c1->pass,
13352                            (const unsigned char*)c2->pass,
13353                            c1->pass_sz)
13354     ) 
13355   ) return 0;
13356   return 1;
13357 }
13358
13359 /**
13360   * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a 
13361   * fully initialized context, you could copy it to write_ctx and all yet data
13362   * and pass information across
13363   *
13364   * returns SQLCIPHER_OK if initialization was successful
13365   * returns SQLCIPHER_NOMEM if an error occured allocating memory
13366   */
13367 int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) {
13368   void *key = target->key; 
13369   void *hmac_key = target->hmac_key; 
13370
13371   CODEC_TRACE(("sqlcipher_cipher_ctx_copy: entered target=%d, source=%d\n", target, source));
13372   sqlcipher_free(target->pass, target->pass_sz); 
13373   memcpy(target, source, sizeof(cipher_ctx));
13374   
13375   target->key = key; //restore pointer to previously allocated key data
13376   memcpy(target->key, source->key, EVP_MAX_KEY_LENGTH);
13377
13378   target->hmac_key = hmac_key; //restore pointer to previously allocated hmac key data
13379   memcpy(target->hmac_key, source->hmac_key, EVP_MAX_KEY_LENGTH);
13380
13381   target->pass = sqlcipher_malloc(source->pass_sz);
13382   if(target->pass == NULL) return SQLCIPHER_NOMEM;
13383   memcpy(target->pass, source->pass, source->pass_sz);
13384
13385   return SQLCIPHER_OK;
13386 }
13387
13388
13389 /**
13390   * Set the raw password / key data for a cipher context
13391   * 
13392   * returns SQLCIPHER_OK if assignment was successfull
13393   * returns SQLCIPHER_NOMEM if an error occured allocating memory
13394   * returns SQLCIPHER_ERROR if the key couldn't be set because the pass was null or size was zero
13395   */
13396 int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) {
13397   sqlcipher_free(ctx->pass, ctx->pass_sz);
13398   ctx->pass_sz = nKey;
13399   if(zKey && nKey) {
13400     ctx->pass = sqlcipher_malloc(nKey);
13401     if(ctx->pass == NULL) return SQLCIPHER_NOMEM;
13402     memcpy(ctx->pass, zKey, nKey);
13403     return SQLCIPHER_OK;
13404   }
13405   return SQLCIPHER_ERROR;
13406 }
13407
13408 int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) {
13409   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13410   int rc;
13411
13412   if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLCIPHER_OK) return rc; 
13413   c_ctx->derive_key = 1;
13414
13415   if(for_ctx == 2)
13416     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK) 
13417       return rc; 
13418
13419   return SQLCIPHER_OK;
13420
13421
13422 int sqlcipher_codec_ctx_set_cipher(codec_ctx *ctx, const char *cipher_name, int for_ctx) {
13423   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13424   int rc;
13425
13426   c_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name);
13427   c_ctx->key_sz = EVP_CIPHER_key_length(c_ctx->evp_cipher);
13428   c_ctx->iv_sz = EVP_CIPHER_iv_length(c_ctx->evp_cipher);
13429   c_ctx->block_sz = EVP_CIPHER_block_size(c_ctx->evp_cipher);
13430   c_ctx->hmac_sz = EVP_MD_size(EVP_sha1());
13431   c_ctx->derive_key = 1;
13432
13433   if(for_ctx == 2)
13434     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK)
13435       return rc; 
13436
13437   return SQLCIPHER_OK;
13438 }
13439
13440 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter, int for_ctx) {
13441   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13442   int rc;
13443
13444   c_ctx->kdf_iter = kdf_iter;
13445   c_ctx->derive_key = 1;
13446
13447   if(for_ctx == 2)
13448     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK)
13449       return rc; 
13450
13451   return SQLCIPHER_OK;
13452 }
13453
13454 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter, int for_ctx) {
13455   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13456   int rc;
13457
13458   c_ctx->fast_kdf_iter = fast_kdf_iter;
13459   c_ctx->derive_key = 1;
13460
13461   if(for_ctx == 2)
13462     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLCIPHER_OK)
13463       return rc; 
13464
13465   return SQLCIPHER_OK;
13466 }
13467
13468
13469 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) {
13470   int reserve = EVP_MAX_IV_LENGTH; /* base reserve size will be IV only */ 
13471
13472   if(use) reserve += ctx->read_ctx->hmac_sz; /* if reserve will include hmac, update that size */
13473
13474   /* calculate the amount of reserve needed in even increments of the cipher block size */
13475
13476   reserve = ((reserve % ctx->read_ctx->block_sz) == 0) ? reserve :
13477                ((reserve / ctx->read_ctx->block_sz) + 1) * ctx->read_ctx->block_sz;  
13478
13479   CODEC_TRACE(("sqlcipher_codec_ctx_set_use_hmac: use=%d block_sz=%d md_size=%d reserve=%d\n", 
13480                 use, ctx->read_ctx->block_sz, ctx->read_ctx->hmac_sz, reserve)); 
13481
13482   ctx->write_ctx->use_hmac = ctx->read_ctx->use_hmac = use;
13483   ctx->write_ctx->reserve_sz = ctx->read_ctx->reserve_sz = reserve;
13484
13485   return SQLCIPHER_OK;
13486 }
13487
13488 void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
13489   ctx->pBt->db->errCode = error;
13490 }
13491
13492 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *ctx) {
13493   return ctx->page_sz;
13494 }
13495
13496 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) {
13497   return ctx->read_ctx->reserve_sz;
13498 }
13499
13500 void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) {
13501   return ctx->buffer;
13502 }
13503
13504 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx) {
13505   return ctx->kdf_salt;
13506 }
13507
13508 void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) {
13509   *zKey = ctx->read_ctx->pass;
13510   *nKey = ctx->read_ctx->pass_sz;
13511 }
13512
13513 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) {
13514   /* attempt to free the existing page buffer */
13515   sqlcipher_free(ctx->buffer,ctx->page_sz);
13516   ctx->page_sz = size;
13517
13518   /* pre-allocate a page buffer of PageSize bytes. This will
13519      be used as a persistent buffer for encryption and decryption 
13520      operations to avoid overhead of multiple memory allocations*/
13521   ctx->buffer = sqlcipher_malloc(size);
13522   if(ctx->buffer == NULL) return SQLCIPHER_NOMEM;
13523   memset(ctx->buffer, 0, size);
13524
13525   return SQLCIPHER_OK;
13526 }
13527
13528 int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlcipher3_file *fd, const void *zKey, int nKey) {
13529   int rc;
13530   codec_ctx *ctx;
13531   *iCtx = sqlcipher_malloc(sizeof(codec_ctx));
13532   ctx = *iCtx;
13533
13534   (void) pPager;
13535
13536   if(ctx == NULL) return SQLCIPHER_NOMEM;
13537
13538   memset(ctx, 0, sizeof(codec_ctx)); /* initialize all pointers and values to 0 */
13539   ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */
13540
13541   /* allocate space for salt data. Then read the first 16 bytes 
13542        directly off the database file. This is the salt for the
13543        key derivation function. If we get a short read allocate
13544        a new random salt value */
13545   ctx->kdf_salt_sz = FILE_HEADER_SZ;
13546   ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
13547   if(ctx->kdf_salt == NULL) return SQLCIPHER_NOMEM;
13548   memset(ctx->kdf_salt, 0, ctx->kdf_salt_sz);
13549
13550   /* allocate space for separate hmac salt data. We want the
13551      HMAC derivation salt to be different than the encryption
13552      key derivation salt */
13553   ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
13554   if(ctx->hmac_kdf_salt == NULL) return SQLCIPHER_NOMEM;
13555
13556
13557   /*
13558      Always overwrite page size and set to the default because the first page of the database
13559      in encrypted and thus sqlcipher can't effectively determine the pagesize. this causes an issue in 
13560      cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman
13561   */
13562   if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, SQLCIPHER_DEFAULT_PAGE_SIZE)) != SQLCIPHER_OK) return rc;
13563
13564   if((rc = sqlcipher_cipher_ctx_init(&ctx->read_ctx)) != SQLCIPHER_OK) return rc; 
13565   if((rc = sqlcipher_cipher_ctx_init(&ctx->write_ctx)) != SQLCIPHER_OK) return rc; 
13566
13567   if(fd == NULL || sqlcipher3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLCIPHER_OK) {
13568     /* if unable to read the bytes, generate random salt */
13569     if(sqlcipher_random(ctx->kdf_salt, FILE_HEADER_SZ) != 1) return SQLCIPHER_ERROR;
13570   }
13571
13572   if((rc = sqlcipher_codec_ctx_set_cipher(ctx, CIPHER, 0)) != SQLCIPHER_OK) return rc;
13573   if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, PBKDF2_ITER, 0)) != SQLCIPHER_OK) return rc;
13574   if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER, 0)) != SQLCIPHER_OK) return rc;
13575   if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLCIPHER_OK) return rc;
13576
13577   /* Use HMAC signatures by default. Note that codec_set_use_hmac will implicity call
13578      codec_set_page_size to set the default */
13579   if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, DEFAULT_USE_HMAC)) != SQLCIPHER_OK) return rc;
13580
13581   if((rc = sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx)) != SQLCIPHER_OK) return rc;
13582
13583   return SQLCIPHER_OK;
13584 }
13585
13586 /**
13587   * Free and wipe memory associated with a cipher_ctx, including the allocated
13588   * read_ctx and write_ctx.
13589   */
13590 void sqlcipher_codec_ctx_free(codec_ctx **iCtx) {
13591   codec_ctx *ctx = *iCtx;
13592   CODEC_TRACE(("codec_ctx_free: entered iCtx=%d\n", iCtx));
13593   sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz);
13594   sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz);
13595   sqlcipher_free(ctx->buffer, 0);
13596   sqlcipher_cipher_ctx_free(&ctx->read_ctx);
13597   sqlcipher_cipher_ctx_free(&ctx->write_ctx);
13598   sqlcipher_free(ctx, sizeof(codec_ctx)); 
13599 }
13600
13601
13602 #if OPENSSL_VERSION_NUMBER < 0x10100000L
13603 static HMAC_CTX *HMAC_CTX_new(void)
13604 {
13605   HMAC_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
13606   if (ctx != NULL) {
13607     HMAC_CTX_init(ctx);
13608   }
13609   return ctx;
13610 }
13611
13612 // Per 1.1.0 (https://wiki.openssl.org/index.php/1.1_API_Changes)
13613 // HMAC_CTX_free should call HMAC_CTX_cleanup, then EVP_MD_CTX_Cleanup.
13614 // HMAC_CTX_cleanup internally calls EVP_MD_CTX_cleanup so these
13615 // calls are not needed.
13616 static void HMAC_CTX_free(HMAC_CTX *ctx)
13617 {
13618   if (ctx != NULL) {
13619     HMAC_CTX_cleanup(ctx);
13620     OPENSSL_free(ctx);
13621   }
13622 }
13623 #endif
13624
13625 int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) {
13626   ctx->hctx = HMAC_CTX_new();
13627   if(ctx->hctx == NULL) return SQLCIPHER_NOMEM;
13628
13629   HMAC_Init_ex(ctx->hctx, ctx->hmac_key, ctx->key_sz, EVP_sha1(), NULL);
13630
13631   /* include the encrypted page data,  initialization vector, and page number in HMAC. This will 
13632      prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise
13633      valid pages out of order in a database */ 
13634   HMAC_Update(ctx->hctx, in, in_sz);
13635   HMAC_Update(ctx->hctx, (const unsigned char*) &pgno, sizeof(Pgno));
13636   HMAC_Final(ctx->hctx, out, NULL);
13637   HMAC_CTX_free(ctx->hctx);
13638   return SQLCIPHER_OK; 
13639 }
13640
13641 /*
13642  * ctx - codec context
13643  * pgno - page number in database
13644  * size - size in bytes of input and output buffers
13645  * mode - 1 to encrypt, 0 to decrypt
13646  * in - pointer to input bytes
13647  * out - pouter to output bytes
13648  */
13649 int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
13650   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
13651   unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
13652   int tmp_csz, csz, size;
13653
13654   /* calculate some required positions into various buffers */
13655   size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
13656   iv_out = out + size;
13657   iv_in = in + size;
13658
13659   /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
13660      random bytes. note, these pointers are only valid when use_hmac is true */
13661   hmac_in = in + size + c_ctx->iv_sz; 
13662   hmac_out = out + size + c_ctx->iv_sz;
13663   out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */
13664
13665   CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size));
13666
13667   /* just copy raw data from in to out when key size is 0
13668    * i.e. during a rekey of a plaintext database */ 
13669   if(c_ctx->key_sz == 0) {
13670     memcpy(out, in, size);
13671     return SQLCIPHER_OK;
13672   } 
13673
13674   if(mode == CIPHER_ENCRYPT) {
13675     /* start at front of the reserve block, write random data to the end */
13676     if(sqlcipher_random(iv_out, c_ctx->reserve_sz) != 1) return SQLCIPHER_ERROR; 
13677   } else { /* CIPHER_DECRYPT */
13678     memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */
13679   } 
13680
13681   if(c_ctx->use_hmac && (mode == CIPHER_DECRYPT)) {
13682     if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLCIPHER_OK) {
13683       memset(out, 0, page_sz); 
13684       CODEC_TRACE(("codec_cipher: hmac operations failed for pgno=%d\n", pgno));
13685       return SQLCIPHER_ERROR;
13686     }
13687
13688     CODEC_TRACE(("codec_cipher: comparing hmac on in=%d out=%d hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz));
13689     if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) {
13690       /* the hmac check failed, which means the data was tampered with or
13691          corrupted in some way. we will return an error, and zero out the page data
13692          to force an error */
13693       memset(out, 0, page_sz); 
13694       CODEC_TRACE(("codec_cipher: hmac check failed for pgno=%d\n", pgno));
13695       return SQLCIPHER_ERROR;
13696     }
13697   } 
13698
13699   c_ctx->ectx = EVP_CIPHER_CTX_new();
13700   if(c_ctx->ectx == NULL) return SQLCIPHER_NOMEM;
13701   EVP_CipherInit(c_ctx->ectx, c_ctx->evp_cipher, NULL, NULL, mode);
13702   EVP_CIPHER_CTX_set_padding(c_ctx->ectx, 0);
13703   EVP_CipherInit(c_ctx->ectx, NULL, c_ctx->key, iv_out, mode);
13704   EVP_CipherUpdate(c_ctx->ectx, out, &tmp_csz, in, size);
13705   csz = tmp_csz;  
13706   out += tmp_csz;
13707   EVP_CipherFinal(c_ctx->ectx, out, &tmp_csz);
13708   csz += tmp_csz;
13709   EVP_CIPHER_CTX_free(c_ctx->ectx);
13710   assert(size == csz);
13711
13712   if(c_ctx->use_hmac && (mode == CIPHER_ENCRYPT)) {
13713     sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out); 
13714   }
13715
13716   return SQLCIPHER_OK;
13717 }
13718
13719 /**
13720   * Derive an encryption key for a cipher contex key based on the raw password.
13721   *
13722   * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
13723   * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. 
13724   * 
13725   * Otherwise, a key data will be derived using PBKDF2
13726   * 
13727   * returns SQLCIPHER_OK if initialization was successful
13728   * returns SQLCIPHER_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
13729   */
13730 int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
13731   CODEC_TRACE(("codec_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \
13732                 ctx->kdf_salt=%d ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \
13733                 ctx->hmac_kdf_salt=%d, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n", 
13734                 c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, 
13735                 ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz)); 
13736                 
13737
13738   if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null
13739     if (c_ctx->pass_sz == ((c_ctx->key_sz*2)+3) && sqlcipher3StrNICmp(c_ctx->pass ,"x'", 2) == 0) { 
13740       int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
13741       const char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
13742       CODEC_TRACE(("codec_key_derive: using raw key from hex\n")); 
13743       cipher_hex2bin(z, n, c_ctx->key);
13744     } else { 
13745       CODEC_TRACE(("codec_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter)); 
13746       PKCS5_PBKDF2_HMAC_SHA1( c_ctx->pass, c_ctx->pass_sz, 
13747                               ctx->kdf_salt, ctx->kdf_salt_sz, 
13748                               c_ctx->kdf_iter, c_ctx->key_sz, c_ctx->key);
13749                               
13750     }
13751
13752     /* if this context is setup to use hmac checks, generate a seperate and different 
13753        key for HMAC. In this case, we use the output of the previous KDF as the input to 
13754        this KDF run. This ensures a distinct but predictable HMAC key. */
13755     if(c_ctx->use_hmac) {
13756       int i;
13757
13758       /* start by copying the kdf key into the hmac salt slot
13759          then XOR it with the fixed hmac salt defined at compile time
13760          this ensures that the salt passed in to derive the hmac key, while 
13761          easy to derive and publically known, is not the same as the salt used 
13762          to generate the encryption key */ 
13763       memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
13764       for(i = 0; i < ctx->kdf_salt_sz; i++) {
13765         ctx->hmac_kdf_salt[i] ^= HMAC_SALT_MASK;
13766       } 
13767
13768       CODEC_TRACE(("codec_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n", 
13769         c_ctx->fast_kdf_iter)); 
13770       PKCS5_PBKDF2_HMAC_SHA1( (const char*)c_ctx->key, c_ctx->key_sz, 
13771                               ctx->hmac_kdf_salt, ctx->kdf_salt_sz, 
13772                               c_ctx->fast_kdf_iter, c_ctx->key_sz, c_ctx->hmac_key); 
13773     }
13774
13775     c_ctx->derive_key = 0;
13776     return SQLCIPHER_OK;
13777   };
13778   return SQLCIPHER_ERROR;
13779 }
13780
13781 int sqlcipher_codec_key_derive(codec_ctx *ctx) {
13782   /* derive key on first use if necessary */
13783   if(ctx->read_ctx->derive_key) {
13784     if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLCIPHER_OK) return SQLCIPHER_ERROR;
13785   }
13786
13787   if(ctx->write_ctx->derive_key) {
13788     if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) {
13789       // the relevant parameters are the same, just copy read key
13790       if(sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx) != SQLCIPHER_OK) return SQLCIPHER_ERROR;
13791     } else {
13792       if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLCIPHER_OK) return SQLCIPHER_ERROR;
13793     }
13794   }
13795   return SQLCIPHER_OK; 
13796 }
13797
13798 int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) {
13799   if(source == CIPHER_READ_CTX) { 
13800       return sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx); 
13801   } else {
13802       return sqlcipher_cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx); 
13803   }
13804 }
13805
13806
13807 #ifndef OMIT_EXPORT
13808
13809 /*
13810  * Implementation of an "export" function that allows a caller
13811  * to duplicate the main database to an attached database. This is intended
13812  * as a conveneince for users who need to:
13813  * 
13814  *   1. migrate from an non-encrypted database to an encrypted database
13815  *   2. move from an encrypted database to a non-encrypted database
13816  *   3. convert beween the various flavors of encrypted databases.  
13817  *
13818  * This implementation is based heavily on the procedure and code used
13819  * in vacuum.c, but is exposed as a function that allows export to any
13820  * named attached database.
13821  */
13822
13823 /*
13824 ** Finalize a prepared statement.  If there was an error, store the
13825 ** text of the error message in *pzErrMsg.  Return the result code.
13826 ** 
13827 ** Based on vacuumFinalize from vacuum.c
13828 */
13829 static int sqlcipher_finalize(sqlcipher3 *db, sqlcipher3_stmt *pStmt, char **pzErrMsg){
13830   int rc;
13831   rc = sqlcipher3VdbeFinalize((Vdbe*)pStmt);
13832   if( rc ){
13833     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
13834   }
13835   return rc;
13836 }
13837
13838 /*
13839 ** Execute zSql on database db. Return an error code.
13840 ** 
13841 ** Based on execSql from vacuum.c
13842 */
13843 static int sqlcipher_execSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
13844   sqlcipher3_stmt *pStmt;
13845   VVA_ONLY( int rc; )
13846   if( !zSql ){
13847     return SQLCIPHER_NOMEM;
13848   }
13849   if( SQLCIPHER_OK!=sqlcipher3_prepare(db, zSql, -1, &pStmt, 0) ){
13850     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
13851     return sqlcipher3_errcode(db);
13852   }
13853   VVA_ONLY( rc = ) sqlcipher3_step(pStmt);
13854   assert( rc!=SQLCIPHER_ROW );
13855   return sqlcipher_finalize(db, pStmt, pzErrMsg);
13856 }
13857
13858 /*
13859 ** Execute zSql on database db. The statement returns exactly
13860 ** one column. Execute this as SQL on the same database.
13861 ** 
13862 ** Based on execExecSql from vacuum.c
13863 */
13864 static int sqlcipher_execExecSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
13865   sqlcipher3_stmt *pStmt;
13866   int rc;
13867
13868   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
13869   if( rc!=SQLCIPHER_OK ) return rc;
13870
13871   while( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
13872     rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlcipher3_column_text(pStmt, 0));
13873     if( rc!=SQLCIPHER_OK ){
13874       sqlcipher_finalize(db, pStmt, pzErrMsg);
13875       return rc;
13876     }
13877   }
13878
13879   return sqlcipher_finalize(db, pStmt, pzErrMsg);
13880 }
13881
13882 /*
13883  * copy database and schema from the main database to an attached database
13884  * 
13885  * Based on sqlcipher3RunVacuum from vacuum.c
13886 */
13887 void sqlcipher_exportFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv) {
13888   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
13889   const char* attachedDb = (const char*) sqlcipher3_value_text(argv[0]);
13890   int saved_flags;        /* Saved value of the db->flags */
13891   int saved_nChange;      /* Saved value of db->nChange */
13892   int saved_nTotalChange; /* Saved value of db->nTotalChange */
13893   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
13894   int rc = SQLCIPHER_OK;     /* Return code from service routines */
13895   char *zSql = NULL;         /* SQL statements */
13896   char *pzErrMsg = NULL;
13897
13898   (void) argc;
13899
13900   saved_flags = db->flags;
13901   saved_nChange = db->nChange;
13902   saved_nTotalChange = db->nTotalChange;
13903   saved_xTrace = db->xTrace;
13904   db->flags |= SQLCIPHER_WriteSchema | SQLCIPHER_IgnoreChecks | SQLCIPHER_PreferBuiltin;
13905   db->flags &= ~(SQLCIPHER_ForeignKeys | SQLCIPHER_ReverseOrder);
13906   db->xTrace = 0;
13907
13908   /* Query the schema of the main database. Create a mirror schema
13909   ** in the temporary database.
13910   */
13911   zSql = sqlcipher3_mprintf(
13912     "SELECT 'CREATE TABLE %s.' || substr(sql,14) "
13913     "  FROM sqlcipher_master WHERE type='table' AND name!='sqlcipher_sequence'"
13914     "   AND rootpage>0"
13915   , attachedDb);
13916   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13917   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13918   sqlcipher3_free(zSql);
13919
13920   zSql = sqlcipher3_mprintf(
13921     "SELECT 'CREATE INDEX %s.' || substr(sql,14)"
13922     "  FROM sqlcipher_master WHERE sql LIKE 'CREATE INDEX %%' "
13923   , attachedDb);
13924   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13925   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13926   sqlcipher3_free(zSql);
13927
13928   zSql = sqlcipher3_mprintf(
13929     "SELECT 'CREATE UNIQUE INDEX %s.' || substr(sql,21) "
13930     "  FROM sqlcipher_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'"
13931   , attachedDb);
13932   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13933   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13934   sqlcipher3_free(zSql);
13935
13936   /* Loop through the tables in the main database. For each, do
13937   ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy
13938   ** the contents to the temporary database.
13939   */
13940   zSql = sqlcipher3_mprintf(
13941     "SELECT 'INSERT INTO %s.' || quote(name) "
13942     "|| ' SELECT * FROM main.' || quote(name) || ';'"
13943     "FROM main.sqlcipher_master "
13944     "WHERE type = 'table' AND name!='sqlcipher_sequence' "
13945     "  AND rootpage>0"
13946   , attachedDb);
13947   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13948   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13949   sqlcipher3_free(zSql);
13950
13951   /* Copy over the sequence table
13952   */
13953   zSql = sqlcipher3_mprintf(
13954     "SELECT 'DELETE FROM %s.' || quote(name) || ';' "
13955     "FROM %s.sqlcipher_master WHERE name='sqlcipher_sequence' "
13956   , attachedDb, attachedDb);
13957   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13958   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13959   sqlcipher3_free(zSql);
13960
13961   zSql = sqlcipher3_mprintf(
13962     "SELECT 'INSERT INTO %s.' || quote(name) "
13963     "|| ' SELECT * FROM main.' || quote(name) || ';' "
13964     "FROM %s.sqlcipher_master WHERE name=='sqlcipher_sequence';"
13965   , attachedDb, attachedDb);
13966   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); 
13967   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13968   sqlcipher3_free(zSql);
13969
13970   /* Copy the triggers, views, and virtual tables from the main database
13971   ** over to the temporary database.  None of these objects has any
13972   ** associated storage, so all we have to do is copy their entries
13973   ** from the SQLCIPHER_MASTER table.
13974   */
13975   zSql = sqlcipher3_mprintf(
13976     "INSERT INTO %s.sqlcipher_master "
13977     "  SELECT type, name, tbl_name, rootpage, sql"
13978     "    FROM main.sqlcipher_master"
13979     "   WHERE type='view' OR type='trigger'"
13980     "      OR (type='table' AND rootpage=0)"
13981   , attachedDb);
13982   rc = (zSql == NULL) ? SQLCIPHER_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); 
13983   if( rc!=SQLCIPHER_OK ) goto end_of_export;
13984   sqlcipher3_free(zSql);
13985
13986   zSql = NULL;
13987 end_of_export:
13988   db->flags = saved_flags;
13989   db->nChange = saved_nChange;
13990   db->nTotalChange = saved_nTotalChange;
13991   db->xTrace = saved_xTrace;
13992
13993   sqlcipher3_free(zSql);
13994
13995   if(rc) {
13996     if(pzErrMsg != NULL) {
13997       sqlcipher3_result_error(context, pzErrMsg, -1);
13998       sqlcipher3DbFree(db, pzErrMsg);
13999     } else {
14000       sqlcipher3_result_error(context, sqlcipher3ErrStr(rc), -1);
14001     }
14002   }
14003 }
14004
14005 #endif
14006 #endif
14007
14008 /************** End of crypto_impl.c *****************************************/
14009 /************** Begin file global.c ******************************************/
14010 /*
14011 ** 2008 June 13
14012 **
14013 ** The author disclaims copyright to this source code.  In place of
14014 ** a legal notice, here is a blessing:
14015 **
14016 **    May you do good and not evil.
14017 **    May you find forgiveness for yourself and forgive others.
14018 **    May you share freely, never taking more than you give.
14019 **
14020 *************************************************************************
14021 **
14022 ** This file contains definitions of global variables and contants.
14023 */
14024
14025 /* An array to map all upper-case characters into their corresponding
14026 ** lower-case character. 
14027 **
14028 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
14029 ** handle case conversions for the UTF character set since the tables
14030 ** involved are nearly as big or bigger than SQLite itself.
14031 */
14032 SQLCIPHER_PRIVATE const unsigned char sqlcipher3UpperToLower[] = {
14033 #ifdef SQLCIPHER_ASCII
14034       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
14035      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
14036      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
14037      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
14038     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
14039     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
14040     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
14041     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
14042     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
14043     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
14044     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
14045     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
14046     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
14047     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
14048     252,253,254,255
14049 #endif
14050 #ifdef SQLCIPHER_EBCDIC
14051       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
14052      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
14053      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
14054      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
14055      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
14056      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
14057      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
14058     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
14059     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
14060     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
14061     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
14062     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
14063     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
14064     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
14065     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
14066     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
14067 #endif
14068 };
14069
14070 /*
14071 ** The following 256 byte lookup table is used to support SQLites built-in
14072 ** equivalents to the following standard library functions:
14073 **
14074 **   isspace()                        0x01
14075 **   isalpha()                        0x02
14076 **   isdigit()                        0x04
14077 **   isalnum()                        0x06
14078 **   isxdigit()                       0x08
14079 **   toupper()                        0x20
14080 **   SQLite identifier character      0x40
14081 **
14082 ** Bit 0x20 is set if the mapped character requires translation to upper
14083 ** case. i.e. if the character is a lower-case ASCII character.
14084 ** If x is a lower-case ASCII character, then its upper-case equivalent
14085 ** is (x - 0x20). Therefore toupper() can be implemented as:
14086 **
14087 **   (x & ~(map[x]&0x20))
14088 **
14089 ** Standard function tolower() is implemented using the sqlcipher3UpperToLower[]
14090 ** array. tolower() is used more often than toupper() by SQLite.
14091 **
14092 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
14093 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
14094 ** non-ASCII UTF character. Hence the test for whether or not a character is
14095 ** part of an identifier is 0x46.
14096 **
14097 ** SQLite's versions are identical to the standard versions assuming a
14098 ** locale of "C". They are implemented as macros in sqlcipherInt.h.
14099 */
14100 #ifdef SQLCIPHER_ASCII
14101 SQLCIPHER_PRIVATE const unsigned char sqlcipher3CtypeMap[256] = {
14102   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
14103   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
14104   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
14105   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
14106   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
14107   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
14108   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
14109   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
14110
14111   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
14112   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
14113   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
14114   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
14115   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
14116   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
14117   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
14118   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
14119
14120   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
14121   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
14122   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
14123   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
14124   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
14125   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
14126   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
14127   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
14128
14129   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
14130   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
14131   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
14132   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
14133   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
14134   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
14135   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
14136   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
14137 };
14138 #endif
14139
14140 #ifndef SQLCIPHER_USE_URI
14141 # define  SQLCIPHER_USE_URI 0
14142 #endif
14143
14144 /*
14145 ** The following singleton contains the global configuration for
14146 ** the SQLite library.
14147 */
14148 SQLCIPHER_PRIVATE SQLCIPHER_WSD struct Sqlite3Config sqlcipher3Config = {
14149    SQLCIPHER_DEFAULT_MEMSTATUS,  /* bMemstat */
14150    1,                         /* bCoreMutex */
14151    SQLCIPHER_THREADSAFE==1,      /* bFullMutex */
14152    SQLCIPHER_USE_URI,            /* bOpenUri */
14153    0x7ffffffe,                /* mxStrlen */
14154    128,                       /* szLookaside */
14155    500,                       /* nLookaside */
14156    {0,0,0,0,0,0,0,0},         /* m */
14157    {0,0,0,0,0,0,0,0,0},       /* mutex */
14158    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
14159    (void*)0,                  /* pHeap */
14160    0,                         /* nHeap */
14161    0, 0,                      /* mnHeap, mxHeap */
14162    (void*)0,                  /* pScratch */
14163    0,                         /* szScratch */
14164    0,                         /* nScratch */
14165    (void*)0,                  /* pPage */
14166    0,                         /* szPage */
14167    0,                         /* nPage */
14168    0,                         /* mxParserStack */
14169    0,                         /* sharedCacheEnabled */
14170    /* All the rest should always be initialized to zero */
14171    0,                         /* isInit */
14172    0,                         /* inProgress */
14173    0,                         /* isMutexInit */
14174    0,                         /* isMallocInit */
14175    0,                         /* isPCacheInit */
14176    0,                         /* pInitMutex */
14177    0,                         /* nRefInitMutex */
14178    0,                         /* xLog */
14179    0,                         /* pLogArg */
14180    0,                         /* bLocaltimeFault */
14181 };
14182
14183
14184 /*
14185 ** Hash table for global functions - functions common to all
14186 ** database connections.  After initialization, this table is
14187 ** read-only.
14188 */
14189 SQLCIPHER_PRIVATE SQLCIPHER_WSD FuncDefHash sqlcipher3GlobalFunctions;
14190
14191 /*
14192 ** Constant tokens for values 0 and 1.
14193 */
14194 SQLCIPHER_PRIVATE const Token sqlcipher3IntTokens[] = {
14195    { "0", 1 },
14196    { "1", 1 }
14197 };
14198
14199
14200 /*
14201 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
14202 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
14203 ** the database page that contains the pending byte.  It never attempts
14204 ** to read or write that page.  The pending byte page is set assign
14205 ** for use by the VFS layers as space for managing file locks.
14206 **
14207 ** During testing, it is often desirable to move the pending byte to
14208 ** a different position in the file.  This allows code that has to
14209 ** deal with the pending byte to run on files that are much smaller
14210 ** than 1 GiB.  The sqlcipher3_test_control() interface can be used to
14211 ** move the pending byte.
14212 **
14213 ** IMPORTANT:  Changing the pending byte to any value other than
14214 ** 0x40000000 results in an incompatible database file format!
14215 ** Changing the pending byte during operating results in undefined
14216 ** and dileterious behavior.
14217 */
14218 #ifndef SQLCIPHER_OMIT_WSD
14219 SQLCIPHER_PRIVATE int sqlcipher3PendingByte = 0x40000000;
14220 #endif
14221
14222 /*
14223 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
14224 ** created by mkopcodeh.awk during compilation.  Data is obtained
14225 ** from the comments following the "case OP_xxxx:" statements in
14226 ** the vdbe.c file.  
14227 */
14228 SQLCIPHER_PRIVATE const unsigned char sqlcipher3OpcodeProperty[] = OPFLG_INITIALIZER;
14229
14230 /************** End of global.c **********************************************/
14231 /************** Begin file ctime.c *******************************************/
14232 /*
14233 ** 2010 February 23
14234 **
14235 ** The author disclaims copyright to this source code.  In place of
14236 ** a legal notice, here is a blessing:
14237 **
14238 **    May you do good and not evil.
14239 **    May you find forgiveness for yourself and forgive others.
14240 **    May you share freely, never taking more than you give.
14241 **
14242 *************************************************************************
14243 **
14244 ** This file implements routines used to report what compile-time options
14245 ** SQLite was built with.
14246 */
14247
14248 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
14249
14250
14251 /*
14252 ** An array of names of all compile-time options.  This array should 
14253 ** be sorted A-Z.
14254 **
14255 ** This array looks large, but in a typical installation actually uses
14256 ** only a handful of compile-time options, so most times this array is usually
14257 ** rather short and uses little memory space.
14258 */
14259 static const char * const azCompileOpt[] = {
14260
14261 /* These macros are provided to "stringify" the value of the define
14262 ** for those options in which the value is meaningful. */
14263 #define CTIMEOPT_VAL_(opt) #opt
14264 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
14265
14266 #ifdef SQLCIPHER_32BIT_ROWID
14267   "32BIT_ROWID",
14268 #endif
14269 #ifdef SQLCIPHER_4_BYTE_ALIGNED_MALLOC
14270   "4_BYTE_ALIGNED_MALLOC",
14271 #endif
14272 #ifdef SQLCIPHER_CASE_SENSITIVE_LIKE
14273   "CASE_SENSITIVE_LIKE",
14274 #endif
14275 #ifdef SQLCIPHER_CHECK_PAGES
14276   "CHECK_PAGES",
14277 #endif
14278 #ifdef SQLCIPHER_COVERAGE_TEST
14279   "COVERAGE_TEST",
14280 #endif
14281 #ifdef SQLCIPHER_DEBUG
14282   "DEBUG",
14283 #endif
14284 #ifdef SQLCIPHER_DEFAULT_LOCKING_MODE
14285   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLCIPHER_DEFAULT_LOCKING_MODE),
14286 #endif
14287 #ifdef SQLCIPHER_DISABLE_DIRSYNC
14288   "DISABLE_DIRSYNC",
14289 #endif
14290 #ifdef SQLCIPHER_DISABLE_LFS
14291   "DISABLE_LFS",
14292 #endif
14293 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
14294   "ENABLE_ATOMIC_WRITE",
14295 #endif
14296 #ifdef SQLCIPHER_ENABLE_CEROD
14297   "ENABLE_CEROD",
14298 #endif
14299 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
14300   "ENABLE_COLUMN_METADATA",
14301 #endif
14302 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
14303   "ENABLE_EXPENSIVE_ASSERT",
14304 #endif
14305 #ifdef SQLCIPHER_ENABLE_FTS1
14306   "ENABLE_FTS1",
14307 #endif
14308 #ifdef SQLCIPHER_ENABLE_FTS2
14309   "ENABLE_FTS2",
14310 #endif
14311 #ifdef SQLCIPHER_ENABLE_FTS3
14312   "ENABLE_FTS3",
14313 #endif
14314 #ifdef SQLCIPHER_ENABLE_FTS3_PARENTHESIS
14315   "ENABLE_FTS3_PARENTHESIS",
14316 #endif
14317 #ifdef SQLCIPHER_ENABLE_FTS4
14318   "ENABLE_FTS4",
14319 #endif
14320 #ifdef SQLCIPHER_ENABLE_ICU
14321   "ENABLE_ICU",
14322 #endif
14323 #ifdef SQLCIPHER_ENABLE_IOTRACE
14324   "ENABLE_IOTRACE",
14325 #endif
14326 #ifdef SQLCIPHER_ENABLE_LOAD_EXTENSION
14327   "ENABLE_LOAD_EXTENSION",
14328 #endif
14329 #ifdef SQLCIPHER_ENABLE_LOCKING_STYLE
14330   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLCIPHER_ENABLE_LOCKING_STYLE),
14331 #endif
14332 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
14333   "ENABLE_MEMORY_MANAGEMENT",
14334 #endif
14335 #ifdef SQLCIPHER_ENABLE_MEMSYS3
14336   "ENABLE_MEMSYS3",
14337 #endif
14338 #ifdef SQLCIPHER_ENABLE_MEMSYS5
14339   "ENABLE_MEMSYS5",
14340 #endif
14341 #ifdef SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK
14342   "ENABLE_OVERSIZE_CELL_CHECK",
14343 #endif
14344 #ifdef SQLCIPHER_ENABLE_RTREE
14345   "ENABLE_RTREE",
14346 #endif
14347 #ifdef SQLCIPHER_ENABLE_STAT3
14348   "ENABLE_STAT3",
14349 #endif
14350 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
14351   "ENABLE_UNLOCK_NOTIFY",
14352 #endif
14353 #ifdef SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT
14354   "ENABLE_UPDATE_DELETE_LIMIT",
14355 #endif
14356 #ifdef SQLCIPHER_HAS_CODEC
14357   "HAS_CODEC",
14358 #endif
14359 #ifdef SQLCIPHER_HAVE_ISNAN
14360   "HAVE_ISNAN",
14361 #endif
14362 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
14363   "HOMEGROWN_RECURSIVE_MUTEX",
14364 #endif
14365 #ifdef SQLCIPHER_IGNORE_AFP_LOCK_ERRORS
14366   "IGNORE_AFP_LOCK_ERRORS",
14367 #endif
14368 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
14369   "IGNORE_FLOCK_LOCK_ERRORS",
14370 #endif
14371 #ifdef SQLCIPHER_INT64_TYPE
14372   "INT64_TYPE",
14373 #endif
14374 #ifdef SQLCIPHER_LOCK_TRACE
14375   "LOCK_TRACE",
14376 #endif
14377 #ifdef SQLCIPHER_MAX_SCHEMA_RETRY
14378   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLCIPHER_MAX_SCHEMA_RETRY),
14379 #endif
14380 #ifdef SQLCIPHER_MEMDEBUG
14381   "MEMDEBUG",
14382 #endif
14383 #ifdef SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT
14384   "MIXED_ENDIAN_64BIT_FLOAT",
14385 #endif
14386 #ifdef SQLCIPHER_NO_SYNC
14387   "NO_SYNC",
14388 #endif
14389 #ifdef SQLCIPHER_OMIT_ALTERTABLE
14390   "OMIT_ALTERTABLE",
14391 #endif
14392 #ifdef SQLCIPHER_OMIT_ANALYZE
14393   "OMIT_ANALYZE",
14394 #endif
14395 #ifdef SQLCIPHER_OMIT_ATTACH
14396   "OMIT_ATTACH",
14397 #endif
14398 #ifdef SQLCIPHER_OMIT_AUTHORIZATION
14399   "OMIT_AUTHORIZATION",
14400 #endif
14401 #ifdef SQLCIPHER_OMIT_AUTOINCREMENT
14402   "OMIT_AUTOINCREMENT",
14403 #endif
14404 #ifdef SQLCIPHER_OMIT_AUTOINIT
14405   "OMIT_AUTOINIT",
14406 #endif
14407 #ifdef SQLCIPHER_OMIT_AUTOMATIC_INDEX
14408   "OMIT_AUTOMATIC_INDEX",
14409 #endif
14410 #ifdef SQLCIPHER_OMIT_AUTORESET
14411   "OMIT_AUTORESET",
14412 #endif
14413 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
14414   "OMIT_AUTOVACUUM",
14415 #endif
14416 #ifdef SQLCIPHER_OMIT_BETWEEN_OPTIMIZATION
14417   "OMIT_BETWEEN_OPTIMIZATION",
14418 #endif
14419 #ifdef SQLCIPHER_OMIT_BLOB_LITERAL
14420   "OMIT_BLOB_LITERAL",
14421 #endif
14422 #ifdef SQLCIPHER_OMIT_BTREECOUNT
14423   "OMIT_BTREECOUNT",
14424 #endif
14425 #ifdef SQLCIPHER_OMIT_BUILTIN_TEST
14426   "OMIT_BUILTIN_TEST",
14427 #endif
14428 #ifdef SQLCIPHER_OMIT_CAST
14429   "OMIT_CAST",
14430 #endif
14431 #ifdef SQLCIPHER_OMIT_CHECK
14432   "OMIT_CHECK",
14433 #endif
14434 /* // redundant
14435 ** #ifdef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
14436 **   "OMIT_COMPILEOPTION_DIAGS",
14437 ** #endif
14438 */
14439 #ifdef SQLCIPHER_OMIT_COMPLETE
14440   "OMIT_COMPLETE",
14441 #endif
14442 #ifdef SQLCIPHER_OMIT_COMPOUND_SELECT
14443   "OMIT_COMPOUND_SELECT",
14444 #endif
14445 #ifdef SQLCIPHER_OMIT_DATETIME_FUNCS
14446   "OMIT_DATETIME_FUNCS",
14447 #endif
14448 #ifdef SQLCIPHER_OMIT_DECLTYPE
14449   "OMIT_DECLTYPE",
14450 #endif
14451 #ifdef SQLCIPHER_OMIT_DEPRECATED
14452   "OMIT_DEPRECATED",
14453 #endif
14454 #ifdef SQLCIPHER_OMIT_DISKIO
14455   "OMIT_DISKIO",
14456 #endif
14457 #ifdef SQLCIPHER_OMIT_EXPLAIN
14458   "OMIT_EXPLAIN",
14459 #endif
14460 #ifdef SQLCIPHER_OMIT_FLAG_PRAGMAS
14461   "OMIT_FLAG_PRAGMAS",
14462 #endif
14463 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
14464   "OMIT_FLOATING_POINT",
14465 #endif
14466 #ifdef SQLCIPHER_OMIT_FOREIGN_KEY
14467   "OMIT_FOREIGN_KEY",
14468 #endif
14469 #ifdef SQLCIPHER_OMIT_GET_TABLE
14470   "OMIT_GET_TABLE",
14471 #endif
14472 #ifdef SQLCIPHER_OMIT_INCRBLOB
14473   "OMIT_INCRBLOB",
14474 #endif
14475 #ifdef SQLCIPHER_OMIT_INTEGRITY_CHECK
14476   "OMIT_INTEGRITY_CHECK",
14477 #endif
14478 #ifdef SQLCIPHER_OMIT_LIKE_OPTIMIZATION
14479   "OMIT_LIKE_OPTIMIZATION",
14480 #endif
14481 #ifdef SQLCIPHER_OMIT_LOAD_EXTENSION
14482   "OMIT_LOAD_EXTENSION",
14483 #endif
14484 #ifdef SQLCIPHER_OMIT_LOCALTIME
14485   "OMIT_LOCALTIME",
14486 #endif
14487 #ifdef SQLCIPHER_OMIT_LOOKASIDE
14488   "OMIT_LOOKASIDE",
14489 #endif
14490 #ifdef SQLCIPHER_OMIT_MEMORYDB
14491   "OMIT_MEMORYDB",
14492 #endif
14493 #ifdef SQLCIPHER_OMIT_MERGE_SORT
14494   "OMIT_MERGE_SORT",
14495 #endif
14496 #ifdef SQLCIPHER_OMIT_OR_OPTIMIZATION
14497   "OMIT_OR_OPTIMIZATION",
14498 #endif
14499 #ifdef SQLCIPHER_OMIT_PAGER_PRAGMAS
14500   "OMIT_PAGER_PRAGMAS",
14501 #endif
14502 #ifdef SQLCIPHER_OMIT_PRAGMA
14503   "OMIT_PRAGMA",
14504 #endif
14505 #ifdef SQLCIPHER_OMIT_PROGRESS_CALLBACK
14506   "OMIT_PROGRESS_CALLBACK",
14507 #endif
14508 #ifdef SQLCIPHER_OMIT_QUICKBALANCE
14509   "OMIT_QUICKBALANCE",
14510 #endif
14511 #ifdef SQLCIPHER_OMIT_REINDEX
14512   "OMIT_REINDEX",
14513 #endif
14514 #ifdef SQLCIPHER_OMIT_SCHEMA_PRAGMAS
14515   "OMIT_SCHEMA_PRAGMAS",
14516 #endif
14517 #ifdef SQLCIPHER_OMIT_SCHEMA_VERSION_PRAGMAS
14518   "OMIT_SCHEMA_VERSION_PRAGMAS",
14519 #endif
14520 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
14521   "OMIT_SHARED_CACHE",
14522 #endif
14523 #ifdef SQLCIPHER_OMIT_SUBQUERY
14524   "OMIT_SUBQUERY",
14525 #endif
14526 #ifdef SQLCIPHER_OMIT_TCL_VARIABLE
14527   "OMIT_TCL_VARIABLE",
14528 #endif
14529 #ifdef SQLCIPHER_OMIT_TEMPDB
14530   "OMIT_TEMPDB",
14531 #endif
14532 #ifdef SQLCIPHER_OMIT_TRACE
14533   "OMIT_TRACE",
14534 #endif
14535 #ifdef SQLCIPHER_OMIT_TRIGGER
14536   "OMIT_TRIGGER",
14537 #endif
14538 #ifdef SQLCIPHER_OMIT_TRUNCATE_OPTIMIZATION
14539   "OMIT_TRUNCATE_OPTIMIZATION",
14540 #endif
14541 #ifdef SQLCIPHER_OMIT_UTF16
14542   "OMIT_UTF16",
14543 #endif
14544 #ifdef SQLCIPHER_OMIT_VACUUM
14545   "OMIT_VACUUM",
14546 #endif
14547 #ifdef SQLCIPHER_OMIT_VIEW
14548   "OMIT_VIEW",
14549 #endif
14550 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
14551   "OMIT_VIRTUALTABLE",
14552 #endif
14553 #ifdef SQLCIPHER_OMIT_WAL
14554   "OMIT_WAL",
14555 #endif
14556 #ifdef SQLCIPHER_OMIT_WSD
14557   "OMIT_WSD",
14558 #endif
14559 #ifdef SQLCIPHER_OMIT_XFER_OPT
14560   "OMIT_XFER_OPT",
14561 #endif
14562 #ifdef SQLCIPHER_PERFORMANCE_TRACE
14563   "PERFORMANCE_TRACE",
14564 #endif
14565 #ifdef SQLCIPHER_PROXY_DEBUG
14566   "PROXY_DEBUG",
14567 #endif
14568 #ifdef SQLCIPHER_SECURE_DELETE
14569   "SECURE_DELETE",
14570 #endif
14571 #ifdef SQLCIPHER_SMALL_STACK
14572   "SMALL_STACK",
14573 #endif
14574 #ifdef SQLCIPHER_SOUNDEX
14575   "SOUNDEX",
14576 #endif
14577 #ifdef SQLCIPHER_TCL
14578   "TCL",
14579 #endif
14580 #ifdef SQLCIPHER_TEMP_STORE
14581   "TEMP_STORE=" CTIMEOPT_VAL(SQLCIPHER_TEMP_STORE),
14582 #endif
14583 #ifdef SQLCIPHER_TEST
14584   "TEST",
14585 #endif
14586 #ifdef SQLCIPHER_THREADSAFE
14587   "THREADSAFE=" CTIMEOPT_VAL(SQLCIPHER_THREADSAFE),
14588 #endif
14589 #ifdef SQLCIPHER_USE_ALLOCA
14590   "USE_ALLOCA",
14591 #endif
14592 #ifdef SQLCIPHER_ZERO_MALLOC
14593   "ZERO_MALLOC"
14594 #endif
14595 };
14596
14597 /*
14598 ** Given the name of a compile-time option, return true if that option
14599 ** was used and false if not.
14600 **
14601 ** The name can optionally begin with "SQLCIPHER_" but the "SQLCIPHER_" prefix
14602 ** is not required for a match.
14603 */
14604 SQLCIPHER_API int sqlcipher3_compileoption_used(const char *zOptName){
14605   int i, n;
14606   if( sqlcipher3StrNICmp(zOptName, "SQLCIPHER_", 7)==0 ) zOptName += 7;
14607   n = sqlcipher3Strlen30(zOptName);
14608
14609   /* Since ArraySize(azCompileOpt) is normally in single digits, a
14610   ** linear search is adequate.  No need for a binary search. */
14611   for(i=0; i<ArraySize(azCompileOpt); i++){
14612     if(   (sqlcipher3StrNICmp(zOptName, azCompileOpt[i], n)==0)
14613        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
14614   }
14615   return 0;
14616 }
14617
14618 /*
14619 ** Return the N-th compile-time option string.  If N is out of range,
14620 ** return a NULL pointer.
14621 */
14622 SQLCIPHER_API const char *sqlcipher3_compileoption_get(int N){
14623   if( N>=0 && N<ArraySize(azCompileOpt) ){
14624     return azCompileOpt[N];
14625   }
14626   return 0;
14627 }
14628
14629 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
14630
14631 /************** End of ctime.c ***********************************************/
14632 /************** Begin file status.c ******************************************/
14633 /*
14634 ** 2008 June 18
14635 **
14636 ** The author disclaims copyright to this source code.  In place of
14637 ** a legal notice, here is a blessing:
14638 **
14639 **    May you do good and not evil.
14640 **    May you find forgiveness for yourself and forgive others.
14641 **    May you share freely, never taking more than you give.
14642 **
14643 *************************************************************************
14644 **
14645 ** This module implements the sqlcipher3_status() interface and related
14646 ** functionality.
14647 */
14648 /************** Include vdbeInt.h in the middle of status.c ******************/
14649 /************** Begin file vdbeInt.h *****************************************/
14650 /*
14651 ** 2003 September 6
14652 **
14653 ** The author disclaims copyright to this source code.  In place of
14654 ** a legal notice, here is a blessing:
14655 **
14656 **    May you do good and not evil.
14657 **    May you find forgiveness for yourself and forgive others.
14658 **    May you share freely, never taking more than you give.
14659 **
14660 *************************************************************************
14661 ** This is the header file for information that is private to the
14662 ** VDBE.  This information used to all be at the top of the single
14663 ** source code file "vdbe.c".  When that file became too big (over
14664 ** 6000 lines long) it was split up into several smaller files and
14665 ** this header information was factored out.
14666 */
14667 #ifndef _VDBEINT_H_
14668 #define _VDBEINT_H_
14669
14670 /*
14671 ** SQL is translated into a sequence of instructions to be
14672 ** executed by a virtual machine.  Each instruction is an instance
14673 ** of the following structure.
14674 */
14675 typedef struct VdbeOp Op;
14676
14677 /*
14678 ** Boolean values
14679 */
14680 typedef unsigned char Bool;
14681
14682 /* Opaque type used by code in vdbesort.c */
14683 typedef struct VdbeSorter VdbeSorter;
14684
14685 /*
14686 ** A cursor is a pointer into a single BTree within a database file.
14687 ** The cursor can seek to a BTree entry with a particular key, or
14688 ** loop over all entries of the Btree.  You can also insert new BTree
14689 ** entries or retrieve the key or data from the entry that the cursor
14690 ** is currently pointing to.
14691 ** 
14692 ** Every cursor that the virtual machine has open is represented by an
14693 ** instance of the following structure.
14694 */
14695 struct VdbeCursor {
14696   BtCursor *pCursor;    /* The cursor structure of the backend */
14697   Btree *pBt;           /* Separate file holding temporary table */
14698   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
14699   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
14700   int pseudoTableReg;   /* Register holding pseudotable content. */
14701   int nField;           /* Number of fields in the header */
14702   Bool zeroed;          /* True if zeroed out and ready for reuse */
14703   Bool rowidIsValid;    /* True if lastRowid is valid */
14704   Bool atFirst;         /* True if pointing to first entry */
14705   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
14706   Bool nullRow;         /* True if pointing to a row with no data */
14707   Bool deferredMoveto;  /* A call to sqlcipher3BtreeMoveto() is needed */
14708   Bool isTable;         /* True if a table requiring integer keys */
14709   Bool isIndex;         /* True if an index containing keys only - no data */
14710   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
14711   Bool isSorter;        /* True if a new-style sorter */
14712   sqlcipher3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
14713   const sqlcipher3_module *pModule;     /* Module for cursor pVtabCursor */
14714   i64 seqCount;         /* Sequence counter */
14715   i64 movetoTarget;     /* Argument to the deferred sqlcipher3BtreeMoveto() */
14716   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
14717   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
14718
14719   /* Result of last sqlcipher3BtreeMoveto() done by an OP_NotExists or 
14720   ** OP_IsUnique opcode on this cursor. */
14721   int seekResult;
14722
14723   /* Cached information about the header for the data record that the
14724   ** cursor is currently pointing to.  Only valid if cacheStatus matches
14725   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
14726   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14727   ** the cache is out of date.
14728   **
14729   ** aRow might point to (ephemeral) data for the current row, or it might
14730   ** be NULL.
14731   */
14732   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
14733   int payloadSize;      /* Total number of bytes in the record */
14734   u32 *aType;           /* Type values for all entries in the record */
14735   u32 *aOffset;         /* Cached offsets to the start of each columns data */
14736   u8 *aRow;             /* Data for the current row, if all on one page */
14737 };
14738 typedef struct VdbeCursor VdbeCursor;
14739
14740 /*
14741 ** When a sub-program is executed (OP_Program), a structure of this type
14742 ** is allocated to store the current value of the program counter, as
14743 ** well as the current memory cell array and various other frame specific
14744 ** values stored in the Vdbe struct. When the sub-program is finished, 
14745 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14746 ** restoring the state of the VM to as it was before the sub-program
14747 ** began executing.
14748 **
14749 ** The memory for a VdbeFrame object is allocated and managed by a memory
14750 ** cell in the parent (calling) frame. When the memory cell is deleted or
14751 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14752 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14753 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14754 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14755 ** calls to sqlcipher3VdbeMemRelease() when the memory cells belonging to the
14756 ** child frame are released.
14757 **
14758 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14759 ** set to NULL if the currently executing frame is the main program.
14760 */
14761 typedef struct VdbeFrame VdbeFrame;
14762 struct VdbeFrame {
14763   Vdbe *v;                /* VM this frame belongs to */
14764   int pc;                 /* Program Counter in parent (calling) frame */
14765   Op *aOp;                /* Program instructions for parent frame */
14766   int nOp;                /* Size of aOp array */
14767   Mem *aMem;              /* Array of memory cells for parent frame */
14768   int nMem;               /* Number of entries in aMem */
14769   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
14770   u16 nCursor;            /* Number of entries in apCsr */
14771   void *token;            /* Copy of SubProgram.token */
14772   int nChildMem;          /* Number of memory cells for child frame */
14773   int nChildCsr;          /* Number of cursors for child frame */
14774   i64 lastRowid;          /* Last insert rowid (sqlcipher3.lastRowid) */
14775   int nChange;            /* Statement changes (Vdbe.nChanges)     */
14776   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
14777 };
14778
14779 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14780
14781 /*
14782 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14783 */
14784 #define CACHE_STALE 0
14785
14786 /*
14787 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14788 ** structures. Each Mem struct may cache multiple representations (string,
14789 ** integer etc.) of the same value.
14790 */
14791 struct Mem {
14792   sqlcipher3 *db;        /* The associated database connection */
14793   char *z;            /* String or BLOB value */
14794   double r;           /* Real value */
14795   union {
14796     i64 i;              /* Integer value used when MEM_Int is set in flags */
14797     int nZero;          /* Used when bit MEM_Zero is set in flags */
14798     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
14799     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
14800     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
14801   } u;
14802   int n;              /* Number of characters in string value, excluding '\0' */
14803   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14804   u8  type;           /* One of SQLCIPHER_NULL, SQLCIPHER_TEXT, SQLCIPHER_INTEGER, etc */
14805   u8  enc;            /* SQLCIPHER_UTF8, SQLCIPHER_UTF16BE, SQLCIPHER_UTF16LE */
14806 #ifdef SQLCIPHER_DEBUG
14807   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
14808   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
14809 #endif
14810   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
14811   char *zMalloc;      /* Dynamic buffer allocated by sqlcipher3_malloc() */
14812 };
14813
14814 /* One or more of the following flags are set to indicate the validOK
14815 ** representations of the value stored in the Mem struct.
14816 **
14817 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14818 ** No other flags may be set in this case.
14819 **
14820 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14821 ** Usually this is encoded in the same unicode encoding as the main
14822 ** database (see below for exceptions). If the MEM_Term flag is also
14823 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
14824 ** flags may coexist with the MEM_Str flag.
14825 */
14826 #define MEM_Null      0x0001   /* Value is NULL */
14827 #define MEM_Str       0x0002   /* Value is a string */
14828 #define MEM_Int       0x0004   /* Value is an integer */
14829 #define MEM_Real      0x0008   /* Value is a real number */
14830 #define MEM_Blob      0x0010   /* Value is a BLOB */
14831 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
14832 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
14833 #define MEM_Invalid   0x0080   /* Value is undefined */
14834 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
14835
14836 /* Whenever Mem contains a valid string or blob representation, one of
14837 ** the following flags must be set to determine the memory management
14838 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14839 ** string is \000 or \u0000 terminated
14840 */
14841 #define MEM_Term      0x0200   /* String rep is nul terminated */
14842 #define MEM_Dyn       0x0400   /* Need to call sqlcipherFree() on Mem.z */
14843 #define MEM_Static    0x0800   /* Mem.z points to a static string */
14844 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
14845 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
14846 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
14847 #ifdef SQLCIPHER_OMIT_INCRBLOB
14848   #undef MEM_Zero
14849   #define MEM_Zero 0x0000
14850 #endif
14851
14852 /*
14853 ** Clear any existing type flags from a Mem and replace them with f
14854 */
14855 #define MemSetTypeFlag(p, f) \
14856    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14857
14858 /*
14859 ** Return true if a memory cell is not marked as invalid.  This macro
14860 ** is for use inside assert() statements only.
14861 */
14862 #ifdef SQLCIPHER_DEBUG
14863 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
14864 #endif
14865
14866
14867 /* A VdbeFunc is just a FuncDef (defined in sqlcipherInt.h) that contains
14868 ** additional information about auxiliary information bound to arguments
14869 ** of the function.  This is used to implement the sqlcipher3_get_auxdata()
14870 ** and sqlcipher3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
14871 ** that can be associated with a constant argument to a function.  This
14872 ** allows functions such as "regexp" to compile their constant regular
14873 ** expression argument once and reused the compiled code for multiple
14874 ** invocations.
14875 */
14876 struct VdbeFunc {
14877   FuncDef *pFunc;               /* The definition of the function */
14878   int nAux;                     /* Number of entries allocated for apAux[] */
14879   struct AuxData {
14880     void *pAux;                   /* Aux data for the i-th argument */
14881     void (*xDelete)(void *);      /* Destructor for the aux data */
14882   } apAux[1];                   /* One slot for each function argument */
14883 };
14884
14885 /*
14886 ** The "context" argument for a installable function.  A pointer to an
14887 ** instance of this structure is the first argument to the routines used
14888 ** implement the SQL functions.
14889 **
14890 ** There is a typedef for this structure in sqlcipher.h.  So all routines,
14891 ** even the public interface to SQLite, can use a pointer to this structure.
14892 ** But this file is the only place where the internal details of this
14893 ** structure are known.
14894 **
14895 ** This structure is defined inside of vdbeInt.h because it uses substructures
14896 ** (Mem) which are only defined there.
14897 */
14898 struct sqlcipher3_context {
14899   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
14900   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
14901   Mem s;                /* The return value is stored here */
14902   Mem *pMem;            /* Memory cell used to store aggregate context */
14903   int isError;          /* Error code returned by the function. */
14904   CollSeq *pColl;       /* Collating sequence */
14905 };
14906
14907 /*
14908 ** An instance of the virtual machine.  This structure contains the complete
14909 ** state of the virtual machine.
14910 **
14911 ** The "sqlcipher3_stmt" structure pointer that is returned by sqlcipher3_prepare()
14912 ** is really a pointer to an instance of this structure.
14913 **
14914 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14915 ** any virtual table method invocations made by the vdbe program. It is
14916 ** set to 2 for xDestroy method calls and 1 for all other methods. This
14917 ** variable is used for two purposes: to allow xDestroy methods to execute
14918 ** "DROP TABLE" statements and to prevent some nasty side effects of
14919 ** malloc failure when SQLite is invoked recursively by a virtual table 
14920 ** method function.
14921 */
14922 struct Vdbe {
14923   sqlcipher3 *db;            /* The database connection that owns this statement */
14924   Op *aOp;                /* Space to hold the virtual machine's program */
14925   Mem *aMem;              /* The memory locations */
14926   Mem **apArg;            /* Arguments to currently executing user function */
14927   Mem *aColName;          /* Column names to return */
14928   Mem *pResultSet;        /* Pointer to an array of results */
14929   int nMem;               /* Number of memory locations currently allocated */
14930   int nOp;                /* Number of instructions in the program */
14931   int nOpAlloc;           /* Number of slots allocated for aOp[] */
14932   int nLabel;             /* Number of labels used */
14933   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
14934   int *aLabel;            /* Space to hold the labels */
14935   u16 nResColumn;         /* Number of columns in one row of the result set */
14936   u16 nCursor;            /* Number of slots in apCsr[] */
14937   u32 magic;              /* Magic number for sanity checking */
14938   char *zErrMsg;          /* Error message written here */
14939   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
14940   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
14941   Mem *aVar;              /* Values for the OP_Variable opcode. */
14942   char **azVar;           /* Name of variables */
14943   ynVar nVar;             /* Number of entries in aVar[] */
14944   ynVar nzVar;            /* Number of entries in azVar[] */
14945   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
14946   int pc;                 /* The program counter */
14947   int rc;                 /* Value to return */
14948   u8 errorAction;         /* Recovery action to do in case of an error */
14949   u8 explain;             /* True if EXPLAIN present on SQL command */
14950   u8 changeCntOn;         /* True to update the change-counter */
14951   u8 expired;             /* True if the VM needs to be recompiled */
14952   u8 runOnlyOnce;         /* Automatically expire on reset */
14953   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
14954   u8 inVtabMethod;        /* See comments above */
14955   u8 usesStmtJournal;     /* True if uses a statement journal */
14956   u8 readOnly;            /* True for read-only statements */
14957   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
14958   int nChange;            /* Number of db changes made since last reset */
14959   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
14960   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
14961   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
14962   int aCounter[3];        /* Counters used by sqlcipher3_stmt_status() */
14963 #ifndef SQLCIPHER_OMIT_TRACE
14964   i64 startTime;          /* Time when query started - used for profiling */
14965 #endif
14966   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
14967   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
14968   char *zSql;             /* Text of the SQL statement that generated this */
14969   void *pFree;            /* Free this when deleting the vdbe */
14970 #ifdef SQLCIPHER_DEBUG
14971   FILE *trace;            /* Write an execution trace here, if not NULL */
14972 #endif
14973   VdbeFrame *pFrame;      /* Parent frame */
14974   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
14975   int nFrame;             /* Number of frames in pFrame list */
14976   u32 expmask;            /* Binding to these vars invalidates VM */
14977   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
14978 };
14979
14980 /*
14981 ** The following are allowed values for Vdbe.magic
14982 */
14983 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
14984 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
14985 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
14986 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
14987
14988 /*
14989 ** Function prototypes
14990 */
14991 SQLCIPHER_PRIVATE void sqlcipher3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14992 void sqlcipherVdbePopStack(Vdbe*,int);
14993 SQLCIPHER_PRIVATE int sqlcipher3VdbeCursorMoveto(VdbeCursor*);
14994 #if defined(SQLCIPHER_DEBUG) || defined(VDBE_PROFILE)
14995 SQLCIPHER_PRIVATE void sqlcipher3VdbePrintOp(FILE*, int, Op*);
14996 #endif
14997 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialTypeLen(u32);
14998 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialType(Mem*, int);
14999 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialPut(unsigned char*, int, Mem*, int);
15000 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialGet(const unsigned char*, u32, Mem*);
15001 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteAuxData(VdbeFunc*, int);
15002
15003 int sqlcipher2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
15004 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
15005 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxRowid(sqlcipher3*, BtCursor *, i64 *);
15006 SQLCIPHER_PRIVATE int sqlcipher3MemCompare(const Mem*, const Mem*, const CollSeq*);
15007 SQLCIPHER_PRIVATE int sqlcipher3VdbeExec(Vdbe*);
15008 SQLCIPHER_PRIVATE int sqlcipher3VdbeList(Vdbe*);
15009 SQLCIPHER_PRIVATE int sqlcipher3VdbeHalt(Vdbe*);
15010 SQLCIPHER_PRIVATE int sqlcipher3VdbeChangeEncoding(Mem *, int);
15011 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTooBig(Mem*);
15012 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemCopy(Mem*, const Mem*);
15013 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemShallowCopy(Mem*, const Mem*, int);
15014 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemMove(Mem*, Mem*);
15015 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNulTerminate(Mem*);
15016 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
15017 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetInt64(Mem*, i64);
15018 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
15019 # define sqlcipher3VdbeMemSetDouble sqlcipher3VdbeMemSetInt64
15020 #else
15021 SQLCIPHER_PRIVATE   void sqlcipher3VdbeMemSetDouble(Mem*, double);
15022 #endif
15023 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetNull(Mem*);
15024 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetZeroBlob(Mem*,int);
15025 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetRowSet(Mem*);
15026 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemMakeWriteable(Mem*);
15027 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemStringify(Mem*, int);
15028 SQLCIPHER_PRIVATE i64 sqlcipher3VdbeIntValue(Mem*);
15029 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemIntegerify(Mem*);
15030 SQLCIPHER_PRIVATE double sqlcipher3VdbeRealValue(Mem*);
15031 SQLCIPHER_PRIVATE void sqlcipher3VdbeIntegerAffinity(Mem*);
15032 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemRealify(Mem*);
15033 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNumerify(Mem*);
15034 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
15035 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemRelease(Mem *p);
15036 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemReleaseExternal(Mem *p);
15037 #define MemReleaseExt(X)  \
15038   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
15039     sqlcipher3VdbeMemReleaseExternal(X);
15040 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFinalize(Mem*, FuncDef*);
15041 SQLCIPHER_PRIVATE const char *sqlcipher3OpcodeName(int);
15042 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemGrow(Mem *pMem, int n, int preserve);
15043 SQLCIPHER_PRIVATE int sqlcipher3VdbeCloseStatement(Vdbe *, int);
15044 SQLCIPHER_PRIVATE void sqlcipher3VdbeFrameDelete(VdbeFrame*);
15045 SQLCIPHER_PRIVATE int sqlcipher3VdbeFrameRestore(VdbeFrame *);
15046 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemStoreType(Mem *pMem);
15047 SQLCIPHER_PRIVATE int sqlcipher3VdbeTransferError(Vdbe *p);
15048
15049 #ifdef SQLCIPHER_OMIT_MERGE_SORT
15050 # define sqlcipher3VdbeSorterInit(Y,Z)      SQLCIPHER_OK
15051 # define sqlcipher3VdbeSorterWrite(X,Y,Z)   SQLCIPHER_OK
15052 # define sqlcipher3VdbeSorterClose(Y,Z)
15053 # define sqlcipher3VdbeSorterRowkey(Y,Z)    SQLCIPHER_OK
15054 # define sqlcipher3VdbeSorterRewind(X,Y,Z)  SQLCIPHER_OK
15055 # define sqlcipher3VdbeSorterNext(X,Y,Z)    SQLCIPHER_OK
15056 # define sqlcipher3VdbeSorterCompare(X,Y,Z) SQLCIPHER_OK
15057 #else
15058 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterInit(sqlcipher3 *, VdbeCursor *);
15059 SQLCIPHER_PRIVATE void sqlcipher3VdbeSorterClose(sqlcipher3 *, VdbeCursor *);
15060 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRowkey(VdbeCursor *, Mem *);
15061 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterNext(sqlcipher3 *, VdbeCursor *, int *);
15062 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRewind(sqlcipher3 *, VdbeCursor *, int *);
15063 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterWrite(sqlcipher3 *, VdbeCursor *, Mem *);
15064 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
15065 #endif
15066
15067 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE>0
15068 SQLCIPHER_PRIVATE   void sqlcipher3VdbeEnter(Vdbe*);
15069 SQLCIPHER_PRIVATE   void sqlcipher3VdbeLeave(Vdbe*);
15070 #else
15071 # define sqlcipher3VdbeEnter(X)
15072 # define sqlcipher3VdbeLeave(X)
15073 #endif
15074
15075 #ifdef SQLCIPHER_DEBUG
15076 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemPrepareToChange(Vdbe*,Mem*);
15077 #endif
15078
15079 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
15080 SQLCIPHER_PRIVATE int sqlcipher3VdbeCheckFk(Vdbe *, int);
15081 #else
15082 # define sqlcipher3VdbeCheckFk(p,i) 0
15083 #endif
15084
15085 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTranslate(Mem*, u8);
15086 #ifdef SQLCIPHER_DEBUG
15087 SQLCIPHER_PRIVATE   void sqlcipher3VdbePrintSql(Vdbe*);
15088 SQLCIPHER_PRIVATE   void sqlcipher3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
15089 #endif
15090 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemHandleBom(Mem *pMem);
15091
15092 #ifndef SQLCIPHER_OMIT_INCRBLOB
15093 SQLCIPHER_PRIVATE   int sqlcipher3VdbeMemExpandBlob(Mem *);
15094 #else
15095   #define sqlcipher3VdbeMemExpandBlob(x) SQLCIPHER_OK
15096 #endif
15097
15098 #endif /* !defined(_VDBEINT_H_) */
15099
15100 /************** End of vdbeInt.h *********************************************/
15101 /************** Continuing where we left off in status.c *********************/
15102
15103 /*
15104 ** Variables in which to record status information.
15105 */
15106 typedef struct sqlcipher3StatType sqlcipher3StatType;
15107 static SQLCIPHER_WSD struct sqlcipher3StatType {
15108   int nowValue[10];         /* Current value */
15109   int mxValue[10];          /* Maximum value */
15110 } sqlcipher3Stat = { {0,}, {0,} };
15111
15112
15113 /* The "wsdStat" macro will resolve to the status information
15114 ** state vector.  If writable static data is unsupported on the target,
15115 ** we have to locate the state vector at run-time.  In the more common
15116 ** case where writable static data is supported, wsdStat can refer directly
15117 ** to the "sqlcipher3Stat" state vector declared above.
15118 */
15119 #ifdef SQLCIPHER_OMIT_WSD
15120 # define wsdStatInit  sqlcipher3StatType *x = &GLOBAL(sqlcipher3StatType,sqlcipher3Stat)
15121 # define wsdStat x[0]
15122 #else
15123 # define wsdStatInit
15124 # define wsdStat sqlcipher3Stat
15125 #endif
15126
15127 /*
15128 ** Return the current value of a status parameter.
15129 */
15130 SQLCIPHER_PRIVATE int sqlcipher3StatusValue(int op){
15131   wsdStatInit;
15132   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15133   return wsdStat.nowValue[op];
15134 }
15135
15136 /*
15137 ** Add N to the value of a status record.  It is assumed that the
15138 ** caller holds appropriate locks.
15139 */
15140 SQLCIPHER_PRIVATE void sqlcipher3StatusAdd(int op, int N){
15141   wsdStatInit;
15142   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15143   wsdStat.nowValue[op] += N;
15144   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15145     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15146   }
15147 }
15148
15149 /*
15150 ** Set the value of a status to X.
15151 */
15152 SQLCIPHER_PRIVATE void sqlcipher3StatusSet(int op, int X){
15153   wsdStatInit;
15154   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15155   wsdStat.nowValue[op] = X;
15156   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15157     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15158   }
15159 }
15160
15161 /*
15162 ** Query status information.
15163 **
15164 ** This implementation assumes that reading or writing an aligned
15165 ** 32-bit integer is an atomic operation.  If that assumption is not true,
15166 ** then this routine is not threadsafe.
15167 */
15168 SQLCIPHER_API int sqlcipher3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
15169   wsdStatInit;
15170   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
15171     return SQLCIPHER_MISUSE_BKPT;
15172   }
15173   *pCurrent = wsdStat.nowValue[op];
15174   *pHighwater = wsdStat.mxValue[op];
15175   if( resetFlag ){
15176     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15177   }
15178   return SQLCIPHER_OK;
15179 }
15180
15181 /*
15182 ** Query status information for a single database connection
15183 */
15184 SQLCIPHER_API int sqlcipher3_db_status(
15185   sqlcipher3 *db,          /* The database connection whose status is desired */
15186   int op,               /* Status verb */
15187   int *pCurrent,        /* Write current value here */
15188   int *pHighwater,      /* Write high-water mark here */
15189   int resetFlag         /* Reset high-water mark if true */
15190 ){
15191   int rc = SQLCIPHER_OK;   /* Return code */
15192   sqlcipher3_mutex_enter(db->mutex);
15193   switch( op ){
15194     case SQLCIPHER_DBSTATUS_LOOKASIDE_USED: {
15195       *pCurrent = db->lookaside.nOut;
15196       *pHighwater = db->lookaside.mxOut;
15197       if( resetFlag ){
15198         db->lookaside.mxOut = db->lookaside.nOut;
15199       }
15200       break;
15201     }
15202
15203     case SQLCIPHER_DBSTATUS_LOOKASIDE_HIT:
15204     case SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE:
15205     case SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL: {
15206       testcase( op==SQLCIPHER_DBSTATUS_LOOKASIDE_HIT );
15207       testcase( op==SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_SIZE );
15208       testcase( op==SQLCIPHER_DBSTATUS_LOOKASIDE_MISS_FULL );
15209       assert( (op-SQLCIPHER_DBSTATUS_LOOKASIDE_HIT)>=0 );
15210       assert( (op-SQLCIPHER_DBSTATUS_LOOKASIDE_HIT)<3 );
15211       *pCurrent = 0;
15212       *pHighwater = db->lookaside.anStat[op - SQLCIPHER_DBSTATUS_LOOKASIDE_HIT];
15213       if( resetFlag ){
15214         db->lookaside.anStat[op - SQLCIPHER_DBSTATUS_LOOKASIDE_HIT] = 0;
15215       }
15216       break;
15217     }
15218
15219     /* 
15220     ** Return an approximation for the amount of memory currently used
15221     ** by all pagers associated with the given database connection.  The
15222     ** highwater mark is meaningless and is returned as zero.
15223     */
15224     case SQLCIPHER_DBSTATUS_CACHE_USED: {
15225       int totalUsed = 0;
15226       int i;
15227       sqlcipher3BtreeEnterAll(db);
15228       for(i=0; i<db->nDb; i++){
15229         Btree *pBt = db->aDb[i].pBt;
15230         if( pBt ){
15231           Pager *pPager = sqlcipher3BtreePager(pBt);
15232           totalUsed += sqlcipher3PagerMemUsed(pPager);
15233         }
15234       }
15235       sqlcipher3BtreeLeaveAll(db);
15236       *pCurrent = totalUsed;
15237       *pHighwater = 0;
15238       break;
15239     }
15240
15241     /*
15242     ** *pCurrent gets an accurate estimate of the amount of memory used
15243     ** to store the schema for all databases (main, temp, and any ATTACHed
15244     ** databases.  *pHighwater is set to zero.
15245     */
15246     case SQLCIPHER_DBSTATUS_SCHEMA_USED: {
15247       int i;                      /* Used to iterate through schemas */
15248       int nByte = 0;              /* Used to accumulate return value */
15249
15250       sqlcipher3BtreeEnterAll(db);
15251       db->pnBytesFreed = &nByte;
15252       for(i=0; i<db->nDb; i++){
15253         Schema *pSchema = db->aDb[i].pSchema;
15254         if( ALWAYS(pSchema!=0) ){
15255           HashElem *p;
15256
15257           nByte += sqlcipher3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
15258               pSchema->tblHash.count 
15259             + pSchema->trigHash.count
15260             + pSchema->idxHash.count
15261             + pSchema->fkeyHash.count
15262           );
15263           nByte += sqlcipher3MallocSize(pSchema->tblHash.ht);
15264           nByte += sqlcipher3MallocSize(pSchema->trigHash.ht);
15265           nByte += sqlcipher3MallocSize(pSchema->idxHash.ht);
15266           nByte += sqlcipher3MallocSize(pSchema->fkeyHash.ht);
15267
15268           for(p=sqlcipherHashFirst(&pSchema->trigHash); p; p=sqlcipherHashNext(p)){
15269             sqlcipher3DeleteTrigger(db, (Trigger*)sqlcipherHashData(p));
15270           }
15271           for(p=sqlcipherHashFirst(&pSchema->tblHash); p; p=sqlcipherHashNext(p)){
15272             sqlcipher3DeleteTable(db, (Table *)sqlcipherHashData(p));
15273           }
15274         }
15275       }
15276       db->pnBytesFreed = 0;
15277       sqlcipher3BtreeLeaveAll(db);
15278
15279       *pHighwater = 0;
15280       *pCurrent = nByte;
15281       break;
15282     }
15283
15284     /*
15285     ** *pCurrent gets an accurate estimate of the amount of memory used
15286     ** to store all prepared statements.
15287     ** *pHighwater is set to zero.
15288     */
15289     case SQLCIPHER_DBSTATUS_STMT_USED: {
15290       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
15291       int nByte = 0;              /* Used to accumulate return value */
15292
15293       db->pnBytesFreed = &nByte;
15294       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
15295         sqlcipher3VdbeDeleteObject(db, pVdbe);
15296       }
15297       db->pnBytesFreed = 0;
15298
15299       *pHighwater = 0;
15300       *pCurrent = nByte;
15301
15302       break;
15303     }
15304
15305     /*
15306     ** Set *pCurrent to the total cache hits or misses encountered by all
15307     ** pagers the database handle is connected to. *pHighwater is always set 
15308     ** to zero.
15309     */
15310     case SQLCIPHER_DBSTATUS_CACHE_HIT:
15311     case SQLCIPHER_DBSTATUS_CACHE_MISS: {
15312       int i;
15313       int nRet = 0;
15314       assert( SQLCIPHER_DBSTATUS_CACHE_MISS==SQLCIPHER_DBSTATUS_CACHE_HIT+1 );
15315
15316       for(i=0; i<db->nDb; i++){
15317         if( db->aDb[i].pBt ){
15318           Pager *pPager = sqlcipher3BtreePager(db->aDb[i].pBt);
15319           sqlcipher3PagerCacheStat(pPager, op, resetFlag, &nRet);
15320         }
15321       }
15322       *pHighwater = 0;
15323       *pCurrent = nRet;
15324       break;
15325     }
15326
15327     default: {
15328       rc = SQLCIPHER_ERROR;
15329     }
15330   }
15331   sqlcipher3_mutex_leave(db->mutex);
15332   return rc;
15333 }
15334
15335 /************** End of status.c **********************************************/
15336 /************** Begin file date.c ********************************************/
15337 /*
15338 ** 2003 October 31
15339 **
15340 ** The author disclaims copyright to this source code.  In place of
15341 ** a legal notice, here is a blessing:
15342 **
15343 **    May you do good and not evil.
15344 **    May you find forgiveness for yourself and forgive others.
15345 **    May you share freely, never taking more than you give.
15346 **
15347 *************************************************************************
15348 ** This file contains the C functions that implement date and time
15349 ** functions for SQLite.  
15350 **
15351 ** There is only one exported symbol in this file - the function
15352 ** sqlcipher3RegisterDateTimeFunctions() found at the bottom of the file.
15353 ** All other code has file scope.
15354 **
15355 ** SQLite processes all times and dates as Julian Day numbers.  The
15356 ** dates and times are stored as the number of days since noon
15357 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
15358 ** calendar system. 
15359 **
15360 ** 1970-01-01 00:00:00 is JD 2440587.5
15361 ** 2000-01-01 00:00:00 is JD 2451544.5
15362 **
15363 ** This implemention requires years to be expressed as a 4-digit number
15364 ** which means that only dates between 0000-01-01 and 9999-12-31 can
15365 ** be represented, even though julian day numbers allow a much wider
15366 ** range of dates.
15367 **
15368 ** The Gregorian calendar system is used for all dates and times,
15369 ** even those that predate the Gregorian calendar.  Historians usually
15370 ** use the Julian calendar for dates prior to 1582-10-15 and for some
15371 ** dates afterwards, depending on locale.  Beware of this difference.
15372 **
15373 ** The conversion algorithms are implemented based on descriptions
15374 ** in the following text:
15375 **
15376 **      Jean Meeus
15377 **      Astronomical Algorithms, 2nd Edition, 1998
15378 **      ISBM 0-943396-61-1
15379 **      Willmann-Bell, Inc
15380 **      Richmond, Virginia (USA)
15381 */
15382 /* #include <stdlib.h> */
15383 /* #include <assert.h> */
15384 #include <time.h>
15385
15386 #ifndef SQLCIPHER_OMIT_DATETIME_FUNCS
15387
15388
15389 /*
15390 ** A structure for holding a single date and time.
15391 */
15392 typedef struct DateTime DateTime;
15393 struct DateTime {
15394   sqlcipher3_int64 iJD; /* The julian day number times 86400000 */
15395   int Y, M, D;       /* Year, month, and day */
15396   int h, m;          /* Hour and minutes */
15397   int tz;            /* Timezone offset in minutes */
15398   double s;          /* Seconds */
15399   char validYMD;     /* True (1) if Y,M,D are valid */
15400   char validHMS;     /* True (1) if h,m,s are valid */
15401   char validJD;      /* True (1) if iJD is valid */
15402   char validTZ;      /* True (1) if tz is valid */
15403 };
15404
15405
15406 /*
15407 ** Convert zDate into one or more integers.  Additional arguments
15408 ** come in groups of 5 as follows:
15409 **
15410 **       N       number of digits in the integer
15411 **       min     minimum allowed value of the integer
15412 **       max     maximum allowed value of the integer
15413 **       nextC   first character after the integer
15414 **       pVal    where to write the integers value.
15415 **
15416 ** Conversions continue until one with nextC==0 is encountered.
15417 ** The function returns the number of successful conversions.
15418 */
15419 static int getDigits(const char *zDate, ...){
15420   va_list ap;
15421   int val;
15422   int N;
15423   int min;
15424   int max;
15425   int nextC;
15426   int *pVal;
15427   int cnt = 0;
15428   va_start(ap, zDate);
15429   do{
15430     N = va_arg(ap, int);
15431     min = va_arg(ap, int);
15432     max = va_arg(ap, int);
15433     nextC = va_arg(ap, int);
15434     pVal = va_arg(ap, int*);
15435     val = 0;
15436     while( N-- ){
15437       if( !sqlcipher3Isdigit(*zDate) ){
15438         goto end_getDigits;
15439       }
15440       val = val*10 + *zDate - '0';
15441       zDate++;
15442     }
15443     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
15444       goto end_getDigits;
15445     }
15446     *pVal = val;
15447     zDate++;
15448     cnt++;
15449   }while( nextC );
15450 end_getDigits:
15451   va_end(ap);
15452   return cnt;
15453 }
15454
15455 /*
15456 ** Parse a timezone extension on the end of a date-time.
15457 ** The extension is of the form:
15458 **
15459 **        (+/-)HH:MM
15460 **
15461 ** Or the "zulu" notation:
15462 **
15463 **        Z
15464 **
15465 ** If the parse is successful, write the number of minutes
15466 ** of change in p->tz and return 0.  If a parser error occurs,
15467 ** return non-zero.
15468 **
15469 ** A missing specifier is not considered an error.
15470 */
15471 static int parseTimezone(const char *zDate, DateTime *p){
15472   int sgn = 0;
15473   int nHr, nMn;
15474   int c;
15475   while( sqlcipher3Isspace(*zDate) ){ zDate++; }
15476   p->tz = 0;
15477   c = *zDate;
15478   if( c=='-' ){
15479     sgn = -1;
15480   }else if( c=='+' ){
15481     sgn = +1;
15482   }else if( c=='Z' || c=='z' ){
15483     zDate++;
15484     goto zulu_time;
15485   }else{
15486     return c!=0;
15487   }
15488   zDate++;
15489   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
15490     return 1;
15491   }
15492   zDate += 5;
15493   p->tz = sgn*(nMn + nHr*60);
15494 zulu_time:
15495   while( sqlcipher3Isspace(*zDate) ){ zDate++; }
15496   return *zDate!=0;
15497 }
15498
15499 /*
15500 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
15501 ** The HH, MM, and SS must each be exactly 2 digits.  The
15502 ** fractional seconds FFFF can be one or more digits.
15503 **
15504 ** Return 1 if there is a parsing error and 0 on success.
15505 */
15506 static int parseHhMmSs(const char *zDate, DateTime *p){
15507   int h, m, s;
15508   double ms = 0.0;
15509   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
15510     return 1;
15511   }
15512   zDate += 5;
15513   if( *zDate==':' ){
15514     zDate++;
15515     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
15516       return 1;
15517     }
15518     zDate += 2;
15519     if( *zDate=='.' && sqlcipher3Isdigit(zDate[1]) ){
15520       double rScale = 1.0;
15521       zDate++;
15522       while( sqlcipher3Isdigit(*zDate) ){
15523         ms = ms*10.0 + *zDate - '0';
15524         rScale *= 10.0;
15525         zDate++;
15526       }
15527       ms /= rScale;
15528     }
15529   }else{
15530     s = 0;
15531   }
15532   p->validJD = 0;
15533   p->validHMS = 1;
15534   p->h = h;
15535   p->m = m;
15536   p->s = s + ms;
15537   if( parseTimezone(zDate, p) ) return 1;
15538   p->validTZ = (p->tz!=0)?1:0;
15539   return 0;
15540 }
15541
15542 /*
15543 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
15544 ** that the YYYY-MM-DD is according to the Gregorian calendar.
15545 **
15546 ** Reference:  Meeus page 61
15547 */
15548 static void computeJD(DateTime *p){
15549   int Y, M, D, A, B, X1, X2;
15550
15551   if( p->validJD ) return;
15552   if( p->validYMD ){
15553     Y = p->Y;
15554     M = p->M;
15555     D = p->D;
15556   }else{
15557     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
15558     M = 1;
15559     D = 1;
15560   }
15561   if( M<=2 ){
15562     Y--;
15563     M += 12;
15564   }
15565   A = Y/100;
15566   B = 2 - A + (A/4);
15567   X1 = 36525*(Y+4716)/100;
15568   X2 = 306001*(M+1)/10000;
15569   p->iJD = (sqlcipher3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
15570   p->validJD = 1;
15571   if( p->validHMS ){
15572     p->iJD += p->h*3600000 + p->m*60000 + (sqlcipher3_int64)(p->s*1000);
15573     if( p->validTZ ){
15574       p->iJD -= p->tz*60000;
15575       p->validYMD = 0;
15576       p->validHMS = 0;
15577       p->validTZ = 0;
15578     }
15579   }
15580 }
15581
15582 /*
15583 ** Parse dates of the form
15584 **
15585 **     YYYY-MM-DD HH:MM:SS.FFF
15586 **     YYYY-MM-DD HH:MM:SS
15587 **     YYYY-MM-DD HH:MM
15588 **     YYYY-MM-DD
15589 **
15590 ** Write the result into the DateTime structure and return 0
15591 ** on success and 1 if the input string is not a well-formed
15592 ** date.
15593 */
15594 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15595   int Y, M, D, neg;
15596
15597   if( zDate[0]=='-' ){
15598     zDate++;
15599     neg = 1;
15600   }else{
15601     neg = 0;
15602   }
15603   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15604     return 1;
15605   }
15606   zDate += 10;
15607   while( sqlcipher3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15608   if( parseHhMmSs(zDate, p)==0 ){
15609     /* We got the time */
15610   }else if( *zDate==0 ){
15611     p->validHMS = 0;
15612   }else{
15613     return 1;
15614   }
15615   p->validJD = 0;
15616   p->validYMD = 1;
15617   p->Y = neg ? -Y : Y;
15618   p->M = M;
15619   p->D = D;
15620   if( p->validTZ ){
15621     computeJD(p);
15622   }
15623   return 0;
15624 }
15625
15626 /*
15627 ** Set the time to the current time reported by the VFS.
15628 **
15629 ** Return the number of errors.
15630 */
15631 static int setDateTimeToCurrent(sqlcipher3_context *context, DateTime *p){
15632   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
15633   if( sqlcipher3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLCIPHER_OK ){
15634     p->validJD = 1;
15635     return 0;
15636   }else{
15637     return 1;
15638   }
15639 }
15640
15641 /*
15642 ** Attempt to parse the given string into a Julian Day Number.  Return
15643 ** the number of errors.
15644 **
15645 ** The following are acceptable forms for the input string:
15646 **
15647 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
15648 **      DDDD.DD 
15649 **      now
15650 **
15651 ** In the first form, the +/-HH:MM is always optional.  The fractional
15652 ** seconds extension (the ".FFF") is optional.  The seconds portion
15653 ** (":SS.FFF") is option.  The year and date can be omitted as long
15654 ** as there is a time string.  The time string can be omitted as long
15655 ** as there is a year and date.
15656 */
15657 static int parseDateOrTime(
15658   sqlcipher3_context *context, 
15659   const char *zDate, 
15660   DateTime *p
15661 ){
15662   double r;
15663   if( parseYyyyMmDd(zDate,p)==0 ){
15664     return 0;
15665   }else if( parseHhMmSs(zDate, p)==0 ){
15666     return 0;
15667   }else if( sqlcipher3StrICmp(zDate,"now")==0){
15668     return setDateTimeToCurrent(context, p);
15669   }else if( sqlcipher3AtoF(zDate, &r, sqlcipher3Strlen30(zDate), SQLCIPHER_UTF8) ){
15670     p->iJD = (sqlcipher3_int64)(r*86400000.0 + 0.5);
15671     p->validJD = 1;
15672     return 0;
15673   }
15674   return 1;
15675 }
15676
15677 /*
15678 ** Compute the Year, Month, and Day from the julian day number.
15679 */
15680 static void computeYMD(DateTime *p){
15681   int Z, A, B, C, D, E, X1;
15682   if( p->validYMD ) return;
15683   if( !p->validJD ){
15684     p->Y = 2000;
15685     p->M = 1;
15686     p->D = 1;
15687   }else{
15688     Z = (int)((p->iJD + 43200000)/86400000);
15689     A = (int)((Z - 1867216.25)/36524.25);
15690     A = Z + 1 + A - (A/4);
15691     B = A + 1524;
15692     C = (int)((B - 122.1)/365.25);
15693     D = (36525*C)/100;
15694     E = (int)((B-D)/30.6001);
15695     X1 = (int)(30.6001*E);
15696     p->D = B - D - X1;
15697     p->M = E<14 ? E-1 : E-13;
15698     p->Y = p->M>2 ? C - 4716 : C - 4715;
15699   }
15700   p->validYMD = 1;
15701 }
15702
15703 /*
15704 ** Compute the Hour, Minute, and Seconds from the julian day number.
15705 */
15706 static void computeHMS(DateTime *p){
15707   int s;
15708   if( p->validHMS ) return;
15709   computeJD(p);
15710   s = (int)((p->iJD + 43200000) % 86400000);
15711   p->s = s/1000.0;
15712   s = (int)p->s;
15713   p->s -= s;
15714   p->h = s/3600;
15715   s -= p->h*3600;
15716   p->m = s/60;
15717   p->s += s - p->m*60;
15718   p->validHMS = 1;
15719 }
15720
15721 /*
15722 ** Compute both YMD and HMS
15723 */
15724 static void computeYMD_HMS(DateTime *p){
15725   computeYMD(p);
15726   computeHMS(p);
15727 }
15728
15729 /*
15730 ** Clear the YMD and HMS and the TZ
15731 */
15732 static void clearYMD_HMS_TZ(DateTime *p){
15733   p->validYMD = 0;
15734   p->validHMS = 0;
15735   p->validTZ = 0;
15736 }
15737
15738 /*
15739 ** On recent Windows platforms, the localtime_s() function is available
15740 ** as part of the "Secure CRT". It is essentially equivalent to 
15741 ** localtime_r() available under most POSIX platforms, except that the 
15742 ** order of the parameters is reversed.
15743 **
15744 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15745 **
15746 ** If the user has not indicated to use localtime_r() or localtime_s()
15747 ** already, check for an MSVC build environment that provides 
15748 ** localtime_s().
15749 */
15750 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
15751      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15752 #define HAVE_LOCALTIME_S 1
15753 #endif
15754
15755 #ifndef SQLCIPHER_OMIT_LOCALTIME
15756 /*
15757 ** The following routine implements the rough equivalent of localtime_r()
15758 ** using whatever operating-system specific localtime facility that
15759 ** is available.  This routine returns 0 on success and
15760 ** non-zero on any kind of error.
15761 **
15762 ** If the sqlcipher3GlobalConfig.bLocaltimeFault variable is true then this
15763 ** routine will always fail.
15764 */
15765 static int osLocaltime(time_t *t, struct tm *pTm){
15766   int rc;
15767 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
15768       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
15769   struct tm *pX;
15770 #if SQLCIPHER_THREADSAFE>0
15771   sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
15772 #endif
15773   sqlcipher3_mutex_enter(mutex);
15774   pX = localtime(t);
15775 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
15776   if( sqlcipher3GlobalConfig.bLocaltimeFault ) pX = 0;
15777 #endif
15778   if( pX ) *pTm = *pX;
15779   sqlcipher3_mutex_leave(mutex);
15780   rc = pX==0;
15781 #else
15782 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
15783   if( sqlcipher3GlobalConfig.bLocaltimeFault ) return 1;
15784 #endif
15785 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
15786   rc = localtime_r(t, pTm)==0;
15787 #else
15788   rc = localtime_s(pTm, t);
15789 #endif /* HAVE_LOCALTIME_R */
15790 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15791   return rc;
15792 }
15793 #endif /* SQLCIPHER_OMIT_LOCALTIME */
15794
15795
15796 #ifndef SQLCIPHER_OMIT_LOCALTIME
15797 /*
15798 ** Compute the difference (in milliseconds) between localtime and UTC
15799 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15800 ** return this value and set *pRc to SQLCIPHER_OK. 
15801 **
15802 ** Or, if an error does occur, set *pRc to SQLCIPHER_ERROR. The returned value
15803 ** is undefined in this case.
15804 */
15805 static sqlcipher3_int64 localtimeOffset(
15806   DateTime *p,                    /* Date at which to calculate offset */
15807   sqlcipher3_context *pCtx,          /* Write error here if one occurs */
15808   int *pRc                        /* OUT: Error code. SQLCIPHER_OK or ERROR */
15809 ){
15810   DateTime x, y;
15811   time_t t;
15812   struct tm sLocal;
15813
15814   /* Initialize the contents of sLocal to avoid a compiler warning. */
15815   memset(&sLocal, 0, sizeof(sLocal));
15816
15817   x = *p;
15818   computeYMD_HMS(&x);
15819   if( x.Y<1971 || x.Y>=2038 ){
15820     x.Y = 2000;
15821     x.M = 1;
15822     x.D = 1;
15823     x.h = 0;
15824     x.m = 0;
15825     x.s = 0.0;
15826   } else {
15827     int s = (int)(x.s + 0.5);
15828     x.s = s;
15829   }
15830   x.tz = 0;
15831   x.validJD = 0;
15832   computeJD(&x);
15833   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15834   if( osLocaltime(&t, &sLocal) ){
15835     sqlcipher3_result_error(pCtx, "local time unavailable", -1);
15836     *pRc = SQLCIPHER_ERROR;
15837     return 0;
15838   }
15839   y.Y = sLocal.tm_year + 1900;
15840   y.M = sLocal.tm_mon + 1;
15841   y.D = sLocal.tm_mday;
15842   y.h = sLocal.tm_hour;
15843   y.m = sLocal.tm_min;
15844   y.s = sLocal.tm_sec;
15845   y.validYMD = 1;
15846   y.validHMS = 1;
15847   y.validJD = 0;
15848   y.validTZ = 0;
15849   computeJD(&y);
15850   *pRc = SQLCIPHER_OK;
15851   return y.iJD - x.iJD;
15852 }
15853 #endif /* SQLCIPHER_OMIT_LOCALTIME */
15854
15855 /*
15856 ** Process a modifier to a date-time stamp.  The modifiers are
15857 ** as follows:
15858 **
15859 **     NNN days
15860 **     NNN hours
15861 **     NNN minutes
15862 **     NNN.NNNN seconds
15863 **     NNN months
15864 **     NNN years
15865 **     start of month
15866 **     start of year
15867 **     start of week
15868 **     start of day
15869 **     weekday N
15870 **     unixepoch
15871 **     localtime
15872 **     utc
15873 **
15874 ** Return 0 on success and 1 if there is any kind of error. If the error
15875 ** is in a system call (i.e. localtime()), then an error message is written
15876 ** to context pCtx. If the error is an unrecognized modifier, no error is
15877 ** written to pCtx.
15878 */
15879 static int parseModifier(sqlcipher3_context *pCtx, const char *zMod, DateTime *p){
15880   int rc = 1;
15881   int n;
15882   double r;
15883   char *z, zBuf[30];
15884   z = zBuf;
15885   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15886     z[n] = (char)sqlcipher3UpperToLower[(u8)zMod[n]];
15887   }
15888   z[n] = 0;
15889   switch( z[0] ){
15890 #ifndef SQLCIPHER_OMIT_LOCALTIME
15891     case 'l': {
15892       /*    localtime
15893       **
15894       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15895       ** show local time.
15896       */
15897       if( strcmp(z, "localtime")==0 ){
15898         computeJD(p);
15899         p->iJD += localtimeOffset(p, pCtx, &rc);
15900         clearYMD_HMS_TZ(p);
15901       }
15902       break;
15903     }
15904 #endif
15905     case 'u': {
15906       /*
15907       **    unixepoch
15908       **
15909       ** Treat the current value of p->iJD as the number of
15910       ** seconds since 1970.  Convert to a real julian day number.
15911       */
15912       if( strcmp(z, "unixepoch")==0 && p->validJD ){
15913         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15914         clearYMD_HMS_TZ(p);
15915         rc = 0;
15916       }
15917 #ifndef SQLCIPHER_OMIT_LOCALTIME
15918       else if( strcmp(z, "utc")==0 ){
15919         sqlcipher3_int64 c1;
15920         computeJD(p);
15921         c1 = localtimeOffset(p, pCtx, &rc);
15922         if( rc==SQLCIPHER_OK ){
15923           p->iJD -= c1;
15924           clearYMD_HMS_TZ(p);
15925           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15926         }
15927       }
15928 #endif
15929       break;
15930     }
15931     case 'w': {
15932       /*
15933       **    weekday N
15934       **
15935       ** Move the date to the same time on the next occurrence of
15936       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
15937       ** date is already on the appropriate weekday, this is a no-op.
15938       */
15939       if( strncmp(z, "weekday ", 8)==0
15940                && sqlcipher3AtoF(&z[8], &r, sqlcipher3Strlen30(&z[8]), SQLCIPHER_UTF8)
15941                && (n=(int)r)==r && n>=0 && r<7 ){
15942         sqlcipher3_int64 Z;
15943         computeYMD_HMS(p);
15944         p->validTZ = 0;
15945         p->validJD = 0;
15946         computeJD(p);
15947         Z = ((p->iJD + 129600000)/86400000) % 7;
15948         if( Z>n ) Z -= 7;
15949         p->iJD += (n - Z)*86400000;
15950         clearYMD_HMS_TZ(p);
15951         rc = 0;
15952       }
15953       break;
15954     }
15955     case 's': {
15956       /*
15957       **    start of TTTTT
15958       **
15959       ** Move the date backwards to the beginning of the current day,
15960       ** or month or year.
15961       */
15962       if( strncmp(z, "start of ", 9)!=0 ) break;
15963       z += 9;
15964       computeYMD(p);
15965       p->validHMS = 1;
15966       p->h = p->m = 0;
15967       p->s = 0.0;
15968       p->validTZ = 0;
15969       p->validJD = 0;
15970       if( strcmp(z,"month")==0 ){
15971         p->D = 1;
15972         rc = 0;
15973       }else if( strcmp(z,"year")==0 ){
15974         computeYMD(p);
15975         p->M = 1;
15976         p->D = 1;
15977         rc = 0;
15978       }else if( strcmp(z,"day")==0 ){
15979         rc = 0;
15980       }
15981       break;
15982     }
15983     case '+':
15984     case '-':
15985     case '0':
15986     case '1':
15987     case '2':
15988     case '3':
15989     case '4':
15990     case '5':
15991     case '6':
15992     case '7':
15993     case '8':
15994     case '9': {
15995       double rRounder;
15996       for(n=1; z[n] && z[n]!=':' && !sqlcipher3Isspace(z[n]); n++){}
15997       if( !sqlcipher3AtoF(z, &r, n, SQLCIPHER_UTF8) ){
15998         rc = 1;
15999         break;
16000       }
16001       if( z[n]==':' ){
16002         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
16003         ** specified number of hours, minutes, seconds, and fractional seconds
16004         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
16005         ** omitted.
16006         */
16007         const char *z2 = z;
16008         DateTime tx;
16009         sqlcipher3_int64 day;
16010         if( !sqlcipher3Isdigit(*z2) ) z2++;
16011         memset(&tx, 0, sizeof(tx));
16012         if( parseHhMmSs(z2, &tx) ) break;
16013         computeJD(&tx);
16014         tx.iJD -= 43200000;
16015         day = tx.iJD/86400000;
16016         tx.iJD -= day*86400000;
16017         if( z[0]=='-' ) tx.iJD = -tx.iJD;
16018         computeJD(p);
16019         clearYMD_HMS_TZ(p);
16020         p->iJD += tx.iJD;
16021         rc = 0;
16022         break;
16023       }
16024       z += n;
16025       while( sqlcipher3Isspace(*z) ) z++;
16026       n = sqlcipher3Strlen30(z);
16027       if( n>10 || n<3 ) break;
16028       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
16029       computeJD(p);
16030       rc = 0;
16031       rRounder = r<0 ? -0.5 : +0.5;
16032       if( n==3 && strcmp(z,"day")==0 ){
16033         p->iJD += (sqlcipher3_int64)(r*86400000.0 + rRounder);
16034       }else if( n==4 && strcmp(z,"hour")==0 ){
16035         p->iJD += (sqlcipher3_int64)(r*(86400000.0/24.0) + rRounder);
16036       }else if( n==6 && strcmp(z,"minute")==0 ){
16037         p->iJD += (sqlcipher3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
16038       }else if( n==6 && strcmp(z,"second")==0 ){
16039         p->iJD += (sqlcipher3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
16040       }else if( n==5 && strcmp(z,"month")==0 ){
16041         int x, y;
16042         computeYMD_HMS(p);
16043         p->M += (int)r;
16044         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
16045         p->Y += x;
16046         p->M -= x*12;
16047         p->validJD = 0;
16048         computeJD(p);
16049         y = (int)r;
16050         if( y!=r ){
16051           p->iJD += (sqlcipher3_int64)((r - y)*30.0*86400000.0 + rRounder);
16052         }
16053       }else if( n==4 && strcmp(z,"year")==0 ){
16054         int y = (int)r;
16055         computeYMD_HMS(p);
16056         p->Y += y;
16057         p->validJD = 0;
16058         computeJD(p);
16059         if( y!=r ){
16060           p->iJD += (sqlcipher3_int64)((r - y)*365.0*86400000.0 + rRounder);
16061         }
16062       }else{
16063         rc = 1;
16064       }
16065       clearYMD_HMS_TZ(p);
16066       break;
16067     }
16068     default: {
16069       break;
16070     }
16071   }
16072   return rc;
16073 }
16074
16075 /*
16076 ** Process time function arguments.  argv[0] is a date-time stamp.
16077 ** argv[1] and following are modifiers.  Parse them all and write
16078 ** the resulting time into the DateTime structure p.  Return 0
16079 ** on success and 1 if there are any errors.
16080 **
16081 ** If there are zero parameters (if even argv[0] is undefined)
16082 ** then assume a default value of "now" for argv[0].
16083 */
16084 static int isDate(
16085   sqlcipher3_context *context, 
16086   int argc, 
16087   sqlcipher3_value **argv, 
16088   DateTime *p
16089 ){
16090   int i;
16091   const unsigned char *z;
16092   int eType;
16093   memset(p, 0, sizeof(*p));
16094   if( argc==0 ){
16095     return setDateTimeToCurrent(context, p);
16096   }
16097   if( (eType = sqlcipher3_value_type(argv[0]))==SQLCIPHER_FLOAT
16098                    || eType==SQLCIPHER_INTEGER ){
16099     p->iJD = (sqlcipher3_int64)(sqlcipher3_value_double(argv[0])*86400000.0 + 0.5);
16100     p->validJD = 1;
16101   }else{
16102     z = sqlcipher3_value_text(argv[0]);
16103     if( !z || parseDateOrTime(context, (char*)z, p) ){
16104       return 1;
16105     }
16106   }
16107   for(i=1; i<argc; i++){
16108     z = sqlcipher3_value_text(argv[i]);
16109     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
16110   }
16111   return 0;
16112 }
16113
16114
16115 /*
16116 ** The following routines implement the various date and time functions
16117 ** of SQLite.
16118 */
16119
16120 /*
16121 **    julianday( TIMESTRING, MOD, MOD, ...)
16122 **
16123 ** Return the julian day number of the date specified in the arguments
16124 */
16125 static void juliandayFunc(
16126   sqlcipher3_context *context,
16127   int argc,
16128   sqlcipher3_value **argv
16129 ){
16130   DateTime x;
16131   if( isDate(context, argc, argv, &x)==0 ){
16132     computeJD(&x);
16133     sqlcipher3_result_double(context, x.iJD/86400000.0);
16134   }
16135 }
16136
16137 /*
16138 **    datetime( TIMESTRING, MOD, MOD, ...)
16139 **
16140 ** Return YYYY-MM-DD HH:MM:SS
16141 */
16142 static void datetimeFunc(
16143   sqlcipher3_context *context,
16144   int argc,
16145   sqlcipher3_value **argv
16146 ){
16147   DateTime x;
16148   if( isDate(context, argc, argv, &x)==0 ){
16149     char zBuf[100];
16150     computeYMD_HMS(&x);
16151     sqlcipher3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
16152                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
16153     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16154   }
16155 }
16156
16157 /*
16158 **    time( TIMESTRING, MOD, MOD, ...)
16159 **
16160 ** Return HH:MM:SS
16161 */
16162 static void timeFunc(
16163   sqlcipher3_context *context,
16164   int argc,
16165   sqlcipher3_value **argv
16166 ){
16167   DateTime x;
16168   if( isDate(context, argc, argv, &x)==0 ){
16169     char zBuf[100];
16170     computeHMS(&x);
16171     sqlcipher3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
16172     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16173   }
16174 }
16175
16176 /*
16177 **    date( TIMESTRING, MOD, MOD, ...)
16178 **
16179 ** Return YYYY-MM-DD
16180 */
16181 static void dateFunc(
16182   sqlcipher3_context *context,
16183   int argc,
16184   sqlcipher3_value **argv
16185 ){
16186   DateTime x;
16187   if( isDate(context, argc, argv, &x)==0 ){
16188     char zBuf[100];
16189     computeYMD(&x);
16190     sqlcipher3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
16191     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16192   }
16193 }
16194
16195 /*
16196 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
16197 **
16198 ** Return a string described by FORMAT.  Conversions as follows:
16199 **
16200 **   %d  day of month
16201 **   %f  ** fractional seconds  SS.SSS
16202 **   %H  hour 00-24
16203 **   %j  day of year 000-366
16204 **   %J  ** Julian day number
16205 **   %m  month 01-12
16206 **   %M  minute 00-59
16207 **   %s  seconds since 1970-01-01
16208 **   %S  seconds 00-59
16209 **   %w  day of week 0-6  sunday==0
16210 **   %W  week of year 00-53
16211 **   %Y  year 0000-9999
16212 **   %%  %
16213 */
16214 static void strftimeFunc(
16215   sqlcipher3_context *context,
16216   int argc,
16217   sqlcipher3_value **argv
16218 ){
16219   DateTime x;
16220   u64 n;
16221   size_t i,j;
16222   char *z;
16223   sqlcipher3 *db;
16224   const char *zFmt = (const char*)sqlcipher3_value_text(argv[0]);
16225   char zBuf[100];
16226   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
16227   db = sqlcipher3_context_db_handle(context);
16228   for(i=0, n=1; zFmt[i]; i++, n++){
16229     if( zFmt[i]=='%' ){
16230       switch( zFmt[i+1] ){
16231         case 'd':
16232         case 'H':
16233         case 'm':
16234         case 'M':
16235         case 'S':
16236         case 'W':
16237           n++;
16238           /* fall thru */
16239         case 'w':
16240         case '%':
16241           break;
16242         case 'f':
16243           n += 8;
16244           break;
16245         case 'j':
16246           n += 3;
16247           break;
16248         case 'Y':
16249           n += 8;
16250           break;
16251         case 's':
16252         case 'J':
16253           n += 50;
16254           break;
16255         default:
16256           return;  /* ERROR.  return a NULL */
16257       }
16258       i++;
16259     }
16260   }
16261   testcase( n==sizeof(zBuf)-1 );
16262   testcase( n==sizeof(zBuf) );
16263   testcase( n==(u64)db->aLimit[SQLCIPHER_LIMIT_LENGTH]+1 );
16264   testcase( n==(u64)db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
16265   if( n<sizeof(zBuf) ){
16266     z = zBuf;
16267   }else if( n>(u64)db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
16268     sqlcipher3_result_error_toobig(context);
16269     return;
16270   }else{
16271     z = sqlcipher3DbMallocRaw(db, (int)n);
16272     if( z==0 ){
16273       sqlcipher3_result_error_nomem(context);
16274       return;
16275     }
16276   }
16277   computeJD(&x);
16278   computeYMD_HMS(&x);
16279   for(i=j=0; zFmt[i]; i++){
16280     if( zFmt[i]!='%' ){
16281       z[j++] = zFmt[i];
16282     }else{
16283       i++;
16284       switch( zFmt[i] ){
16285         case 'd':  sqlcipher3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
16286         case 'f': {
16287           double s = x.s;
16288           if( s>59.999 ) s = 59.999;
16289           sqlcipher3_snprintf(7, &z[j],"%06.3f", s);
16290           j += sqlcipher3Strlen30(&z[j]);
16291           break;
16292         }
16293         case 'H':  sqlcipher3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
16294         case 'W': /* Fall thru */
16295         case 'j': {
16296           int nDay;             /* Number of days since 1st day of year */
16297           DateTime y = x;
16298           y.validJD = 0;
16299           y.M = 1;
16300           y.D = 1;
16301           computeJD(&y);
16302           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
16303           if( zFmt[i]=='W' ){
16304             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
16305             wd = (int)(((x.iJD+43200000)/86400000)%7);
16306             sqlcipher3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
16307             j += 2;
16308           }else{
16309             sqlcipher3_snprintf(4, &z[j],"%03d",nDay+1);
16310             j += 3;
16311           }
16312           break;
16313         }
16314         case 'J': {
16315           sqlcipher3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
16316           j+=sqlcipher3Strlen30(&z[j]);
16317           break;
16318         }
16319         case 'm':  sqlcipher3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
16320         case 'M':  sqlcipher3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
16321         case 's': {
16322           sqlcipher3_snprintf(30,&z[j],"%lld",
16323                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
16324           j += sqlcipher3Strlen30(&z[j]);
16325           break;
16326         }
16327         case 'S':  sqlcipher3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
16328         case 'w': {
16329           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
16330           break;
16331         }
16332         case 'Y': {
16333           sqlcipher3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlcipher3Strlen30(&z[j]);
16334           break;
16335         }
16336         default:   z[j++] = '%'; break;
16337       }
16338     }
16339   }
16340   z[j] = 0;
16341   sqlcipher3_result_text(context, z, -1,
16342                       z==zBuf ? SQLCIPHER_TRANSIENT : SQLCIPHER_DYNAMIC);
16343 }
16344
16345 /*
16346 ** current_time()
16347 **
16348 ** This function returns the same value as time('now').
16349 */
16350 static void ctimeFunc(
16351   sqlcipher3_context *context,
16352   int NotUsed,
16353   sqlcipher3_value **NotUsed2
16354 ){
16355   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16356   timeFunc(context, 0, 0);
16357 }
16358
16359 /*
16360 ** current_date()
16361 **
16362 ** This function returns the same value as date('now').
16363 */
16364 static void cdateFunc(
16365   sqlcipher3_context *context,
16366   int NotUsed,
16367   sqlcipher3_value **NotUsed2
16368 ){
16369   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16370   dateFunc(context, 0, 0);
16371 }
16372
16373 /*
16374 ** current_timestamp()
16375 **
16376 ** This function returns the same value as datetime('now').
16377 */
16378 static void ctimestampFunc(
16379   sqlcipher3_context *context,
16380   int NotUsed,
16381   sqlcipher3_value **NotUsed2
16382 ){
16383   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16384   datetimeFunc(context, 0, 0);
16385 }
16386 #endif /* !defined(SQLCIPHER_OMIT_DATETIME_FUNCS) */
16387
16388 #ifdef SQLCIPHER_OMIT_DATETIME_FUNCS
16389 /*
16390 ** If the library is compiled to omit the full-scale date and time
16391 ** handling (to get a smaller binary), the following minimal version
16392 ** of the functions current_time(), current_date() and current_timestamp()
16393 ** are included instead. This is to support column declarations that
16394 ** include "DEFAULT CURRENT_TIME" etc.
16395 **
16396 ** This function uses the C-library functions time(), gmtime()
16397 ** and strftime(). The format string to pass to strftime() is supplied
16398 ** as the user-data for the function.
16399 */
16400 static void currentTimeFunc(
16401   sqlcipher3_context *context,
16402   int argc,
16403   sqlcipher3_value **argv
16404 ){
16405   time_t t;
16406   char *zFormat = (char *)sqlcipher3_user_data(context);
16407   sqlcipher3 *db;
16408   sqlcipher3_int64 iT;
16409   struct tm *pTm;
16410   struct tm sNow;
16411   char zBuf[20];
16412
16413   UNUSED_PARAMETER(argc);
16414   UNUSED_PARAMETER(argv);
16415
16416   db = sqlcipher3_context_db_handle(context);
16417   if( sqlcipher3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
16418   t = iT/1000 - 10000*(sqlcipher3_int64)21086676;
16419 #ifdef HAVE_GMTIME_R
16420   pTm = gmtime_r(&t, &sNow);
16421 #else
16422   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
16423   pTm = gmtime(&t);
16424   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
16425   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
16426 #endif
16427   if( pTm ){
16428     strftime(zBuf, 20, zFormat, &sNow);
16429     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
16430   }
16431 }
16432 #endif
16433
16434 /*
16435 ** This function registered all of the above C functions as SQL
16436 ** functions.  This should be the only routine in this file with
16437 ** external linkage.
16438 */
16439 SQLCIPHER_PRIVATE void sqlcipher3RegisterDateTimeFunctions(void){
16440   static SQLCIPHER_WSD FuncDef aDateTimeFuncs[] = {
16441 #ifndef SQLCIPHER_OMIT_DATETIME_FUNCS
16442     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
16443     FUNCTION(date,             -1, 0, 0, dateFunc      ),
16444     FUNCTION(time,             -1, 0, 0, timeFunc      ),
16445     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
16446     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
16447     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
16448     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
16449     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
16450 #else
16451     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
16452     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
16453     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
16454 #endif
16455   };
16456   int i;
16457   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
16458   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
16459
16460   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
16461     sqlcipher3FuncDefInsert(pHash, &aFunc[i]);
16462   }
16463 }
16464
16465 /************** End of date.c ************************************************/
16466 /************** Begin file os.c **********************************************/
16467 /*
16468 ** 2005 November 29
16469 **
16470 ** The author disclaims copyright to this source code.  In place of
16471 ** a legal notice, here is a blessing:
16472 **
16473 **    May you do good and not evil.
16474 **    May you find forgiveness for yourself and forgive others.
16475 **    May you share freely, never taking more than you give.
16476 **
16477 ******************************************************************************
16478 **
16479 ** This file contains OS interface code that is common to all
16480 ** architectures.
16481 */
16482 #define _SQLCIPHER_OS_C_ 1
16483 #undef _SQLCIPHER_OS_C_
16484
16485 /*
16486 ** The default SQLite sqlcipher3_vfs implementations do not allocate
16487 ** memory (actually, os_unix.c allocates a small amount of memory
16488 ** from within OsOpen()), but some third-party implementations may.
16489 ** So we test the effects of a malloc() failing and the sqlcipher3OsXXX()
16490 ** function returning SQLCIPHER_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
16491 **
16492 ** The following functions are instrumented for malloc() failure 
16493 ** testing:
16494 **
16495 **     sqlcipher3OsOpen()
16496 **     sqlcipher3OsRead()
16497 **     sqlcipher3OsWrite()
16498 **     sqlcipher3OsSync()
16499 **     sqlcipher3OsLock()
16500 **
16501 */
16502 #if defined(SQLCIPHER_TEST)
16503 SQLCIPHER_API int sqlcipher3_memdebug_vfs_oom_test = 1;
16504   #define DO_OS_MALLOC_TEST(x)                                       \
16505   if (sqlcipher3_memdebug_vfs_oom_test && (!x || !sqlcipher3IsMemJournal(x))) {  \
16506     void *pTstAlloc = sqlcipher3Malloc(10);                             \
16507     if (!pTstAlloc) return SQLCIPHER_IOERR_NOMEM;                       \
16508     sqlcipher3_free(pTstAlloc);                                         \
16509   }
16510 #else
16511   #define DO_OS_MALLOC_TEST(x)
16512 #endif
16513
16514 /*
16515 ** The following routines are convenience wrappers around methods
16516 ** of the sqlcipher3_file object.  This is mostly just syntactic sugar. All
16517 ** of this would be completely automatic if SQLite were coded using
16518 ** C++ instead of plain old C.
16519 */
16520 SQLCIPHER_PRIVATE int sqlcipher3OsClose(sqlcipher3_file *pId){
16521   int rc = SQLCIPHER_OK;
16522   if( pId->pMethods ){
16523     rc = pId->pMethods->xClose(pId);
16524     pId->pMethods = 0;
16525   }
16526   return rc;
16527 }
16528 SQLCIPHER_PRIVATE int sqlcipher3OsRead(sqlcipher3_file *id, void *pBuf, int amt, i64 offset){
16529   DO_OS_MALLOC_TEST(id);
16530   return id->pMethods->xRead(id, pBuf, amt, offset);
16531 }
16532 SQLCIPHER_PRIVATE int sqlcipher3OsWrite(sqlcipher3_file *id, const void *pBuf, int amt, i64 offset){
16533   DO_OS_MALLOC_TEST(id);
16534   return id->pMethods->xWrite(id, pBuf, amt, offset);
16535 }
16536 SQLCIPHER_PRIVATE int sqlcipher3OsTruncate(sqlcipher3_file *id, i64 size){
16537   return id->pMethods->xTruncate(id, size);
16538 }
16539 SQLCIPHER_PRIVATE int sqlcipher3OsSync(sqlcipher3_file *id, int flags){
16540   DO_OS_MALLOC_TEST(id);
16541   return id->pMethods->xSync(id, flags);
16542 }
16543 SQLCIPHER_PRIVATE int sqlcipher3OsFileSize(sqlcipher3_file *id, i64 *pSize){
16544   DO_OS_MALLOC_TEST(id);
16545   return id->pMethods->xFileSize(id, pSize);
16546 }
16547 SQLCIPHER_PRIVATE int sqlcipher3OsLock(sqlcipher3_file *id, int lockType){
16548   DO_OS_MALLOC_TEST(id);
16549   return id->pMethods->xLock(id, lockType);
16550 }
16551 SQLCIPHER_PRIVATE int sqlcipher3OsUnlock(sqlcipher3_file *id, int lockType){
16552   return id->pMethods->xUnlock(id, lockType);
16553 }
16554 SQLCIPHER_PRIVATE int sqlcipher3OsCheckReservedLock(sqlcipher3_file *id, int *pResOut){
16555   DO_OS_MALLOC_TEST(id);
16556   return id->pMethods->xCheckReservedLock(id, pResOut);
16557 }
16558 SQLCIPHER_PRIVATE int sqlcipher3OsFileControl(sqlcipher3_file *id, int op, void *pArg){
16559   return id->pMethods->xFileControl(id, op, pArg);
16560 }
16561 SQLCIPHER_PRIVATE int sqlcipher3OsSectorSize(sqlcipher3_file *id){
16562   int (*xSectorSize)(sqlcipher3_file*) = id->pMethods->xSectorSize;
16563   return (xSectorSize ? xSectorSize(id) : SQLCIPHER_DEFAULT_SECTOR_SIZE);
16564 }
16565 SQLCIPHER_PRIVATE int sqlcipher3OsDeviceCharacteristics(sqlcipher3_file *id){
16566   return id->pMethods->xDeviceCharacteristics(id);
16567 }
16568 SQLCIPHER_PRIVATE int sqlcipher3OsShmLock(sqlcipher3_file *id, int offset, int n, int flags){
16569   return id->pMethods->xShmLock(id, offset, n, flags);
16570 }
16571 SQLCIPHER_PRIVATE void sqlcipher3OsShmBarrier(sqlcipher3_file *id){
16572   id->pMethods->xShmBarrier(id);
16573 }
16574 SQLCIPHER_PRIVATE int sqlcipher3OsShmUnmap(sqlcipher3_file *id, int deleteFlag){
16575   return id->pMethods->xShmUnmap(id, deleteFlag);
16576 }
16577 SQLCIPHER_PRIVATE int sqlcipher3OsShmMap(
16578   sqlcipher3_file *id,               /* Database file handle */
16579   int iPage,
16580   int pgsz,
16581   int bExtend,                    /* True to extend file if necessary */
16582   void volatile **pp              /* OUT: Pointer to mapping */
16583 ){
16584   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16585 }
16586
16587 /*
16588 ** The next group of routines are convenience wrappers around the
16589 ** VFS methods.
16590 */
16591 SQLCIPHER_PRIVATE int sqlcipher3OsOpen(
16592   sqlcipher3_vfs *pVfs, 
16593   const char *zPath, 
16594   sqlcipher3_file *pFile, 
16595   int flags, 
16596   int *pFlagsOut
16597 ){
16598   int rc;
16599   DO_OS_MALLOC_TEST(0);
16600   /* 0x87f3f is a mask of SQLCIPHER_OPEN_ flags that are valid to be passed
16601   ** down into the VFS layer.  Some SQLCIPHER_OPEN_ flags (for example,
16602   ** SQLCIPHER_OPEN_FULLMUTEX or SQLCIPHER_OPEN_SHAREDCACHE) are blocked before
16603   ** reaching the VFS. */
16604   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16605   assert( rc==SQLCIPHER_OK || pFile->pMethods==0 );
16606   return rc;
16607 }
16608 SQLCIPHER_PRIVATE int sqlcipher3OsDelete(sqlcipher3_vfs *pVfs, const char *zPath, int dirSync){
16609   return pVfs->xDelete(pVfs, zPath, dirSync);
16610 }
16611 SQLCIPHER_PRIVATE int sqlcipher3OsAccess(
16612   sqlcipher3_vfs *pVfs, 
16613   const char *zPath, 
16614   int flags, 
16615   int *pResOut
16616 ){
16617   DO_OS_MALLOC_TEST(0);
16618   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16619 }
16620 SQLCIPHER_PRIVATE int sqlcipher3OsFullPathname(
16621   sqlcipher3_vfs *pVfs, 
16622   const char *zPath, 
16623   int nPathOut, 
16624   char *zPathOut
16625 ){
16626   zPathOut[0] = 0;
16627   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16628 }
16629 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
16630 SQLCIPHER_PRIVATE void *sqlcipher3OsDlOpen(sqlcipher3_vfs *pVfs, const char *zPath){
16631   return pVfs->xDlOpen(pVfs, zPath);
16632 }
16633 SQLCIPHER_PRIVATE void sqlcipher3OsDlError(sqlcipher3_vfs *pVfs, int nByte, char *zBufOut){
16634   pVfs->xDlError(pVfs, nByte, zBufOut);
16635 }
16636 SQLCIPHER_PRIVATE void (*sqlcipher3OsDlSym(sqlcipher3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16637   return pVfs->xDlSym(pVfs, pHdle, zSym);
16638 }
16639 SQLCIPHER_PRIVATE void sqlcipher3OsDlClose(sqlcipher3_vfs *pVfs, void *pHandle){
16640   pVfs->xDlClose(pVfs, pHandle);
16641 }
16642 #endif /* SQLCIPHER_OMIT_LOAD_EXTENSION */
16643 SQLCIPHER_PRIVATE int sqlcipher3OsRandomness(sqlcipher3_vfs *pVfs, int nByte, char *zBufOut){
16644   return pVfs->xRandomness(pVfs, nByte, zBufOut);
16645 }
16646 SQLCIPHER_PRIVATE int sqlcipher3OsSleep(sqlcipher3_vfs *pVfs, int nMicro){
16647   return pVfs->xSleep(pVfs, nMicro);
16648 }
16649 SQLCIPHER_PRIVATE int sqlcipher3OsCurrentTimeInt64(sqlcipher3_vfs *pVfs, sqlcipher3_int64 *pTimeOut){
16650   int rc;
16651   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16652   ** method to get the current date and time if that method is available
16653   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16654   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16655   ** unavailable.
16656   */
16657   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16658     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16659   }else{
16660     double r;
16661     rc = pVfs->xCurrentTime(pVfs, &r);
16662     *pTimeOut = (sqlcipher3_int64)(r*86400000.0);
16663   }
16664   return rc;
16665 }
16666
16667 SQLCIPHER_PRIVATE int sqlcipher3OsOpenMalloc(
16668   sqlcipher3_vfs *pVfs, 
16669   const char *zFile, 
16670   sqlcipher3_file **ppFile, 
16671   int flags,
16672   int *pOutFlags
16673 ){
16674   int rc = SQLCIPHER_NOMEM;
16675   sqlcipher3_file *pFile;
16676   pFile = (sqlcipher3_file *)sqlcipher3MallocZero(pVfs->szOsFile);
16677   if( pFile ){
16678     rc = sqlcipher3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16679     if( rc!=SQLCIPHER_OK ){
16680       sqlcipher3_free(pFile);
16681     }else{
16682       *ppFile = pFile;
16683     }
16684   }
16685   return rc;
16686 }
16687 SQLCIPHER_PRIVATE int sqlcipher3OsCloseFree(sqlcipher3_file *pFile){
16688   int rc = SQLCIPHER_OK;
16689   assert( pFile );
16690   rc = sqlcipher3OsClose(pFile);
16691   sqlcipher3_free(pFile);
16692   return rc;
16693 }
16694
16695 /*
16696 ** This function is a wrapper around the OS specific implementation of
16697 ** sqlcipher3_os_init(). The purpose of the wrapper is to provide the
16698 ** ability to simulate a malloc failure, so that the handling of an
16699 ** error in sqlcipher3_os_init() by the upper layers can be tested.
16700 */
16701 SQLCIPHER_PRIVATE int sqlcipher3OsInit(void){
16702   void *p = sqlcipher3_malloc(10);
16703   if( p==0 ) return SQLCIPHER_NOMEM;
16704   sqlcipher3_free(p);
16705   return sqlcipher3_os_init();
16706 }
16707
16708 /*
16709 ** The list of all registered VFS implementations.
16710 */
16711 static sqlcipher3_vfs * SQLCIPHER_WSD vfsList = 0;
16712 #define vfsList GLOBAL(sqlcipher3_vfs *, vfsList)
16713
16714 /*
16715 ** Locate a VFS by name.  If no name is given, simply return the
16716 ** first VFS on the list.
16717 */
16718 SQLCIPHER_API sqlcipher3_vfs *sqlcipher3_vfs_find(const char *zVfs){
16719   sqlcipher3_vfs *pVfs = 0;
16720 #if SQLCIPHER_THREADSAFE
16721   sqlcipher3_mutex *mutex;
16722 #endif
16723 #ifndef SQLCIPHER_OMIT_AUTOINIT
16724   int rc = sqlcipher3_initialize();
16725   if( rc ) return 0;
16726 #endif
16727 #if SQLCIPHER_THREADSAFE
16728   mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
16729 #endif
16730   sqlcipher3_mutex_enter(mutex);
16731   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16732     if( zVfs==0 ) break;
16733     if( strcmp(zVfs, pVfs->zName)==0 ) break;
16734   }
16735   sqlcipher3_mutex_leave(mutex);
16736   return pVfs;
16737 }
16738
16739 /*
16740 ** Unlink a VFS from the linked list
16741 */
16742 static void vfsUnlink(sqlcipher3_vfs *pVfs){
16743   assert( sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER)) );
16744   if( pVfs==0 ){
16745     /* No-op */
16746   }else if( vfsList==pVfs ){
16747     vfsList = pVfs->pNext;
16748   }else if( vfsList ){
16749     sqlcipher3_vfs *p = vfsList;
16750     while( p->pNext && p->pNext!=pVfs ){
16751       p = p->pNext;
16752     }
16753     if( p->pNext==pVfs ){
16754       p->pNext = pVfs->pNext;
16755     }
16756   }
16757 }
16758
16759 /*
16760 ** Register a VFS with the system.  It is harmless to register the same
16761 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
16762 ** true.
16763 */
16764 SQLCIPHER_API int sqlcipher3_vfs_register(sqlcipher3_vfs *pVfs, int makeDflt){
16765   MUTEX_LOGIC(sqlcipher3_mutex *mutex;)
16766 #ifndef SQLCIPHER_OMIT_AUTOINIT
16767   int rc = sqlcipher3_initialize();
16768   if( rc ) return rc;
16769 #endif
16770   MUTEX_LOGIC( mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER); )
16771   sqlcipher3_mutex_enter(mutex);
16772   vfsUnlink(pVfs);
16773   if( makeDflt || vfsList==0 ){
16774     pVfs->pNext = vfsList;
16775     vfsList = pVfs;
16776   }else{
16777     pVfs->pNext = vfsList->pNext;
16778     vfsList->pNext = pVfs;
16779   }
16780   assert(vfsList);
16781   sqlcipher3_mutex_leave(mutex);
16782   return SQLCIPHER_OK;
16783 }
16784
16785 /*
16786 ** Unregister a VFS so that it is no longer accessible.
16787 */
16788 SQLCIPHER_API int sqlcipher3_vfs_unregister(sqlcipher3_vfs *pVfs){
16789 #if SQLCIPHER_THREADSAFE
16790   sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
16791 #endif
16792   sqlcipher3_mutex_enter(mutex);
16793   vfsUnlink(pVfs);
16794   sqlcipher3_mutex_leave(mutex);
16795   return SQLCIPHER_OK;
16796 }
16797
16798 /************** End of os.c **************************************************/
16799 /************** Begin file fault.c *******************************************/
16800 /*
16801 ** 2008 Jan 22
16802 **
16803 ** The author disclaims copyright to this source code.  In place of
16804 ** a legal notice, here is a blessing:
16805 **
16806 **    May you do good and not evil.
16807 **    May you find forgiveness for yourself and forgive others.
16808 **    May you share freely, never taking more than you give.
16809 **
16810 *************************************************************************
16811 **
16812 ** This file contains code to support the concept of "benign" 
16813 ** malloc failures (when the xMalloc() or xRealloc() method of the
16814 ** sqlcipher3_mem_methods structure fails to allocate a block of memory
16815 ** and returns 0). 
16816 **
16817 ** Most malloc failures are non-benign. After they occur, SQLite
16818 ** abandons the current operation and returns an error code (usually
16819 ** SQLCIPHER_NOMEM) to the user. However, sometimes a fault is not necessarily
16820 ** fatal. For example, if a malloc fails while resizing a hash table, this 
16821 ** is completely recoverable simply by not carrying out the resize. The 
16822 ** hash table will continue to function normally.  So a malloc failure 
16823 ** during a hash table resize is a benign fault.
16824 */
16825
16826
16827 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
16828
16829 /*
16830 ** Global variables.
16831 */
16832 typedef struct BenignMallocHooks BenignMallocHooks;
16833 static SQLCIPHER_WSD struct BenignMallocHooks {
16834   void (*xBenignBegin)(void);
16835   void (*xBenignEnd)(void);
16836 } sqlcipher3Hooks = { 0, 0 };
16837
16838 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16839 ** structure.  If writable static data is unsupported on the target,
16840 ** we have to locate the state vector at run-time.  In the more common
16841 ** case where writable static data is supported, wsdHooks can refer directly
16842 ** to the "sqlcipher3Hooks" state vector declared above.
16843 */
16844 #ifdef SQLCIPHER_OMIT_WSD
16845 # define wsdHooksInit \
16846   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlcipher3Hooks)
16847 # define wsdHooks x[0]
16848 #else
16849 # define wsdHooksInit
16850 # define wsdHooks sqlcipher3Hooks
16851 #endif
16852
16853
16854 /*
16855 ** Register hooks to call when sqlcipher3BeginBenignMalloc() and
16856 ** sqlcipher3EndBenignMalloc() are called, respectively.
16857 */
16858 SQLCIPHER_PRIVATE void sqlcipher3BenignMallocHooks(
16859   void (*xBenignBegin)(void),
16860   void (*xBenignEnd)(void)
16861 ){
16862   wsdHooksInit;
16863   wsdHooks.xBenignBegin = xBenignBegin;
16864   wsdHooks.xBenignEnd = xBenignEnd;
16865 }
16866
16867 /*
16868 ** This (sqlcipher3EndBenignMalloc()) is called by SQLite code to indicate that
16869 ** subsequent malloc failures are benign. A call to sqlcipher3EndBenignMalloc()
16870 ** indicates that subsequent malloc failures are non-benign.
16871 */
16872 SQLCIPHER_PRIVATE void sqlcipher3BeginBenignMalloc(void){
16873   wsdHooksInit;
16874   if( wsdHooks.xBenignBegin ){
16875     wsdHooks.xBenignBegin();
16876   }
16877 }
16878 SQLCIPHER_PRIVATE void sqlcipher3EndBenignMalloc(void){
16879   wsdHooksInit;
16880   if( wsdHooks.xBenignEnd ){
16881     wsdHooks.xBenignEnd();
16882   }
16883 }
16884
16885 #endif   /* #ifndef SQLCIPHER_OMIT_BUILTIN_TEST */
16886
16887 /************** End of fault.c ***********************************************/
16888 /************** Begin file mem0.c ********************************************/
16889 /*
16890 ** 2008 October 28
16891 **
16892 ** The author disclaims copyright to this source code.  In place of
16893 ** a legal notice, here is a blessing:
16894 **
16895 **    May you do good and not evil.
16896 **    May you find forgiveness for yourself and forgive others.
16897 **    May you share freely, never taking more than you give.
16898 **
16899 *************************************************************************
16900 **
16901 ** This file contains a no-op memory allocation drivers for use when
16902 ** SQLCIPHER_ZERO_MALLOC is defined.  The allocation drivers implemented
16903 ** here always fail.  SQLite will not operate with these drivers.  These
16904 ** are merely placeholders.  Real drivers must be substituted using
16905 ** sqlcipher3_config() before SQLite will operate.
16906 */
16907
16908 /*
16909 ** This version of the memory allocator is the default.  It is
16910 ** used when no other memory allocator is specified using compile-time
16911 ** macros.
16912 */
16913 #ifdef SQLCIPHER_ZERO_MALLOC
16914
16915 /*
16916 ** No-op versions of all memory allocation routines
16917 */
16918 static void *sqlcipher3MemMalloc(int nByte){ return 0; }
16919 static void sqlcipher3MemFree(void *pPrior){ return; }
16920 static void *sqlcipher3MemRealloc(void *pPrior, int nByte){ return 0; }
16921 static int sqlcipher3MemSize(void *pPrior){ return 0; }
16922 static int sqlcipher3MemRoundup(int n){ return n; }
16923 static int sqlcipher3MemInit(void *NotUsed){ return SQLCIPHER_OK; }
16924 static void sqlcipher3MemShutdown(void *NotUsed){ return; }
16925
16926 /*
16927 ** This routine is the only routine in this file with external linkage.
16928 **
16929 ** Populate the low-level memory allocation function pointers in
16930 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file.
16931 */
16932 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
16933   static const sqlcipher3_mem_methods defaultMethods = {
16934      sqlcipher3MemMalloc,
16935      sqlcipher3MemFree,
16936      sqlcipher3MemRealloc,
16937      sqlcipher3MemSize,
16938      sqlcipher3MemRoundup,
16939      sqlcipher3MemInit,
16940      sqlcipher3MemShutdown,
16941      0
16942   };
16943   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, &defaultMethods);
16944 }
16945
16946 #endif /* SQLCIPHER_ZERO_MALLOC */
16947
16948 /************** End of mem0.c ************************************************/
16949 /************** Begin file mem1.c ********************************************/
16950 /*
16951 ** 2007 August 14
16952 **
16953 ** The author disclaims copyright to this source code.  In place of
16954 ** a legal notice, here is a blessing:
16955 **
16956 **    May you do good and not evil.
16957 **    May you find forgiveness for yourself and forgive others.
16958 **    May you share freely, never taking more than you give.
16959 **
16960 *************************************************************************
16961 **
16962 ** This file contains low-level memory allocation drivers for when
16963 ** SQLite will use the standard C-library malloc/realloc/free interface
16964 ** to obtain the memory it needs.
16965 **
16966 ** This file contains implementations of the low-level memory allocation
16967 ** routines specified in the sqlcipher3_mem_methods object.
16968 */
16969
16970 /*
16971 ** This version of the memory allocator is the default.  It is
16972 ** used when no other memory allocator is specified using compile-time
16973 ** macros.
16974 */
16975 #ifdef SQLCIPHER_SYSTEM_MALLOC
16976
16977 /*
16978 ** Like malloc(), but remember the size of the allocation
16979 ** so that we can find it later using sqlcipher3MemSize().
16980 **
16981 ** For this low-level routine, we are guaranteed that nByte>0 because
16982 ** cases of nByte<=0 will be intercepted and dealt with by higher level
16983 ** routines.
16984 */
16985 static void *sqlcipher3MemMalloc(int nByte){
16986   sqlcipher3_int64 *p;
16987   assert( nByte>0 );
16988   nByte = ROUND8(nByte);
16989   p = malloc( nByte+8 );
16990   if( p ){
16991     p[0] = nByte;
16992     p++;
16993   }else{
16994     testcase( sqlcipher3GlobalConfig.xLog!=0 );
16995     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to allocate %u bytes of memory", nByte);
16996   }
16997   return (void *)p;
16998 }
16999
17000 /*
17001 ** Like free() but works for allocations obtained from sqlcipher3MemMalloc()
17002 ** or sqlcipher3MemRealloc().
17003 **
17004 ** For this low-level routine, we already know that pPrior!=0 since
17005 ** cases where pPrior==0 will have been intecepted and dealt with
17006 ** by higher-level routines.
17007 */
17008 static void sqlcipher3MemFree(void *pPrior){
17009   sqlcipher3_int64 *p = (sqlcipher3_int64*)pPrior;
17010   assert( pPrior!=0 );
17011   p--;
17012   free(p);
17013 }
17014
17015 /*
17016 ** Report the allocated size of a prior return from xMalloc()
17017 ** or xRealloc().
17018 */
17019 static int sqlcipher3MemSize(void *pPrior){
17020   sqlcipher3_int64 *p;
17021   if( pPrior==0 ) return 0;
17022   p = (sqlcipher3_int64*)pPrior;
17023   p--;
17024   return (int)p[0];
17025 }
17026
17027 /*
17028 ** Like realloc().  Resize an allocation previously obtained from
17029 ** sqlcipher3MemMalloc().
17030 **
17031 ** For this low-level interface, we know that pPrior!=0.  Cases where
17032 ** pPrior==0 while have been intercepted by higher-level routine and
17033 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
17034 ** cases where nByte<=0 will have been intercepted by higher-level
17035 ** routines and redirected to xFree.
17036 */
17037 static void *sqlcipher3MemRealloc(void *pPrior, int nByte){
17038   sqlcipher3_int64 *p = (sqlcipher3_int64*)pPrior;
17039   assert( pPrior!=0 && nByte>0 );
17040   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
17041   p--;
17042   p = realloc(p, nByte+8 );
17043   if( p ){
17044     p[0] = nByte;
17045     p++;
17046   }else{
17047     testcase( sqlcipher3GlobalConfig.xLog!=0 );
17048     sqlcipher3_log(SQLCIPHER_NOMEM,
17049       "failed memory resize %u to %u bytes",
17050       sqlcipher3MemSize(pPrior), nByte);
17051   }
17052   return (void*)p;
17053 }
17054
17055 /*
17056 ** Round up a request size to the next valid allocation size.
17057 */
17058 static int sqlcipher3MemRoundup(int n){
17059   return ROUND8(n);
17060 }
17061
17062 /*
17063 ** Initialize this module.
17064 */
17065 static int sqlcipher3MemInit(void *NotUsed){
17066   UNUSED_PARAMETER(NotUsed);
17067   return SQLCIPHER_OK;
17068 }
17069
17070 /*
17071 ** Deinitialize this module.
17072 */
17073 static void sqlcipher3MemShutdown(void *NotUsed){
17074   UNUSED_PARAMETER(NotUsed);
17075   return;
17076 }
17077
17078 /*
17079 ** This routine is the only routine in this file with external linkage.
17080 **
17081 ** Populate the low-level memory allocation function pointers in
17082 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file.
17083 */
17084 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
17085   static const sqlcipher3_mem_methods defaultMethods = {
17086      sqlcipher3MemMalloc,
17087      sqlcipher3MemFree,
17088      sqlcipher3MemRealloc,
17089      sqlcipher3MemSize,
17090      sqlcipher3MemRoundup,
17091      sqlcipher3MemInit,
17092      sqlcipher3MemShutdown,
17093      0
17094   };
17095   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, &defaultMethods);
17096 }
17097
17098 #endif /* SQLCIPHER_SYSTEM_MALLOC */
17099
17100 /************** End of mem1.c ************************************************/
17101 /************** Begin file mem2.c ********************************************/
17102 /*
17103 ** 2007 August 15
17104 **
17105 ** The author disclaims copyright to this source code.  In place of
17106 ** a legal notice, here is a blessing:
17107 **
17108 **    May you do good and not evil.
17109 **    May you find forgiveness for yourself and forgive others.
17110 **    May you share freely, never taking more than you give.
17111 **
17112 *************************************************************************
17113 **
17114 ** This file contains low-level memory allocation drivers for when
17115 ** SQLite will use the standard C-library malloc/realloc/free interface
17116 ** to obtain the memory it needs while adding lots of additional debugging
17117 ** information to each allocation in order to help detect and fix memory
17118 ** leaks and memory usage errors.
17119 **
17120 ** This file contains implementations of the low-level memory allocation
17121 ** routines specified in the sqlcipher3_mem_methods object.
17122 */
17123
17124 /*
17125 ** This version of the memory allocator is used only if the
17126 ** SQLCIPHER_MEMDEBUG macro is defined
17127 */
17128 #ifdef SQLCIPHER_MEMDEBUG
17129
17130 /*
17131 ** The backtrace functionality is only available with GLIBC
17132 */
17133 #ifdef __GLIBC__
17134   extern int backtrace(void**,int);
17135   extern void backtrace_symbols_fd(void*const*,int,int);
17136 #else
17137 # define backtrace(A,B) 1
17138 # define backtrace_symbols_fd(A,B,C)
17139 #endif
17140 /* #include <stdio.h> */
17141
17142 /*
17143 ** Each memory allocation looks like this:
17144 **
17145 **  ------------------------------------------------------------------------
17146 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
17147 **  ------------------------------------------------------------------------
17148 **
17149 ** The application code sees only a pointer to the allocation.  We have
17150 ** to back up from the allocation pointer to find the MemBlockHdr.  The
17151 ** MemBlockHdr tells us the size of the allocation and the number of
17152 ** backtrace pointers.  There is also a guard word at the end of the
17153 ** MemBlockHdr.
17154 */
17155 struct MemBlockHdr {
17156   i64 iSize;                          /* Size of this allocation */
17157   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
17158   char nBacktrace;                    /* Number of backtraces on this alloc */
17159   char nBacktraceSlots;               /* Available backtrace slots */
17160   u8 nTitle;                          /* Bytes of title; includes '\0' */
17161   u8 eType;                           /* Allocation type code */
17162   int iForeGuard;                     /* Guard word for sanity */
17163 };
17164
17165 /*
17166 ** Guard words
17167 */
17168 #define FOREGUARD 0x80F5E153
17169 #define REARGUARD 0xE4676B53
17170
17171 /*
17172 ** Number of malloc size increments to track.
17173 */
17174 #define NCSIZE  1000
17175
17176 /*
17177 ** All of the static variables used by this module are collected
17178 ** into a single structure named "mem".  This is to keep the
17179 ** static variables organized and to reduce namespace pollution
17180 ** when this module is combined with other in the amalgamation.
17181 */
17182 static struct {
17183   
17184   /*
17185   ** Mutex to control access to the memory allocation subsystem.
17186   */
17187   sqlcipher3_mutex *mutex;
17188
17189   /*
17190   ** Head and tail of a linked list of all outstanding allocations
17191   */
17192   struct MemBlockHdr *pFirst;
17193   struct MemBlockHdr *pLast;
17194   
17195   /*
17196   ** The number of levels of backtrace to save in new allocations.
17197   */
17198   int nBacktrace;
17199   void (*xBacktrace)(int, int, void **);
17200
17201   /*
17202   ** Title text to insert in front of each block
17203   */
17204   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
17205   char zTitle[100];  /* The title text */
17206
17207   /* 
17208   ** sqlcipher3MallocDisallow() increments the following counter.
17209   ** sqlcipher3MallocAllow() decrements it.
17210   */
17211   int disallow; /* Do not allow memory allocation */
17212
17213   /*
17214   ** Gather statistics on the sizes of memory allocations.
17215   ** nAlloc[i] is the number of allocation attempts of i*8
17216   ** bytes.  i==NCSIZE is the number of allocation attempts for
17217   ** sizes more than NCSIZE*8 bytes.
17218   */
17219   int nAlloc[NCSIZE];      /* Total number of allocations */
17220   int nCurrent[NCSIZE];    /* Current number of allocations */
17221   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
17222
17223 } mem;
17224
17225
17226 /*
17227 ** Adjust memory usage statistics
17228 */
17229 static void adjustStats(int iSize, int increment){
17230   int i = ROUND8(iSize)/8;
17231   if( i>NCSIZE-1 ){
17232     i = NCSIZE - 1;
17233   }
17234   if( increment>0 ){
17235     mem.nAlloc[i]++;
17236     mem.nCurrent[i]++;
17237     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
17238       mem.mxCurrent[i] = mem.nCurrent[i];
17239     }
17240   }else{
17241     mem.nCurrent[i]--;
17242     assert( mem.nCurrent[i]>=0 );
17243   }
17244 }
17245
17246 /*
17247 ** Given an allocation, find the MemBlockHdr for that allocation.
17248 **
17249 ** This routine checks the guards at either end of the allocation and
17250 ** if they are incorrect it asserts.
17251 */
17252 static struct MemBlockHdr *sqlcipher3MemsysGetHeader(void *pAllocation){
17253   struct MemBlockHdr *p;
17254   int *pInt;
17255   u8 *pU8;
17256   int nReserve;
17257
17258   p = (struct MemBlockHdr*)pAllocation;
17259   p--;
17260   assert( p->iForeGuard==(int)FOREGUARD );
17261   nReserve = ROUND8(p->iSize);
17262   pInt = (int*)pAllocation;
17263   pU8 = (u8*)pAllocation;
17264   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
17265   /* This checks any of the "extra" bytes allocated due
17266   ** to rounding up to an 8 byte boundary to ensure 
17267   ** they haven't been overwritten.
17268   */
17269   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
17270   return p;
17271 }
17272
17273 /*
17274 ** Return the number of bytes currently allocated at address p.
17275 */
17276 static int sqlcipher3MemSize(void *p){
17277   struct MemBlockHdr *pHdr;
17278   if( !p ){
17279     return 0;
17280   }
17281   pHdr = sqlcipher3MemsysGetHeader(p);
17282   return pHdr->iSize;
17283 }
17284
17285 /*
17286 ** Initialize the memory allocation subsystem.
17287 */
17288 static int sqlcipher3MemInit(void *NotUsed){
17289   UNUSED_PARAMETER(NotUsed);
17290   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
17291   if( !sqlcipher3GlobalConfig.bMemstat ){
17292     /* If memory status is enabled, then the malloc.c wrapper will already
17293     ** hold the STATIC_MEM mutex when the routines here are invoked. */
17294     mem.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
17295   }
17296   return SQLCIPHER_OK;
17297 }
17298
17299 /*
17300 ** Deinitialize the memory allocation subsystem.
17301 */
17302 static void sqlcipher3MemShutdown(void *NotUsed){
17303   UNUSED_PARAMETER(NotUsed);
17304   mem.mutex = 0;
17305 }
17306
17307 /*
17308 ** Round up a request size to the next valid allocation size.
17309 */
17310 static int sqlcipher3MemRoundup(int n){
17311   return ROUND8(n);
17312 }
17313
17314 /*
17315 ** Fill a buffer with pseudo-random bytes.  This is used to preset
17316 ** the content of a new memory allocation to unpredictable values and
17317 ** to clear the content of a freed allocation to unpredictable values.
17318 */
17319 static void randomFill(char *pBuf, int nByte){
17320   unsigned int x, y, r;
17321   x = SQLCIPHER_PTR_TO_INT(pBuf);
17322   y = nByte | 1;
17323   while( nByte >= 4 ){
17324     x = (x>>1) ^ (-(x&1) & 0xd0000001);
17325     y = y*1103515245 + 12345;
17326     r = x ^ y;
17327     *(int*)pBuf = r;
17328     pBuf += 4;
17329     nByte -= 4;
17330   }
17331   while( nByte-- > 0 ){
17332     x = (x>>1) ^ (-(x&1) & 0xd0000001);
17333     y = y*1103515245 + 12345;
17334     r = x ^ y;
17335     *(pBuf++) = r & 0xff;
17336   }
17337 }
17338
17339 /*
17340 ** Allocate nByte bytes of memory.
17341 */
17342 static void *sqlcipher3MemMalloc(int nByte){
17343   struct MemBlockHdr *pHdr;
17344   void **pBt;
17345   char *z;
17346   int *pInt;
17347   void *p = 0;
17348   int totalSize;
17349   int nReserve;
17350   sqlcipher3_mutex_enter(mem.mutex);
17351   assert( mem.disallow==0 );
17352   nReserve = ROUND8(nByte);
17353   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
17354                mem.nBacktrace*sizeof(void*) + mem.nTitle;
17355   p = malloc(totalSize);
17356   if( p ){
17357     z = p;
17358     pBt = (void**)&z[mem.nTitle];
17359     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
17360     pHdr->pNext = 0;
17361     pHdr->pPrev = mem.pLast;
17362     if( mem.pLast ){
17363       mem.pLast->pNext = pHdr;
17364     }else{
17365       mem.pFirst = pHdr;
17366     }
17367     mem.pLast = pHdr;
17368     pHdr->iForeGuard = FOREGUARD;
17369     pHdr->eType = MEMTYPE_HEAP;
17370     pHdr->nBacktraceSlots = mem.nBacktrace;
17371     pHdr->nTitle = mem.nTitle;
17372     if( mem.nBacktrace ){
17373       void *aAddr[40];
17374       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17375       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17376       assert(pBt[0]);
17377       if( mem.xBacktrace ){
17378         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17379       }
17380     }else{
17381       pHdr->nBacktrace = 0;
17382     }
17383     if( mem.nTitle ){
17384       memcpy(z, mem.zTitle, mem.nTitle);
17385     }
17386     pHdr->iSize = nByte;
17387     adjustStats(nByte, +1);
17388     pInt = (int*)&pHdr[1];
17389     pInt[nReserve/sizeof(int)] = REARGUARD;
17390     randomFill((char*)pInt, nByte);
17391     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17392     p = (void*)pInt;
17393   }
17394   sqlcipher3_mutex_leave(mem.mutex);
17395   return p; 
17396 }
17397
17398 /*
17399 ** Free memory.
17400 */
17401 static void sqlcipher3MemFree(void *pPrior){
17402   struct MemBlockHdr *pHdr;
17403   void **pBt;
17404   char *z;
17405   assert( sqlcipher3GlobalConfig.bMemstat || sqlcipher3GlobalConfig.bCoreMutex==0 
17406        || mem.mutex!=0 );
17407   pHdr = sqlcipher3MemsysGetHeader(pPrior);
17408   pBt = (void**)pHdr;
17409   pBt -= pHdr->nBacktraceSlots;
17410   sqlcipher3_mutex_enter(mem.mutex);
17411   if( pHdr->pPrev ){
17412     assert( pHdr->pPrev->pNext==pHdr );
17413     pHdr->pPrev->pNext = pHdr->pNext;
17414   }else{
17415     assert( mem.pFirst==pHdr );
17416     mem.pFirst = pHdr->pNext;
17417   }
17418   if( pHdr->pNext ){
17419     assert( pHdr->pNext->pPrev==pHdr );
17420     pHdr->pNext->pPrev = pHdr->pPrev;
17421   }else{
17422     assert( mem.pLast==pHdr );
17423     mem.pLast = pHdr->pPrev;
17424   }
17425   z = (char*)pBt;
17426   z -= pHdr->nTitle;
17427   adjustStats(pHdr->iSize, -1);
17428   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17429                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
17430   free(z);
17431   sqlcipher3_mutex_leave(mem.mutex);  
17432 }
17433
17434 /*
17435 ** Change the size of an existing memory allocation.
17436 **
17437 ** For this debugging implementation, we *always* make a copy of the
17438 ** allocation into a new place in memory.  In this way, if the 
17439 ** higher level code is using pointer to the old allocation, it is 
17440 ** much more likely to break and we are much more liking to find
17441 ** the error.
17442 */
17443 static void *sqlcipher3MemRealloc(void *pPrior, int nByte){
17444   struct MemBlockHdr *pOldHdr;
17445   void *pNew;
17446   assert( mem.disallow==0 );
17447   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
17448   pOldHdr = sqlcipher3MemsysGetHeader(pPrior);
17449   pNew = sqlcipher3MemMalloc(nByte);
17450   if( pNew ){
17451     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
17452     if( nByte>pOldHdr->iSize ){
17453       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
17454     }
17455     sqlcipher3MemFree(pPrior);
17456   }
17457   return pNew;
17458 }
17459
17460 /*
17461 ** Populate the low-level memory allocation function pointers in
17462 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file.
17463 */
17464 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
17465   static const sqlcipher3_mem_methods defaultMethods = {
17466      sqlcipher3MemMalloc,
17467      sqlcipher3MemFree,
17468      sqlcipher3MemRealloc,
17469      sqlcipher3MemSize,
17470      sqlcipher3MemRoundup,
17471      sqlcipher3MemInit,
17472      sqlcipher3MemShutdown,
17473      0
17474   };
17475   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, &defaultMethods);
17476 }
17477
17478 /*
17479 ** Set the "type" of an allocation.
17480 */
17481 SQLCIPHER_PRIVATE void sqlcipher3MemdebugSetType(void *p, u8 eType){
17482   if( p && sqlcipher3GlobalConfig.m.xMalloc==sqlcipher3MemMalloc ){
17483     struct MemBlockHdr *pHdr;
17484     pHdr = sqlcipher3MemsysGetHeader(p);
17485     assert( pHdr->iForeGuard==FOREGUARD );
17486     pHdr->eType = eType;
17487   }
17488 }
17489
17490 /*
17491 ** Return TRUE if the mask of type in eType matches the type of the
17492 ** allocation p.  Also return true if p==NULL.
17493 **
17494 ** This routine is designed for use within an assert() statement, to
17495 ** verify the type of an allocation.  For example:
17496 **
17497 **     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
17498 */
17499 SQLCIPHER_PRIVATE int sqlcipher3MemdebugHasType(void *p, u8 eType){
17500   int rc = 1;
17501   if( p && sqlcipher3GlobalConfig.m.xMalloc==sqlcipher3MemMalloc ){
17502     struct MemBlockHdr *pHdr;
17503     pHdr = sqlcipher3MemsysGetHeader(p);
17504     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17505     if( (pHdr->eType&eType)==0 ){
17506       rc = 0;
17507     }
17508   }
17509   return rc;
17510 }
17511
17512 /*
17513 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17514 ** allocation p.  Also return true if p==NULL.
17515 **
17516 ** This routine is designed for use within an assert() statement, to
17517 ** verify the type of an allocation.  For example:
17518 **
17519 **     assert( sqlcipher3MemdebugNoType(p, MEMTYPE_DB) );
17520 */
17521 SQLCIPHER_PRIVATE int sqlcipher3MemdebugNoType(void *p, u8 eType){
17522   int rc = 1;
17523   if( p && sqlcipher3GlobalConfig.m.xMalloc==sqlcipher3MemMalloc ){
17524     struct MemBlockHdr *pHdr;
17525     pHdr = sqlcipher3MemsysGetHeader(p);
17526     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17527     if( (pHdr->eType&eType)!=0 ){
17528       rc = 0;
17529     }
17530   }
17531   return rc;
17532 }
17533
17534 /*
17535 ** Set the number of backtrace levels kept for each allocation.
17536 ** A value of zero turns off backtracing.  The number is always rounded
17537 ** up to a multiple of 2.
17538 */
17539 SQLCIPHER_PRIVATE void sqlcipher3MemdebugBacktrace(int depth){
17540   if( depth<0 ){ depth = 0; }
17541   if( depth>20 ){ depth = 20; }
17542   depth = (depth+1)&0xfe;
17543   mem.nBacktrace = depth;
17544 }
17545
17546 SQLCIPHER_PRIVATE void sqlcipher3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17547   mem.xBacktrace = xBacktrace;
17548 }
17549
17550 /*
17551 ** Set the title string for subsequent allocations.
17552 */
17553 SQLCIPHER_PRIVATE void sqlcipher3MemdebugSettitle(const char *zTitle){
17554   unsigned int n = sqlcipher3Strlen30(zTitle) + 1;
17555   sqlcipher3_mutex_enter(mem.mutex);
17556   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17557   memcpy(mem.zTitle, zTitle, n);
17558   mem.zTitle[n] = 0;
17559   mem.nTitle = ROUND8(n);
17560   sqlcipher3_mutex_leave(mem.mutex);
17561 }
17562
17563 SQLCIPHER_PRIVATE void sqlcipher3MemdebugSync(){
17564   struct MemBlockHdr *pHdr;
17565   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17566     void **pBt = (void**)pHdr;
17567     pBt -= pHdr->nBacktraceSlots;
17568     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17569   }
17570 }
17571
17572 /*
17573 ** Open the file indicated and write a log of all unfreed memory 
17574 ** allocations into that log.
17575 */
17576 SQLCIPHER_PRIVATE void sqlcipher3MemdebugDump(const char *zFilename){
17577   FILE *out;
17578   struct MemBlockHdr *pHdr;
17579   void **pBt;
17580   int i;
17581   out = fopen(zFilename, "w");
17582   if( out==0 ){
17583     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17584                     zFilename);
17585     return;
17586   }
17587   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17588     char *z = (char*)pHdr;
17589     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17590     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
17591             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17592     if( pHdr->nBacktrace ){
17593       fflush(out);
17594       pBt = (void**)pHdr;
17595       pBt -= pHdr->nBacktraceSlots;
17596       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17597       fprintf(out, "\n");
17598     }
17599   }
17600   fprintf(out, "COUNTS:\n");
17601   for(i=0; i<NCSIZE-1; i++){
17602     if( mem.nAlloc[i] ){
17603       fprintf(out, "   %5d: %10d %10d %10d\n", 
17604             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17605     }
17606   }
17607   if( mem.nAlloc[NCSIZE-1] ){
17608     fprintf(out, "   %5d: %10d %10d %10d\n",
17609              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17610              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17611   }
17612   fclose(out);
17613 }
17614
17615 /*
17616 ** Return the number of times sqlcipher3MemMalloc() has been called.
17617 */
17618 SQLCIPHER_PRIVATE int sqlcipher3MemdebugMallocCount(){
17619   int i;
17620   int nTotal = 0;
17621   for(i=0; i<NCSIZE; i++){
17622     nTotal += mem.nAlloc[i];
17623   }
17624   return nTotal;
17625 }
17626
17627
17628 #endif /* SQLCIPHER_MEMDEBUG */
17629
17630 /************** End of mem2.c ************************************************/
17631 /************** Begin file mem3.c ********************************************/
17632 /*
17633 ** 2007 October 14
17634 **
17635 ** The author disclaims copyright to this source code.  In place of
17636 ** a legal notice, here is a blessing:
17637 **
17638 **    May you do good and not evil.
17639 **    May you find forgiveness for yourself and forgive others.
17640 **    May you share freely, never taking more than you give.
17641 **
17642 *************************************************************************
17643 ** This file contains the C functions that implement a memory
17644 ** allocation subsystem for use by SQLite. 
17645 **
17646 ** This version of the memory allocation subsystem omits all
17647 ** use of malloc(). The SQLite user supplies a block of memory
17648 ** before calling sqlcipher3_initialize() from which allocations
17649 ** are made and returned by the xMalloc() and xRealloc() 
17650 ** implementations. Once sqlcipher3_initialize() has been called,
17651 ** the amount of memory available to SQLite is fixed and cannot
17652 ** be changed.
17653 **
17654 ** This version of the memory allocation subsystem is included
17655 ** in the build only if SQLCIPHER_ENABLE_MEMSYS3 is defined.
17656 */
17657
17658 /*
17659 ** This version of the memory allocator is only built into the library
17660 ** SQLCIPHER_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17661 ** mean that the library will use a memory-pool by default, just that
17662 ** it is available. The mempool allocator is activated by calling
17663 ** sqlcipher3_config().
17664 */
17665 #ifdef SQLCIPHER_ENABLE_MEMSYS3
17666
17667 /*
17668 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17669 */
17670 #define MX_SMALL 10
17671
17672
17673 /*
17674 ** Number of freelist hash slots
17675 */
17676 #define N_HASH  61
17677
17678 /*
17679 ** A memory allocation (also called a "chunk") consists of two or 
17680 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
17681 ** a header that is not returned to the user.
17682 **
17683 ** A chunk is two or more blocks that is either checked out or
17684 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
17685 ** size of the allocation in blocks if the allocation is free.
17686 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17687 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
17688 ** is true if the previous chunk is checked out and false if the
17689 ** previous chunk is free.  The u.hdr.prevSize field is the size of
17690 ** the previous chunk in blocks if the previous chunk is on the
17691 ** freelist. If the previous chunk is checked out, then
17692 ** u.hdr.prevSize can be part of the data for that chunk and should
17693 ** not be read or written.
17694 **
17695 ** We often identify a chunk by its index in mem3.aPool[].  When
17696 ** this is done, the chunk index refers to the second block of
17697 ** the chunk.  In this way, the first chunk has an index of 1.
17698 ** A chunk index of 0 means "no such chunk" and is the equivalent
17699 ** of a NULL pointer.
17700 **
17701 ** The second block of free chunks is of the form u.list.  The
17702 ** two fields form a double-linked list of chunks of related sizes.
17703 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
17704 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17705 **
17706 ** The second block of a chunk is user data if the chunk is checked 
17707 ** out.  If a chunk is checked out, the user data may extend into
17708 ** the u.hdr.prevSize value of the following chunk.
17709 */
17710 typedef struct Mem3Block Mem3Block;
17711 struct Mem3Block {
17712   union {
17713     struct {
17714       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
17715       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
17716     } hdr;
17717     struct {
17718       u32 next;       /* Index in mem3.aPool[] of next free chunk */
17719       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
17720     } list;
17721   } u;
17722 };
17723
17724 /*
17725 ** All of the static variables used by this module are collected
17726 ** into a single structure named "mem3".  This is to keep the
17727 ** static variables organized and to reduce namespace pollution
17728 ** when this module is combined with other in the amalgamation.
17729 */
17730 static SQLCIPHER_WSD struct Mem3Global {
17731   /*
17732   ** Memory available for allocation. nPool is the size of the array
17733   ** (in Mem3Blocks) pointed to by aPool less 2.
17734   */
17735   u32 nPool;
17736   Mem3Block *aPool;
17737
17738   /*
17739   ** True if we are evaluating an out-of-memory callback.
17740   */
17741   int alarmBusy;
17742   
17743   /*
17744   ** Mutex to control access to the memory allocation subsystem.
17745   */
17746   sqlcipher3_mutex *mutex;
17747   
17748   /*
17749   ** The minimum amount of free space that we have seen.
17750   */
17751   u32 mnMaster;
17752
17753   /*
17754   ** iMaster is the index of the master chunk.  Most new allocations
17755   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
17756   ** of the current master.  iMaster is 0 if there is not master chunk.
17757   ** The master chunk is not in either the aiHash[] or aiSmall[].
17758   */
17759   u32 iMaster;
17760   u32 szMaster;
17761
17762   /*
17763   ** Array of lists of free blocks according to the block size 
17764   ** for smaller chunks, or a hash on the block size for larger
17765   ** chunks.
17766   */
17767   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
17768   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
17769 } mem3 = { 97535575 };
17770
17771 #define mem3 GLOBAL(struct Mem3Global, mem3)
17772
17773 /*
17774 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17775 ** on.  *pRoot is the list that i is a member of.
17776 */
17777 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17778   u32 next = mem3.aPool[i].u.list.next;
17779   u32 prev = mem3.aPool[i].u.list.prev;
17780   assert( sqlcipher3_mutex_held(mem3.mutex) );
17781   if( prev==0 ){
17782     *pRoot = next;
17783   }else{
17784     mem3.aPool[prev].u.list.next = next;
17785   }
17786   if( next ){
17787     mem3.aPool[next].u.list.prev = prev;
17788   }
17789   mem3.aPool[i].u.list.next = 0;
17790   mem3.aPool[i].u.list.prev = 0;
17791 }
17792
17793 /*
17794 ** Unlink the chunk at index i from 
17795 ** whatever list is currently a member of.
17796 */
17797 static void memsys3Unlink(u32 i){
17798   u32 size, hash;
17799   assert( sqlcipher3_mutex_held(mem3.mutex) );
17800   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17801   assert( i>=1 );
17802   size = mem3.aPool[i-1].u.hdr.size4x/4;
17803   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17804   assert( size>=2 );
17805   if( size <= MX_SMALL ){
17806     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17807   }else{
17808     hash = size % N_HASH;
17809     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17810   }
17811 }
17812
17813 /*
17814 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17815 ** at *pRoot.
17816 */
17817 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17818   assert( sqlcipher3_mutex_held(mem3.mutex) );
17819   mem3.aPool[i].u.list.next = *pRoot;
17820   mem3.aPool[i].u.list.prev = 0;
17821   if( *pRoot ){
17822     mem3.aPool[*pRoot].u.list.prev = i;
17823   }
17824   *pRoot = i;
17825 }
17826
17827 /*
17828 ** Link the chunk at index i into either the appropriate
17829 ** small chunk list, or into the large chunk hash table.
17830 */
17831 static void memsys3Link(u32 i){
17832   u32 size, hash;
17833   assert( sqlcipher3_mutex_held(mem3.mutex) );
17834   assert( i>=1 );
17835   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17836   size = mem3.aPool[i-1].u.hdr.size4x/4;
17837   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17838   assert( size>=2 );
17839   if( size <= MX_SMALL ){
17840     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17841   }else{
17842     hash = size % N_HASH;
17843     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17844   }
17845 }
17846
17847 /*
17848 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17849 ** will already be held (obtained by code in malloc.c) if
17850 ** sqlcipher3GlobalConfig.bMemStat is true.
17851 */
17852 static void memsys3Enter(void){
17853   if( sqlcipher3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17854     mem3.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
17855   }
17856   sqlcipher3_mutex_enter(mem3.mutex);
17857 }
17858 static void memsys3Leave(void){
17859   sqlcipher3_mutex_leave(mem3.mutex);
17860 }
17861
17862 /*
17863 ** Called when we are unable to satisfy an allocation of nBytes.
17864 */
17865 static void memsys3OutOfMemory(int nByte){
17866   if( !mem3.alarmBusy ){
17867     mem3.alarmBusy = 1;
17868     assert( sqlcipher3_mutex_held(mem3.mutex) );
17869     sqlcipher3_mutex_leave(mem3.mutex);
17870     sqlcipher3_release_memory(nByte);
17871     sqlcipher3_mutex_enter(mem3.mutex);
17872     mem3.alarmBusy = 0;
17873   }
17874 }
17875
17876
17877 /*
17878 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
17879 ** size parameters for check-out and return a pointer to the 
17880 ** user portion of the chunk.
17881 */
17882 static void *memsys3Checkout(u32 i, u32 nBlock){
17883   u32 x;
17884   assert( sqlcipher3_mutex_held(mem3.mutex) );
17885   assert( i>=1 );
17886   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17887   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17888   x = mem3.aPool[i-1].u.hdr.size4x;
17889   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17890   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17891   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17892   return &mem3.aPool[i];
17893 }
17894
17895 /*
17896 ** Carve a piece off of the end of the mem3.iMaster free chunk.
17897 ** Return a pointer to the new allocation.  Or, if the master chunk
17898 ** is not large enough, return 0.
17899 */
17900 static void *memsys3FromMaster(u32 nBlock){
17901   assert( sqlcipher3_mutex_held(mem3.mutex) );
17902   assert( mem3.szMaster>=nBlock );
17903   if( nBlock>=mem3.szMaster-1 ){
17904     /* Use the entire master */
17905     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17906     mem3.iMaster = 0;
17907     mem3.szMaster = 0;
17908     mem3.mnMaster = 0;
17909     return p;
17910   }else{
17911     /* Split the master block.  Return the tail. */
17912     u32 newi, x;
17913     newi = mem3.iMaster + mem3.szMaster - nBlock;
17914     assert( newi > mem3.iMaster+1 );
17915     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17916     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17917     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17918     mem3.szMaster -= nBlock;
17919     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17920     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17921     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17922     if( mem3.szMaster < mem3.mnMaster ){
17923       mem3.mnMaster = mem3.szMaster;
17924     }
17925     return (void*)&mem3.aPool[newi];
17926   }
17927 }
17928
17929 /*
17930 ** *pRoot is the head of a list of free chunks of the same size
17931 ** or same size hash.  In other words, *pRoot is an entry in either
17932 ** mem3.aiSmall[] or mem3.aiHash[].  
17933 **
17934 ** This routine examines all entries on the given list and tries
17935 ** to coalesce each entries with adjacent free chunks.  
17936 **
17937 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
17938 ** the current mem3.iMaster with the new larger chunk.  In order for
17939 ** this mem3.iMaster replacement to work, the master chunk must be
17940 ** linked into the hash tables.  That is not the normal state of
17941 ** affairs, of course.  The calling routine must link the master
17942 ** chunk before invoking this routine, then must unlink the (possibly
17943 ** changed) master chunk once this routine has finished.
17944 */
17945 static void memsys3Merge(u32 *pRoot){
17946   u32 iNext, prev, size, i, x;
17947
17948   assert( sqlcipher3_mutex_held(mem3.mutex) );
17949   for(i=*pRoot; i>0; i=iNext){
17950     iNext = mem3.aPool[i].u.list.next;
17951     size = mem3.aPool[i-1].u.hdr.size4x;
17952     assert( (size&1)==0 );
17953     if( (size&2)==0 ){
17954       memsys3UnlinkFromList(i, pRoot);
17955       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17956       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17957       if( prev==iNext ){
17958         iNext = mem3.aPool[prev].u.list.next;
17959       }
17960       memsys3Unlink(prev);
17961       size = i + size/4 - prev;
17962       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17963       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17964       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17965       memsys3Link(prev);
17966       i = prev;
17967     }else{
17968       size /= 4;
17969     }
17970     if( size>mem3.szMaster ){
17971       mem3.iMaster = i;
17972       mem3.szMaster = size;
17973     }
17974   }
17975 }
17976
17977 /*
17978 ** Return a block of memory of at least nBytes in size.
17979 ** Return NULL if unable.
17980 **
17981 ** This function assumes that the necessary mutexes, if any, are
17982 ** already held by the caller. Hence "Unsafe".
17983 */
17984 static void *memsys3MallocUnsafe(int nByte){
17985   u32 i;
17986   u32 nBlock;
17987   u32 toFree;
17988
17989   assert( sqlcipher3_mutex_held(mem3.mutex) );
17990   assert( sizeof(Mem3Block)==8 );
17991   if( nByte<=12 ){
17992     nBlock = 2;
17993   }else{
17994     nBlock = (nByte + 11)/8;
17995   }
17996   assert( nBlock>=2 );
17997
17998   /* STEP 1:
17999   ** Look for an entry of the correct size in either the small
18000   ** chunk table or in the large chunk hash table.  This is
18001   ** successful most of the time (about 9 times out of 10).
18002   */
18003   if( nBlock <= MX_SMALL ){
18004     i = mem3.aiSmall[nBlock-2];
18005     if( i>0 ){
18006       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
18007       return memsys3Checkout(i, nBlock);
18008     }
18009   }else{
18010     int hash = nBlock % N_HASH;
18011     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
18012       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
18013         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18014         return memsys3Checkout(i, nBlock);
18015       }
18016     }
18017   }
18018
18019   /* STEP 2:
18020   ** Try to satisfy the allocation by carving a piece off of the end
18021   ** of the master chunk.  This step usually works if step 1 fails.
18022   */
18023   if( mem3.szMaster>=nBlock ){
18024     return memsys3FromMaster(nBlock);
18025   }
18026
18027
18028   /* STEP 3:  
18029   ** Loop through the entire memory pool.  Coalesce adjacent free
18030   ** chunks.  Recompute the master chunk as the largest free chunk.
18031   ** Then try again to satisfy the allocation by carving a piece off
18032   ** of the end of the master chunk.  This step happens very
18033   ** rarely (we hope!)
18034   */
18035   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
18036     memsys3OutOfMemory(toFree);
18037     if( mem3.iMaster ){
18038       memsys3Link(mem3.iMaster);
18039       mem3.iMaster = 0;
18040       mem3.szMaster = 0;
18041     }
18042     for(i=0; i<N_HASH; i++){
18043       memsys3Merge(&mem3.aiHash[i]);
18044     }
18045     for(i=0; i<MX_SMALL-1; i++){
18046       memsys3Merge(&mem3.aiSmall[i]);
18047     }
18048     if( mem3.szMaster ){
18049       memsys3Unlink(mem3.iMaster);
18050       if( mem3.szMaster>=nBlock ){
18051         return memsys3FromMaster(nBlock);
18052       }
18053     }
18054   }
18055
18056   /* If none of the above worked, then we fail. */
18057   return 0;
18058 }
18059
18060 /*
18061 ** Free an outstanding memory allocation.
18062 **
18063 ** This function assumes that the necessary mutexes, if any, are
18064 ** already held by the caller. Hence "Unsafe".
18065 */
18066 static void memsys3FreeUnsafe(void *pOld){
18067   Mem3Block *p = (Mem3Block*)pOld;
18068   int i;
18069   u32 size, x;
18070   assert( sqlcipher3_mutex_held(mem3.mutex) );
18071   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
18072   i = p - mem3.aPool;
18073   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
18074   size = mem3.aPool[i-1].u.hdr.size4x/4;
18075   assert( i+size<=mem3.nPool+1 );
18076   mem3.aPool[i-1].u.hdr.size4x &= ~1;
18077   mem3.aPool[i+size-1].u.hdr.prevSize = size;
18078   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
18079   memsys3Link(i);
18080
18081   /* Try to expand the master using the newly freed chunk */
18082   if( mem3.iMaster ){
18083     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
18084       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
18085       mem3.iMaster -= size;
18086       mem3.szMaster += size;
18087       memsys3Unlink(mem3.iMaster);
18088       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18089       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18090       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18091     }
18092     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18093     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
18094       memsys3Unlink(mem3.iMaster+mem3.szMaster);
18095       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
18096       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18097       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18098     }
18099   }
18100 }
18101
18102 /*
18103 ** Return the size of an outstanding allocation, in bytes.  The
18104 ** size returned omits the 8-byte header overhead.  This only
18105 ** works for chunks that are currently checked out.
18106 */
18107 static int memsys3Size(void *p){
18108   Mem3Block *pBlock;
18109   if( p==0 ) return 0;
18110   pBlock = (Mem3Block*)p;
18111   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
18112   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
18113 }
18114
18115 /*
18116 ** Round up a request size to the next valid allocation size.
18117 */
18118 static int memsys3Roundup(int n){
18119   if( n<=12 ){
18120     return 12;
18121   }else{
18122     return ((n+11)&~7) - 4;
18123   }
18124 }
18125
18126 /*
18127 ** Allocate nBytes of memory.
18128 */
18129 static void *memsys3Malloc(int nBytes){
18130   sqlcipher3_int64 *p;
18131   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
18132   memsys3Enter();
18133   p = memsys3MallocUnsafe(nBytes);
18134   memsys3Leave();
18135   return (void*)p; 
18136 }
18137
18138 /*
18139 ** Free memory.
18140 */
18141 static void memsys3Free(void *pPrior){
18142   assert( pPrior );
18143   memsys3Enter();
18144   memsys3FreeUnsafe(pPrior);
18145   memsys3Leave();
18146 }
18147
18148 /*
18149 ** Change the size of an existing memory allocation
18150 */
18151 static void *memsys3Realloc(void *pPrior, int nBytes){
18152   int nOld;
18153   void *p;
18154   if( pPrior==0 ){
18155     return sqlcipher3_malloc(nBytes);
18156   }
18157   if( nBytes<=0 ){
18158     sqlcipher3_free(pPrior);
18159     return 0;
18160   }
18161   nOld = memsys3Size(pPrior);
18162   if( nBytes<=nOld && nBytes>=nOld-128 ){
18163     return pPrior;
18164   }
18165   memsys3Enter();
18166   p = memsys3MallocUnsafe(nBytes);
18167   if( p ){
18168     if( nOld<nBytes ){
18169       memcpy(p, pPrior, nOld);
18170     }else{
18171       memcpy(p, pPrior, nBytes);
18172     }
18173     memsys3FreeUnsafe(pPrior);
18174   }
18175   memsys3Leave();
18176   return p;
18177 }
18178
18179 /*
18180 ** Initialize this module.
18181 */
18182 static int memsys3Init(void *NotUsed){
18183   UNUSED_PARAMETER(NotUsed);
18184   if( !sqlcipher3GlobalConfig.pHeap ){
18185     return SQLCIPHER_ERROR;
18186   }
18187
18188   /* Store a pointer to the memory block in global structure mem3. */
18189   assert( sizeof(Mem3Block)==8 );
18190   mem3.aPool = (Mem3Block *)sqlcipher3GlobalConfig.pHeap;
18191   mem3.nPool = (sqlcipher3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
18192
18193   /* Initialize the master block. */
18194   mem3.szMaster = mem3.nPool;
18195   mem3.mnMaster = mem3.szMaster;
18196   mem3.iMaster = 1;
18197   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
18198   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
18199   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
18200
18201   return SQLCIPHER_OK;
18202 }
18203
18204 /*
18205 ** Deinitialize this module.
18206 */
18207 static void memsys3Shutdown(void *NotUsed){
18208   UNUSED_PARAMETER(NotUsed);
18209   mem3.mutex = 0;
18210   return;
18211 }
18212
18213
18214
18215 /*
18216 ** Open the file indicated and write a log of all unfreed memory 
18217 ** allocations into that log.
18218 */
18219 SQLCIPHER_PRIVATE void sqlcipher3Memsys3Dump(const char *zFilename){
18220 #ifdef SQLCIPHER_DEBUG
18221   FILE *out;
18222   u32 i, j;
18223   u32 size;
18224   if( zFilename==0 || zFilename[0]==0 ){
18225     out = stdout;
18226   }else{
18227     out = fopen(zFilename, "w");
18228     if( out==0 ){
18229       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18230                       zFilename);
18231       return;
18232     }
18233   }
18234   memsys3Enter();
18235   fprintf(out, "CHUNKS:\n");
18236   for(i=1; i<=mem3.nPool; i+=size/4){
18237     size = mem3.aPool[i-1].u.hdr.size4x;
18238     if( size/4<=1 ){
18239       fprintf(out, "%p size error\n", &mem3.aPool[i]);
18240       assert( 0 );
18241       break;
18242     }
18243     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
18244       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
18245       assert( 0 );
18246       break;
18247     }
18248     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
18249       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
18250       assert( 0 );
18251       break;
18252     }
18253     if( size&1 ){
18254       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
18255     }else{
18256       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
18257                   i==mem3.iMaster ? " **master**" : "");
18258     }
18259   }
18260   for(i=0; i<MX_SMALL-1; i++){
18261     if( mem3.aiSmall[i]==0 ) continue;
18262     fprintf(out, "small(%2d):", i);
18263     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
18264       fprintf(out, " %p(%d)", &mem3.aPool[j],
18265               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18266     }
18267     fprintf(out, "\n"); 
18268   }
18269   for(i=0; i<N_HASH; i++){
18270     if( mem3.aiHash[i]==0 ) continue;
18271     fprintf(out, "hash(%2d):", i);
18272     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
18273       fprintf(out, " %p(%d)", &mem3.aPool[j],
18274               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18275     }
18276     fprintf(out, "\n"); 
18277   }
18278   fprintf(out, "master=%d\n", mem3.iMaster);
18279   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
18280   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
18281   sqlcipher3_mutex_leave(mem3.mutex);
18282   if( out==stdout ){
18283     fflush(stdout);
18284   }else{
18285     fclose(out);
18286   }
18287 #else
18288   UNUSED_PARAMETER(zFilename);
18289 #endif
18290 }
18291
18292 /*
18293 ** This routine is the only routine in this file with external 
18294 ** linkage.
18295 **
18296 ** Populate the low-level memory allocation function pointers in
18297 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file. The
18298 ** arguments specify the block of memory to manage.
18299 **
18300 ** This routine is only called by sqlcipher3_config(), and therefore
18301 ** is not required to be threadsafe (it is not).
18302 */
18303 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys3(void){
18304   static const sqlcipher3_mem_methods mempoolMethods = {
18305      memsys3Malloc,
18306      memsys3Free,
18307      memsys3Realloc,
18308      memsys3Size,
18309      memsys3Roundup,
18310      memsys3Init,
18311      memsys3Shutdown,
18312      0
18313   };
18314   return &mempoolMethods;
18315 }
18316
18317 #endif /* SQLCIPHER_ENABLE_MEMSYS3 */
18318
18319 /************** End of mem3.c ************************************************/
18320 /************** Begin file mem5.c ********************************************/
18321 /*
18322 ** 2007 October 14
18323 **
18324 ** The author disclaims copyright to this source code.  In place of
18325 ** a legal notice, here is a blessing:
18326 **
18327 **    May you do good and not evil.
18328 **    May you find forgiveness for yourself and forgive others.
18329 **    May you share freely, never taking more than you give.
18330 **
18331 *************************************************************************
18332 ** This file contains the C functions that implement a memory
18333 ** allocation subsystem for use by SQLite. 
18334 **
18335 ** This version of the memory allocation subsystem omits all
18336 ** use of malloc(). The application gives SQLite a block of memory
18337 ** before calling sqlcipher3_initialize() from which allocations
18338 ** are made and returned by the xMalloc() and xRealloc() 
18339 ** implementations. Once sqlcipher3_initialize() has been called,
18340 ** the amount of memory available to SQLite is fixed and cannot
18341 ** be changed.
18342 **
18343 ** This version of the memory allocation subsystem is included
18344 ** in the build only if SQLCIPHER_ENABLE_MEMSYS5 is defined.
18345 **
18346 ** This memory allocator uses the following algorithm:
18347 **
18348 **   1.  All memory allocations sizes are rounded up to a power of 2.
18349 **
18350 **   2.  If two adjacent free blocks are the halves of a larger block,
18351 **       then the two blocks are coalesed into the single larger block.
18352 **
18353 **   3.  New memory is allocated from the first available free block.
18354 **
18355 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
18356 ** Concerning Dynamic Storage Allocation". Journal of the Association for
18357 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
18358 ** 
18359 ** Let n be the size of the largest allocation divided by the minimum
18360 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
18361 ** be the maximum amount of memory ever outstanding at one time.  Let
18362 ** N be the total amount of memory available for allocation.  Robson
18363 ** proved that this memory allocator will never breakdown due to 
18364 ** fragmentation as long as the following constraint holds:
18365 **
18366 **      N >=  M*(1 + log2(n)/2) - n + 1
18367 **
18368 ** The sqlcipher3_status() logic tracks the maximum values of n and M so
18369 ** that an application can, at any time, verify this constraint.
18370 */
18371
18372 /*
18373 ** This version of the memory allocator is used only when 
18374 ** SQLCIPHER_ENABLE_MEMSYS5 is defined.
18375 */
18376 #ifdef SQLCIPHER_ENABLE_MEMSYS5
18377
18378 /*
18379 ** A minimum allocation is an instance of the following structure.
18380 ** Larger allocations are an array of these structures where the
18381 ** size of the array is a power of 2.
18382 **
18383 ** The size of this object must be a power of two.  That fact is
18384 ** verified in memsys5Init().
18385 */
18386 typedef struct Mem5Link Mem5Link;
18387 struct Mem5Link {
18388   int next;       /* Index of next free chunk */
18389   int prev;       /* Index of previous free chunk */
18390 };
18391
18392 /*
18393 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18394 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18395 ** it is not actually possible to reach this limit.
18396 */
18397 #define LOGMAX 30
18398
18399 /*
18400 ** Masks used for mem5.aCtrl[] elements.
18401 */
18402 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
18403 #define CTRL_FREE     0x20    /* True if not checked out */
18404
18405 /*
18406 ** All of the static variables used by this module are collected
18407 ** into a single structure named "mem5".  This is to keep the
18408 ** static variables organized and to reduce namespace pollution
18409 ** when this module is combined with other in the amalgamation.
18410 */
18411 static SQLCIPHER_WSD struct Mem5Global {
18412   /*
18413   ** Memory available for allocation
18414   */
18415   int szAtom;      /* Smallest possible allocation in bytes */
18416   int nBlock;      /* Number of szAtom sized blocks in zPool */
18417   u8 *zPool;       /* Memory available to be allocated */
18418   
18419   /*
18420   ** Mutex to control access to the memory allocation subsystem.
18421   */
18422   sqlcipher3_mutex *mutex;
18423
18424   /*
18425   ** Performance statistics
18426   */
18427   u64 nAlloc;         /* Total number of calls to malloc */
18428   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
18429   u64 totalExcess;    /* Total internal fragmentation */
18430   u32 currentOut;     /* Current checkout, including internal fragmentation */
18431   u32 currentCount;   /* Current number of distinct checkouts */
18432   u32 maxOut;         /* Maximum instantaneous currentOut */
18433   u32 maxCount;       /* Maximum instantaneous currentCount */
18434   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
18435   
18436   /*
18437   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
18438   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
18439   ** and so forth.
18440   */
18441   int aiFreelist[LOGMAX+1];
18442
18443   /*
18444   ** Space for tracking which blocks are checked out and the size
18445   ** of each block.  One byte per block.
18446   */
18447   u8 *aCtrl;
18448
18449 } mem5;
18450
18451 /*
18452 ** Access the static variable through a macro for SQLCIPHER_OMIT_WSD
18453 */
18454 #define mem5 GLOBAL(struct Mem5Global, mem5)
18455
18456 /*
18457 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18458 ** structures, return a pointer to the idx-th such lik.
18459 */
18460 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18461
18462 /*
18463 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18464 ** on.  It should be found on mem5.aiFreelist[iLogsize].
18465 */
18466 static void memsys5Unlink(int i, int iLogsize){
18467   int next, prev;
18468   assert( i>=0 && i<mem5.nBlock );
18469   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18470   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18471
18472   next = MEM5LINK(i)->next;
18473   prev = MEM5LINK(i)->prev;
18474   if( prev<0 ){
18475     mem5.aiFreelist[iLogsize] = next;
18476   }else{
18477     MEM5LINK(prev)->next = next;
18478   }
18479   if( next>=0 ){
18480     MEM5LINK(next)->prev = prev;
18481   }
18482 }
18483
18484 /*
18485 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18486 ** free list.
18487 */
18488 static void memsys5Link(int i, int iLogsize){
18489   int x;
18490   assert( sqlcipher3_mutex_held(mem5.mutex) );
18491   assert( i>=0 && i<mem5.nBlock );
18492   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18493   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18494
18495   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18496   MEM5LINK(i)->prev = -1;
18497   if( x>=0 ){
18498     assert( x<mem5.nBlock );
18499     MEM5LINK(x)->prev = i;
18500   }
18501   mem5.aiFreelist[iLogsize] = i;
18502 }
18503
18504 /*
18505 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18506 ** will already be held (obtained by code in malloc.c) if
18507 ** sqlcipher3GlobalConfig.bMemStat is true.
18508 */
18509 static void memsys5Enter(void){
18510   sqlcipher3_mutex_enter(mem5.mutex);
18511 }
18512 static void memsys5Leave(void){
18513   sqlcipher3_mutex_leave(mem5.mutex);
18514 }
18515
18516 /*
18517 ** Return the size of an outstanding allocation, in bytes.  The
18518 ** size returned omits the 8-byte header overhead.  This only
18519 ** works for chunks that are currently checked out.
18520 */
18521 static int memsys5Size(void *p){
18522   int iSize = 0;
18523   if( p ){
18524     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
18525     assert( i>=0 && i<mem5.nBlock );
18526     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18527   }
18528   return iSize;
18529 }
18530
18531 /*
18532 ** Find the first entry on the freelist iLogsize.  Unlink that
18533 ** entry and return its index. 
18534 */
18535 static int memsys5UnlinkFirst(int iLogsize){
18536   int i;
18537   int iFirst;
18538
18539   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18540   i = iFirst = mem5.aiFreelist[iLogsize];
18541   assert( iFirst>=0 );
18542   while( i>0 ){
18543     if( i<iFirst ) iFirst = i;
18544     i = MEM5LINK(i)->next;
18545   }
18546   memsys5Unlink(iFirst, iLogsize);
18547   return iFirst;
18548 }
18549
18550 /*
18551 ** Return a block of memory of at least nBytes in size.
18552 ** Return NULL if unable.  Return NULL if nBytes==0.
18553 **
18554 ** The caller guarantees that nByte positive.
18555 **
18556 ** The caller has obtained a mutex prior to invoking this
18557 ** routine so there is never any chance that two or more
18558 ** threads can be in this routine at the same time.
18559 */
18560 static void *memsys5MallocUnsafe(int nByte){
18561   int i;           /* Index of a mem5.aPool[] slot */
18562   int iBin;        /* Index into mem5.aiFreelist[] */
18563   int iFullSz;     /* Size of allocation rounded up to power of 2 */
18564   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
18565
18566   /* nByte must be a positive */
18567   assert( nByte>0 );
18568
18569   /* Keep track of the maximum allocation request.  Even unfulfilled
18570   ** requests are counted */
18571   if( (u32)nByte>mem5.maxRequest ){
18572     mem5.maxRequest = nByte;
18573   }
18574
18575   /* Abort if the requested allocation size is larger than the largest
18576   ** power of two that we can represent using 32-bit signed integers.
18577   */
18578   if( nByte > 0x40000000 ){
18579     return 0;
18580   }
18581
18582   /* Round nByte up to the next valid power of two */
18583   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18584
18585   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18586   ** block.  If not, then split a block of the next larger power of
18587   ** two in order to create a new free block of size iLogsize.
18588   */
18589   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
18590   if( iBin>LOGMAX ){
18591     testcase( sqlcipher3GlobalConfig.xLog!=0 );
18592     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to allocate %u bytes", nByte);
18593     return 0;
18594   }
18595   i = memsys5UnlinkFirst(iBin);
18596   while( iBin>iLogsize ){
18597     int newSize;
18598
18599     iBin--;
18600     newSize = 1 << iBin;
18601     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18602     memsys5Link(i+newSize, iBin);
18603   }
18604   mem5.aCtrl[i] = iLogsize;
18605
18606   /* Update allocator performance statistics. */
18607   mem5.nAlloc++;
18608   mem5.totalAlloc += iFullSz;
18609   mem5.totalExcess += iFullSz - nByte;
18610   mem5.currentCount++;
18611   mem5.currentOut += iFullSz;
18612   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18613   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18614
18615   /* Return a pointer to the allocated memory. */
18616   return (void*)&mem5.zPool[i*mem5.szAtom];
18617 }
18618
18619 /*
18620 ** Free an outstanding memory allocation.
18621 */
18622 static void memsys5FreeUnsafe(void *pOld){
18623   u32 size, iLogsize;
18624   int iBlock;
18625
18626   /* Set iBlock to the index of the block pointed to by pOld in 
18627   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18628   */
18629   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
18630
18631   /* Check that the pointer pOld points to a valid, non-free block. */
18632   assert( iBlock>=0 && iBlock<mem5.nBlock );
18633   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18634   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18635
18636   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18637   size = 1<<iLogsize;
18638   assert( iBlock+size-1<(u32)mem5.nBlock );
18639
18640   mem5.aCtrl[iBlock] |= CTRL_FREE;
18641   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18642   assert( mem5.currentCount>0 );
18643   assert( mem5.currentOut>=(size*mem5.szAtom) );
18644   mem5.currentCount--;
18645   mem5.currentOut -= size*mem5.szAtom;
18646   assert( mem5.currentOut>0 || mem5.currentCount==0 );
18647   assert( mem5.currentCount>0 || mem5.currentOut==0 );
18648
18649   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18650   while( ALWAYS(iLogsize<LOGMAX) ){
18651     int iBuddy;
18652     if( (iBlock>>iLogsize) & 1 ){
18653       iBuddy = iBlock - size;
18654     }else{
18655       iBuddy = iBlock + size;
18656     }
18657     assert( iBuddy>=0 );
18658     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18659     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18660     memsys5Unlink(iBuddy, iLogsize);
18661     iLogsize++;
18662     if( iBuddy<iBlock ){
18663       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18664       mem5.aCtrl[iBlock] = 0;
18665       iBlock = iBuddy;
18666     }else{
18667       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18668       mem5.aCtrl[iBuddy] = 0;
18669     }
18670     size *= 2;
18671   }
18672   memsys5Link(iBlock, iLogsize);
18673 }
18674
18675 /*
18676 ** Allocate nBytes of memory
18677 */
18678 static void *memsys5Malloc(int nBytes){
18679   sqlcipher3_int64 *p = 0;
18680   if( nBytes>0 ){
18681     memsys5Enter();
18682     p = memsys5MallocUnsafe(nBytes);
18683     memsys5Leave();
18684   }
18685   return (void*)p; 
18686 }
18687
18688 /*
18689 ** Free memory.
18690 **
18691 ** The outer layer memory allocator prevents this routine from
18692 ** being called with pPrior==0.
18693 */
18694 static void memsys5Free(void *pPrior){
18695   assert( pPrior!=0 );
18696   memsys5Enter();
18697   memsys5FreeUnsafe(pPrior);
18698   memsys5Leave();  
18699 }
18700
18701 /*
18702 ** Change the size of an existing memory allocation.
18703 **
18704 ** The outer layer memory allocator prevents this routine from
18705 ** being called with pPrior==0.  
18706 **
18707 ** nBytes is always a value obtained from a prior call to
18708 ** memsys5Round().  Hence nBytes is always a non-negative power
18709 ** of two.  If nBytes==0 that means that an oversize allocation
18710 ** (an allocation larger than 0x40000000) was requested and this
18711 ** routine should return 0 without freeing pPrior.
18712 */
18713 static void *memsys5Realloc(void *pPrior, int nBytes){
18714   int nOld;
18715   void *p;
18716   assert( pPrior!=0 );
18717   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
18718   assert( nBytes>=0 );
18719   if( nBytes==0 ){
18720     return 0;
18721   }
18722   nOld = memsys5Size(pPrior);
18723   if( nBytes<=nOld ){
18724     return pPrior;
18725   }
18726   memsys5Enter();
18727   p = memsys5MallocUnsafe(nBytes);
18728   if( p ){
18729     memcpy(p, pPrior, nOld);
18730     memsys5FreeUnsafe(pPrior);
18731   }
18732   memsys5Leave();
18733   return p;
18734 }
18735
18736 /*
18737 ** Round up a request size to the next valid allocation size.  If
18738 ** the allocation is too large to be handled by this allocation system,
18739 ** return 0.
18740 **
18741 ** All allocations must be a power of two and must be expressed by a
18742 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
18743 ** or 1073741824 bytes.
18744 */
18745 static int memsys5Roundup(int n){
18746   int iFullSz;
18747   if( n > 0x40000000 ) return 0;
18748   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18749   return iFullSz;
18750 }
18751
18752 /*
18753 ** Return the ceiling of the logarithm base 2 of iValue.
18754 **
18755 ** Examples:   memsys5Log(1) -> 0
18756 **             memsys5Log(2) -> 1
18757 **             memsys5Log(4) -> 2
18758 **             memsys5Log(5) -> 3
18759 **             memsys5Log(8) -> 3
18760 **             memsys5Log(9) -> 4
18761 */
18762 static int memsys5Log(int iValue){
18763   int iLog;
18764   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18765   return iLog;
18766 }
18767
18768 /*
18769 ** Initialize the memory allocator.
18770 **
18771 ** This routine is not threadsafe.  The caller must be holding a mutex
18772 ** to prevent multiple threads from entering at the same time.
18773 */
18774 static int memsys5Init(void *NotUsed){
18775   int ii;            /* Loop counter */
18776   int nByte;         /* Number of bytes of memory available to this allocator */
18777   u8 *zByte;         /* Memory usable by this allocator */
18778   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
18779   int iOffset;       /* An offset into mem5.aCtrl[] */
18780
18781   UNUSED_PARAMETER(NotUsed);
18782
18783   /* For the purposes of this routine, disable the mutex */
18784   mem5.mutex = 0;
18785
18786   /* The size of a Mem5Link object must be a power of two.  Verify that
18787   ** this is case.
18788   */
18789   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18790
18791   nByte = sqlcipher3GlobalConfig.nHeap;
18792   zByte = (u8*)sqlcipher3GlobalConfig.pHeap;
18793   assert( zByte!=0 );  /* sqlcipher3_config() does not allow otherwise */
18794
18795   /* boundaries on sqlcipher3GlobalConfig.mnReq are enforced in sqlcipher3_config() */
18796   nMinLog = memsys5Log(sqlcipher3GlobalConfig.mnReq);
18797   mem5.szAtom = (1<<nMinLog);
18798   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18799     mem5.szAtom = mem5.szAtom << 1;
18800   }
18801
18802   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18803   mem5.zPool = zByte;
18804   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18805
18806   for(ii=0; ii<=LOGMAX; ii++){
18807     mem5.aiFreelist[ii] = -1;
18808   }
18809
18810   iOffset = 0;
18811   for(ii=LOGMAX; ii>=0; ii--){
18812     int nAlloc = (1<<ii);
18813     if( (iOffset+nAlloc)<=mem5.nBlock ){
18814       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18815       memsys5Link(iOffset, ii);
18816       iOffset += nAlloc;
18817     }
18818     assert((iOffset+nAlloc)>mem5.nBlock);
18819   }
18820
18821   /* If a mutex is required for normal operation, allocate one */
18822   if( sqlcipher3GlobalConfig.bMemstat==0 ){
18823     mem5.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
18824   }
18825
18826   return SQLCIPHER_OK;
18827 }
18828
18829 /*
18830 ** Deinitialize this module.
18831 */
18832 static void memsys5Shutdown(void *NotUsed){
18833   UNUSED_PARAMETER(NotUsed);
18834   mem5.mutex = 0;
18835   return;
18836 }
18837
18838 #ifdef SQLCIPHER_TEST
18839 /*
18840 ** Open the file indicated and write a log of all unfreed memory 
18841 ** allocations into that log.
18842 */
18843 SQLCIPHER_PRIVATE void sqlcipher3Memsys5Dump(const char *zFilename){
18844   FILE *out;
18845   int i, j, n;
18846   int nMinLog;
18847
18848   if( zFilename==0 || zFilename[0]==0 ){
18849     out = stdout;
18850   }else{
18851     out = fopen(zFilename, "w");
18852     if( out==0 ){
18853       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18854                       zFilename);
18855       return;
18856     }
18857   }
18858   memsys5Enter();
18859   nMinLog = memsys5Log(mem5.szAtom);
18860   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18861     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18862     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18863   }
18864   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
18865   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
18866   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
18867   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
18868   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18869   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
18870   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
18871   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
18872   memsys5Leave();
18873   if( out==stdout ){
18874     fflush(stdout);
18875   }else{
18876     fclose(out);
18877   }
18878 }
18879 #endif
18880
18881 /*
18882 ** This routine is the only routine in this file with external 
18883 ** linkage. It returns a pointer to a static sqlcipher3_mem_methods
18884 ** struct populated with the memsys5 methods.
18885 */
18886 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetMemsys5(void){
18887   static const sqlcipher3_mem_methods memsys5Methods = {
18888      memsys5Malloc,
18889      memsys5Free,
18890      memsys5Realloc,
18891      memsys5Size,
18892      memsys5Roundup,
18893      memsys5Init,
18894      memsys5Shutdown,
18895      0
18896   };
18897   return &memsys5Methods;
18898 }
18899
18900 #endif /* SQLCIPHER_ENABLE_MEMSYS5 */
18901
18902 /************** End of mem5.c ************************************************/
18903 /************** Begin file mutex.c *******************************************/
18904 /*
18905 ** 2007 August 14
18906 **
18907 ** The author disclaims copyright to this source code.  In place of
18908 ** a legal notice, here is a blessing:
18909 **
18910 **    May you do good and not evil.
18911 **    May you find forgiveness for yourself and forgive others.
18912 **    May you share freely, never taking more than you give.
18913 **
18914 *************************************************************************
18915 ** This file contains the C functions that implement mutexes.
18916 **
18917 ** This file contains code that is common across all mutex implementations.
18918 */
18919
18920 #if defined(SQLCIPHER_DEBUG) && !defined(SQLCIPHER_MUTEX_OMIT)
18921 /*
18922 ** For debugging purposes, record when the mutex subsystem is initialized
18923 ** and uninitialized so that we can assert() if there is an attempt to
18924 ** allocate a mutex while the system is uninitialized.
18925 */
18926 static SQLCIPHER_WSD int mutexIsInit = 0;
18927 #endif /* SQLCIPHER_DEBUG */
18928
18929
18930 #ifndef SQLCIPHER_MUTEX_OMIT
18931 /*
18932 ** Initialize the mutex system.
18933 */
18934 SQLCIPHER_PRIVATE int sqlcipher3MutexInit(void){ 
18935   int rc = SQLCIPHER_OK;
18936   if( !sqlcipher3GlobalConfig.mutex.xMutexAlloc ){
18937     /* If the xMutexAlloc method has not been set, then the user did not
18938     ** install a mutex implementation via sqlcipher3_config() prior to 
18939     ** sqlcipher3_initialize() being called. This block copies pointers to
18940     ** the default implementation into the sqlcipher3GlobalConfig structure.
18941     */
18942     sqlcipher3_mutex_methods const *pFrom;
18943     sqlcipher3_mutex_methods *pTo = &sqlcipher3GlobalConfig.mutex;
18944
18945     if( sqlcipher3GlobalConfig.bCoreMutex ){
18946       pFrom = sqlcipher3DefaultMutex();
18947     }else{
18948       pFrom = sqlcipher3NoopMutex();
18949     }
18950     memcpy(pTo, pFrom, offsetof(sqlcipher3_mutex_methods, xMutexAlloc));
18951     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18952            sizeof(*pTo) - offsetof(sqlcipher3_mutex_methods, xMutexFree));
18953     pTo->xMutexAlloc = pFrom->xMutexAlloc;
18954   }
18955   rc = sqlcipher3GlobalConfig.mutex.xMutexInit();
18956
18957 #ifdef SQLCIPHER_DEBUG
18958   GLOBAL(int, mutexIsInit) = 1;
18959 #endif
18960
18961   return rc;
18962 }
18963
18964 /*
18965 ** Shutdown the mutex system. This call frees resources allocated by
18966 ** sqlcipher3MutexInit().
18967 */
18968 SQLCIPHER_PRIVATE int sqlcipher3MutexEnd(void){
18969   int rc = SQLCIPHER_OK;
18970   if( sqlcipher3GlobalConfig.mutex.xMutexEnd ){
18971     rc = sqlcipher3GlobalConfig.mutex.xMutexEnd();
18972   }
18973
18974 #ifdef SQLCIPHER_DEBUG
18975   GLOBAL(int, mutexIsInit) = 0;
18976 #endif
18977
18978   return rc;
18979 }
18980
18981 /*
18982 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18983 */
18984 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_mutex_alloc(int id){
18985 #ifndef SQLCIPHER_OMIT_AUTOINIT
18986   if( sqlcipher3_initialize() ) return 0;
18987 #endif
18988   return sqlcipher3GlobalConfig.mutex.xMutexAlloc(id);
18989 }
18990
18991 SQLCIPHER_PRIVATE sqlcipher3_mutex *sqlcipher3MutexAlloc(int id){
18992   if( !sqlcipher3GlobalConfig.bCoreMutex ){
18993     return 0;
18994   }
18995   assert( GLOBAL(int, mutexIsInit) );
18996   return sqlcipher3GlobalConfig.mutex.xMutexAlloc(id);
18997 }
18998
18999 /*
19000 ** Free a dynamic mutex.
19001 */
19002 SQLCIPHER_API void sqlcipher3_mutex_free(sqlcipher3_mutex *p){
19003   if( p ){
19004     sqlcipher3GlobalConfig.mutex.xMutexFree(p);
19005   }
19006 }
19007
19008 /*
19009 ** Obtain the mutex p. If some other thread already has the mutex, block
19010 ** until it can be obtained.
19011 */
19012 SQLCIPHER_API void sqlcipher3_mutex_enter(sqlcipher3_mutex *p){
19013   if( p ){
19014     sqlcipher3GlobalConfig.mutex.xMutexEnter(p);
19015   }
19016 }
19017
19018 /*
19019 ** Obtain the mutex p. If successful, return SQLCIPHER_OK. Otherwise, if another
19020 ** thread holds the mutex and it cannot be obtained, return SQLCIPHER_BUSY.
19021 */
19022 SQLCIPHER_API int sqlcipher3_mutex_try(sqlcipher3_mutex *p){
19023   int rc = SQLCIPHER_OK;
19024   if( p ){
19025     return sqlcipher3GlobalConfig.mutex.xMutexTry(p);
19026   }
19027   return rc;
19028 }
19029
19030 /*
19031 ** The sqlcipher3_mutex_leave() routine exits a mutex that was previously
19032 ** entered by the same thread.  The behavior is undefined if the mutex 
19033 ** is not currently entered. If a NULL pointer is passed as an argument
19034 ** this function is a no-op.
19035 */
19036 SQLCIPHER_API void sqlcipher3_mutex_leave(sqlcipher3_mutex *p){
19037   if( p ){
19038     sqlcipher3GlobalConfig.mutex.xMutexLeave(p);
19039   }
19040 }
19041
19042 #ifndef NDEBUG
19043 /*
19044 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19045 ** intended for use inside assert() statements.
19046 */
19047 SQLCIPHER_API int sqlcipher3_mutex_held(sqlcipher3_mutex *p){
19048   return p==0 || sqlcipher3GlobalConfig.mutex.xMutexHeld(p);
19049 }
19050 SQLCIPHER_API int sqlcipher3_mutex_notheld(sqlcipher3_mutex *p){
19051   return p==0 || sqlcipher3GlobalConfig.mutex.xMutexNotheld(p);
19052 }
19053 #endif
19054
19055 #endif /* SQLCIPHER_MUTEX_OMIT */
19056
19057 /************** End of mutex.c ***********************************************/
19058 /************** Begin file mutex_noop.c **************************************/
19059 /*
19060 ** 2008 October 07
19061 **
19062 ** The author disclaims copyright to this source code.  In place of
19063 ** a legal notice, here is a blessing:
19064 **
19065 **    May you do good and not evil.
19066 **    May you find forgiveness for yourself and forgive others.
19067 **    May you share freely, never taking more than you give.
19068 **
19069 *************************************************************************
19070 ** This file contains the C functions that implement mutexes.
19071 **
19072 ** This implementation in this file does not provide any mutual
19073 ** exclusion and is thus suitable for use only in applications
19074 ** that use SQLite in a single thread.  The routines defined
19075 ** here are place-holders.  Applications can substitute working
19076 ** mutex routines at start-time using the
19077 **
19078 **     sqlcipher3_config(SQLCIPHER_CONFIG_MUTEX,...)
19079 **
19080 ** interface.
19081 **
19082 ** If compiled with SQLCIPHER_DEBUG, then additional logic is inserted
19083 ** that does error checking on mutexes to make sure they are being
19084 ** called correctly.
19085 */
19086
19087 #ifndef SQLCIPHER_MUTEX_OMIT
19088
19089 #ifndef SQLCIPHER_DEBUG
19090 /*
19091 ** Stub routines for all mutex methods.
19092 **
19093 ** This routines provide no mutual exclusion or error checking.
19094 */
19095 static int noopMutexInit(void){ return SQLCIPHER_OK; }
19096 static int noopMutexEnd(void){ return SQLCIPHER_OK; }
19097 static sqlcipher3_mutex *noopMutexAlloc(int id){ 
19098   UNUSED_PARAMETER(id);
19099   return (sqlcipher3_mutex*)8; 
19100 }
19101 static void noopMutexFree(sqlcipher3_mutex *p){ UNUSED_PARAMETER(p); return; }
19102 static void noopMutexEnter(sqlcipher3_mutex *p){ UNUSED_PARAMETER(p); return; }
19103 static int noopMutexTry(sqlcipher3_mutex *p){
19104   UNUSED_PARAMETER(p);
19105   return SQLCIPHER_OK;
19106 }
19107 static void noopMutexLeave(sqlcipher3_mutex *p){ UNUSED_PARAMETER(p); return; }
19108
19109 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3NoopMutex(void){
19110   static const sqlcipher3_mutex_methods sMutex = {
19111     noopMutexInit,
19112     noopMutexEnd,
19113     noopMutexAlloc,
19114     noopMutexFree,
19115     noopMutexEnter,
19116     noopMutexTry,
19117     noopMutexLeave,
19118
19119     0,
19120     0,
19121   };
19122
19123   return &sMutex;
19124 }
19125 #endif /* !SQLCIPHER_DEBUG */
19126
19127 #ifdef SQLCIPHER_DEBUG
19128 /*
19129 ** In this implementation, error checking is provided for testing
19130 ** and debugging purposes.  The mutexes still do not provide any
19131 ** mutual exclusion.
19132 */
19133
19134 /*
19135 ** The mutex object
19136 */
19137 typedef struct sqlcipher3_debug_mutex {
19138   int id;     /* The mutex type */
19139   int cnt;    /* Number of entries without a matching leave */
19140 } sqlcipher3_debug_mutex;
19141
19142 /*
19143 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19144 ** intended for use inside assert() statements.
19145 */
19146 static int debugMutexHeld(sqlcipher3_mutex *pX){
19147   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19148   return p==0 || p->cnt>0;
19149 }
19150 static int debugMutexNotheld(sqlcipher3_mutex *pX){
19151   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19152   return p==0 || p->cnt==0;
19153 }
19154
19155 /*
19156 ** Initialize and deinitialize the mutex subsystem.
19157 */
19158 static int debugMutexInit(void){ return SQLCIPHER_OK; }
19159 static int debugMutexEnd(void){ return SQLCIPHER_OK; }
19160
19161 /*
19162 ** The sqlcipher3_mutex_alloc() routine allocates a new
19163 ** mutex and returns a pointer to it.  If it returns NULL
19164 ** that means that a mutex could not be allocated. 
19165 */
19166 static sqlcipher3_mutex *debugMutexAlloc(int id){
19167   static sqlcipher3_debug_mutex aStatic[6];
19168   sqlcipher3_debug_mutex *pNew = 0;
19169   switch( id ){
19170     case SQLCIPHER_MUTEX_FAST:
19171     case SQLCIPHER_MUTEX_RECURSIVE: {
19172       pNew = sqlcipher3Malloc(sizeof(*pNew));
19173       if( pNew ){
19174         pNew->id = id;
19175         pNew->cnt = 0;
19176       }
19177       break;
19178     }
19179     default: {
19180       assert( id-2 >= 0 );
19181       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
19182       pNew = &aStatic[id-2];
19183       pNew->id = id;
19184       break;
19185     }
19186   }
19187   return (sqlcipher3_mutex*)pNew;
19188 }
19189
19190 /*
19191 ** This routine deallocates a previously allocated mutex.
19192 */
19193 static void debugMutexFree(sqlcipher3_mutex *pX){
19194   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19195   assert( p->cnt==0 );
19196   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19197   sqlcipher3_free(p);
19198 }
19199
19200 /*
19201 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
19202 ** to enter a mutex.  If another thread is already within the mutex,
19203 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
19204 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
19205 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
19206 ** be entered multiple times by the same thread.  In such cases the,
19207 ** mutex must be exited an equal number of times before another thread
19208 ** can enter.  If the same thread tries to enter any other kind of mutex
19209 ** more than once, the behavior is undefined.
19210 */
19211 static void debugMutexEnter(sqlcipher3_mutex *pX){
19212   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19213   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19214   p->cnt++;
19215 }
19216 static int debugMutexTry(sqlcipher3_mutex *pX){
19217   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19218   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19219   p->cnt++;
19220   return SQLCIPHER_OK;
19221 }
19222
19223 /*
19224 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
19225 ** previously entered by the same thread.  The behavior
19226 ** is undefined if the mutex is not currently entered or
19227 ** is not currently allocated.  SQLite will never do either.
19228 */
19229 static void debugMutexLeave(sqlcipher3_mutex *pX){
19230   sqlcipher3_debug_mutex *p = (sqlcipher3_debug_mutex*)pX;
19231   assert( debugMutexHeld(pX) );
19232   p->cnt--;
19233   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19234 }
19235
19236 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3NoopMutex(void){
19237   static const sqlcipher3_mutex_methods sMutex = {
19238     debugMutexInit,
19239     debugMutexEnd,
19240     debugMutexAlloc,
19241     debugMutexFree,
19242     debugMutexEnter,
19243     debugMutexTry,
19244     debugMutexLeave,
19245
19246     debugMutexHeld,
19247     debugMutexNotheld
19248   };
19249
19250   return &sMutex;
19251 }
19252 #endif /* SQLCIPHER_DEBUG */
19253
19254 /*
19255 ** If compiled with SQLCIPHER_MUTEX_NOOP, then the no-op mutex implementation
19256 ** is used regardless of the run-time threadsafety setting.
19257 */
19258 #ifdef SQLCIPHER_MUTEX_NOOP
19259 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
19260   return sqlcipher3NoopMutex();
19261 }
19262 #endif /* SQLCIPHER_MUTEX_NOOP */
19263 #endif /* SQLCIPHER_MUTEX_OMIT */
19264
19265 /************** End of mutex_noop.c ******************************************/
19266 /************** Begin file mutex_os2.c ***************************************/
19267 /*
19268 ** 2007 August 28
19269 **
19270 ** The author disclaims copyright to this source code.  In place of
19271 ** a legal notice, here is a blessing:
19272 **
19273 **    May you do good and not evil.
19274 **    May you find forgiveness for yourself and forgive others.
19275 **    May you share freely, never taking more than you give.
19276 **
19277 *************************************************************************
19278 ** This file contains the C functions that implement mutexes for OS/2
19279 */
19280
19281 /*
19282 ** The code in this file is only used if SQLCIPHER_MUTEX_OS2 is defined.
19283 ** See the mutex.h file for details.
19284 */
19285 #ifdef SQLCIPHER_MUTEX_OS2
19286
19287 /********************** OS/2 Mutex Implementation **********************
19288 **
19289 ** This implementation of mutexes is built using the OS/2 API.
19290 */
19291
19292 /*
19293 ** The mutex object
19294 ** Each recursive mutex is an instance of the following structure.
19295 */
19296 struct sqlcipher3_mutex {
19297   HMTX mutex;       /* Mutex controlling the lock */
19298   int  id;          /* Mutex type */
19299 #ifdef SQLCIPHER_DEBUG
19300  int   trace;       /* True to trace changes */
19301 #endif
19302 };
19303
19304 #ifdef SQLCIPHER_DEBUG
19305 #define SQLCIPHER3_MUTEX_INITIALIZER { 0, 0, 0 }
19306 #else
19307 #define SQLCIPHER3_MUTEX_INITIALIZER { 0, 0 }
19308 #endif
19309
19310 /*
19311 ** Initialize and deinitialize the mutex subsystem.
19312 */
19313 static int os2MutexInit(void){ return SQLCIPHER_OK; }
19314 static int os2MutexEnd(void){ return SQLCIPHER_OK; }
19315
19316 /*
19317 ** The sqlcipher3_mutex_alloc() routine allocates a new
19318 ** mutex and returns a pointer to it.  If it returns NULL
19319 ** that means that a mutex could not be allocated. 
19320 ** SQLite will unwind its stack and return an error.  The argument
19321 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
19322 **
19323 ** <ul>
19324 ** <li>  SQLCIPHER_MUTEX_FAST
19325 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
19326 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
19327 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
19328 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
19329 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
19330 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
19331 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU2
19332 ** </ul>
19333 **
19334 ** The first two constants cause sqlcipher3_mutex_alloc() to create
19335 ** a new mutex.  The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
19336 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
19337 ** The mutex implementation does not need to make a distinction
19338 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
19339 ** not want to.  But SQLite will only request a recursive mutex in
19340 ** cases where it really needs one.  If a faster non-recursive mutex
19341 ** implementation is available on the host platform, the mutex subsystem
19342 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
19343 **
19344 ** The other allowed parameters to sqlcipher3_mutex_alloc() each return
19345 ** a pointer to a static preexisting mutex.  Six static mutexes are
19346 ** used by the current version of SQLite.  Future versions of SQLite
19347 ** may add additional static mutexes.  Static mutexes are for internal
19348 ** use by SQLite only.  Applications that use SQLite mutexes should
19349 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
19350 ** SQLCIPHER_MUTEX_RECURSIVE.
19351 **
19352 ** Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
19353 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
19354 ** returns a different mutex on every call.  But for the static
19355 ** mutex types, the same mutex is returned on every call that has
19356 ** the same type number.
19357 */
19358 static sqlcipher3_mutex *os2MutexAlloc(int iType){
19359   sqlcipher3_mutex *p = NULL;
19360   switch( iType ){
19361     case SQLCIPHER_MUTEX_FAST:
19362     case SQLCIPHER_MUTEX_RECURSIVE: {
19363       p = sqlcipher3MallocZero( sizeof(*p) );
19364       if( p ){
19365         p->id = iType;
19366         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
19367           sqlcipher3_free( p );
19368           p = NULL;
19369         }
19370       }
19371       break;
19372     }
19373     default: {
19374       static volatile int isInit = 0;
19375       static sqlcipher3_mutex staticMutexes[6] = {
19376         SQLCIPHER3_MUTEX_INITIALIZER,
19377         SQLCIPHER3_MUTEX_INITIALIZER,
19378         SQLCIPHER3_MUTEX_INITIALIZER,
19379         SQLCIPHER3_MUTEX_INITIALIZER,
19380         SQLCIPHER3_MUTEX_INITIALIZER,
19381         SQLCIPHER3_MUTEX_INITIALIZER,
19382       };
19383       if ( !isInit ){
19384         APIRET rc;
19385         PTIB ptib;
19386         PPIB ppib;
19387         HMTX mutex;
19388         char name[32];
19389         DosGetInfoBlocks( &ptib, &ppib );
19390         sqlcipher3_snprintf( sizeof(name), name, "\\SEM32\\SQLCIPHER%04x",
19391                           ppib->pib_ulpid );
19392         while( !isInit ){
19393           mutex = 0;
19394           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
19395           if( rc == NO_ERROR ){
19396             unsigned int i;
19397             if( !isInit ){
19398               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
19399                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
19400               }
19401               isInit = 1;
19402             }
19403             DosCloseMutexSem( mutex );
19404           }else if( rc == ERROR_DUPLICATE_NAME ){
19405             DosSleep( 1 );
19406           }else{
19407             return p;
19408           }
19409         }
19410       }
19411       assert( iType-2 >= 0 );
19412       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
19413       p = &staticMutexes[iType-2];
19414       p->id = iType;
19415       break;
19416     }
19417   }
19418   return p;
19419 }
19420
19421
19422 /*
19423 ** This routine deallocates a previously allocated mutex.
19424 ** SQLite is careful to deallocate every mutex that it allocates.
19425 */
19426 static void os2MutexFree(sqlcipher3_mutex *p){
19427 #ifdef SQLCIPHER_DEBUG
19428   TID tid;
19429   PID pid;
19430   ULONG ulCount;
19431   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19432   assert( ulCount==0 );
19433   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19434 #endif
19435   DosCloseMutexSem( p->mutex );
19436   sqlcipher3_free( p );
19437 }
19438
19439 #ifdef SQLCIPHER_DEBUG
19440 /*
19441 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19442 ** intended for use inside assert() statements.
19443 */
19444 static int os2MutexHeld(sqlcipher3_mutex *p){
19445   TID tid;
19446   PID pid;
19447   ULONG ulCount;
19448   PTIB ptib;
19449   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19450   if( ulCount==0 || ( ulCount>1 && p->id!=SQLCIPHER_MUTEX_RECURSIVE ) )
19451     return 0;
19452   DosGetInfoBlocks(&ptib, NULL);
19453   return tid==ptib->tib_ptib2->tib2_ultid;
19454 }
19455 static int os2MutexNotheld(sqlcipher3_mutex *p){
19456   TID tid;
19457   PID pid;
19458   ULONG ulCount;
19459   PTIB ptib;
19460   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19461   if( ulCount==0 )
19462     return 1;
19463   DosGetInfoBlocks(&ptib, NULL);
19464   return tid!=ptib->tib_ptib2->tib2_ultid;
19465 }
19466 static void os2MutexTrace(sqlcipher3_mutex *p, char *pAction){
19467   TID   tid;
19468   PID   pid;
19469   ULONG ulCount;
19470   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
19471   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
19472 }
19473 #endif
19474
19475 /*
19476 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
19477 ** to enter a mutex.  If another thread is already within the mutex,
19478 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
19479 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
19480 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
19481 ** be entered multiple times by the same thread.  In such cases the,
19482 ** mutex must be exited an equal number of times before another thread
19483 ** can enter.  If the same thread tries to enter any other kind of mutex
19484 ** more than once, the behavior is undefined.
19485 */
19486 static void os2MutexEnter(sqlcipher3_mutex *p){
19487   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || os2MutexNotheld(p) );
19488   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
19489 #ifdef SQLCIPHER_DEBUG
19490   if( p->trace ) os2MutexTrace(p, "enter");
19491 #endif
19492 }
19493 static int os2MutexTry(sqlcipher3_mutex *p){
19494   int rc = SQLCIPHER_BUSY;
19495   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || os2MutexNotheld(p) );
19496   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
19497     rc = SQLCIPHER_OK;
19498 #ifdef SQLCIPHER_DEBUG
19499     if( p->trace ) os2MutexTrace(p, "try");
19500 #endif
19501   }
19502   return rc;
19503 }
19504
19505 /*
19506 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
19507 ** previously entered by the same thread.  The behavior
19508 ** is undefined if the mutex is not currently entered or
19509 ** is not currently allocated.  SQLite will never do either.
19510 */
19511 static void os2MutexLeave(sqlcipher3_mutex *p){
19512   assert( os2MutexHeld(p) );
19513   DosReleaseMutexSem(p->mutex);
19514 #ifdef SQLCIPHER_DEBUG
19515   if( p->trace ) os2MutexTrace(p, "leave");
19516 #endif
19517 }
19518
19519 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
19520   static const sqlcipher3_mutex_methods sMutex = {
19521     os2MutexInit,
19522     os2MutexEnd,
19523     os2MutexAlloc,
19524     os2MutexFree,
19525     os2MutexEnter,
19526     os2MutexTry,
19527     os2MutexLeave,
19528 #ifdef SQLCIPHER_DEBUG
19529     os2MutexHeld,
19530     os2MutexNotheld
19531 #else
19532     0,
19533     0
19534 #endif
19535   };
19536
19537   return &sMutex;
19538 }
19539 #endif /* SQLCIPHER_MUTEX_OS2 */
19540
19541 /************** End of mutex_os2.c *******************************************/
19542 /************** Begin file mutex_unix.c **************************************/
19543 /*
19544 ** 2007 August 28
19545 **
19546 ** The author disclaims copyright to this source code.  In place of
19547 ** a legal notice, here is a blessing:
19548 **
19549 **    May you do good and not evil.
19550 **    May you find forgiveness for yourself and forgive others.
19551 **    May you share freely, never taking more than you give.
19552 **
19553 *************************************************************************
19554 ** This file contains the C functions that implement mutexes for pthreads
19555 */
19556
19557 /*
19558 ** The code in this file is only used if we are compiling threadsafe
19559 ** under unix with pthreads.
19560 **
19561 ** Note that this implementation requires a version of pthreads that
19562 ** supports recursive mutexes.
19563 */
19564 #ifdef SQLCIPHER_MUTEX_PTHREADS
19565
19566 #include <pthread.h>
19567
19568 /*
19569 ** The sqlcipher3_mutex.id, sqlcipher3_mutex.nRef, and sqlcipher3_mutex.owner fields
19570 ** are necessary under two condidtions:  (1) Debug builds and (2) using
19571 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
19572 */
19573 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX)
19574 # define SQLCIPHER_MUTEX_NREF 1
19575 #else
19576 # define SQLCIPHER_MUTEX_NREF 0
19577 #endif
19578
19579 /*
19580 ** Each recursive mutex is an instance of the following structure.
19581 */
19582 struct sqlcipher3_mutex {
19583   pthread_mutex_t mutex;     /* Mutex controlling the lock */
19584 #if SQLCIPHER_MUTEX_NREF
19585   int id;                    /* Mutex type */
19586   volatile int nRef;         /* Number of entrances */
19587   volatile pthread_t owner;  /* Thread that is within this mutex */
19588   int trace;                 /* True to trace changes */
19589 #endif
19590 };
19591 #if SQLCIPHER_MUTEX_NREF
19592 #define SQLCIPHER3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
19593 #else
19594 #define SQLCIPHER3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
19595 #endif
19596
19597 /*
19598 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19599 ** intended for use only inside assert() statements.  On some platforms,
19600 ** there might be race conditions that can cause these routines to
19601 ** deliver incorrect results.  In particular, if pthread_equal() is
19602 ** not an atomic operation, then these routines might delivery
19603 ** incorrect results.  On most platforms, pthread_equal() is a 
19604 ** comparison of two integers and is therefore atomic.  But we are
19605 ** told that HPUX is not such a platform.  If so, then these routines
19606 ** will not always work correctly on HPUX.
19607 **
19608 ** On those platforms where pthread_equal() is not atomic, SQLite
19609 ** should be compiled without -DSQLCIPHER_DEBUG and with -DNDEBUG to
19610 ** make sure no assert() statements are evaluated and hence these
19611 ** routines are never called.
19612 */
19613 #if !defined(NDEBUG) || defined(SQLCIPHER_DEBUG)
19614 static int pthreadMutexHeld(sqlcipher3_mutex *p){
19615   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
19616 }
19617 static int pthreadMutexNotheld(sqlcipher3_mutex *p){
19618   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
19619 }
19620 #endif
19621
19622 /*
19623 ** Initialize and deinitialize the mutex subsystem.
19624 */
19625 static int pthreadMutexInit(void){ return SQLCIPHER_OK; }
19626 static int pthreadMutexEnd(void){ return SQLCIPHER_OK; }
19627
19628 /*
19629 ** The sqlcipher3_mutex_alloc() routine allocates a new
19630 ** mutex and returns a pointer to it.  If it returns NULL
19631 ** that means that a mutex could not be allocated.  SQLite
19632 ** will unwind its stack and return an error.  The argument
19633 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
19634 **
19635 ** <ul>
19636 ** <li>  SQLCIPHER_MUTEX_FAST
19637 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
19638 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
19639 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
19640 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
19641 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
19642 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
19643 ** <li>  SQLCIPHER_MUTEX_STATIC_PMEM
19644 ** </ul>
19645 **
19646 ** The first two constants cause sqlcipher3_mutex_alloc() to create
19647 ** a new mutex.  The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
19648 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
19649 ** The mutex implementation does not need to make a distinction
19650 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
19651 ** not want to.  But SQLite will only request a recursive mutex in
19652 ** cases where it really needs one.  If a faster non-recursive mutex
19653 ** implementation is available on the host platform, the mutex subsystem
19654 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
19655 **
19656 ** The other allowed parameters to sqlcipher3_mutex_alloc() each return
19657 ** a pointer to a static preexisting mutex.  Six static mutexes are
19658 ** used by the current version of SQLite.  Future versions of SQLite
19659 ** may add additional static mutexes.  Static mutexes are for internal
19660 ** use by SQLite only.  Applications that use SQLite mutexes should
19661 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
19662 ** SQLCIPHER_MUTEX_RECURSIVE.
19663 **
19664 ** Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
19665 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
19666 ** returns a different mutex on every call.  But for the static 
19667 ** mutex types, the same mutex is returned on every call that has
19668 ** the same type number.
19669 */
19670 static sqlcipher3_mutex *pthreadMutexAlloc(int iType){
19671   static sqlcipher3_mutex staticMutexes[] = {
19672     SQLCIPHER3_MUTEX_INITIALIZER,
19673     SQLCIPHER3_MUTEX_INITIALIZER,
19674     SQLCIPHER3_MUTEX_INITIALIZER,
19675     SQLCIPHER3_MUTEX_INITIALIZER,
19676     SQLCIPHER3_MUTEX_INITIALIZER,
19677     SQLCIPHER3_MUTEX_INITIALIZER
19678   };
19679   sqlcipher3_mutex *p;
19680   switch( iType ){
19681     case SQLCIPHER_MUTEX_RECURSIVE: {
19682       p = sqlcipher3MallocZero( sizeof(*p) );
19683       if( p ){
19684 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19685         /* If recursive mutexes are not available, we will have to
19686         ** build our own.  See below. */
19687         pthread_mutex_init(&p->mutex, 0);
19688 #else
19689         /* Use a recursive mutex if it is available */
19690         pthread_mutexattr_t recursiveAttr;
19691         pthread_mutexattr_init(&recursiveAttr);
19692         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19693         pthread_mutex_init(&p->mutex, &recursiveAttr);
19694         pthread_mutexattr_destroy(&recursiveAttr);
19695 #endif
19696 #if SQLCIPHER_MUTEX_NREF
19697         p->id = iType;
19698 #endif
19699       }
19700       break;
19701     }
19702     case SQLCIPHER_MUTEX_FAST: {
19703       p = sqlcipher3MallocZero( sizeof(*p) );
19704       if( p ){
19705 #if SQLCIPHER_MUTEX_NREF
19706         p->id = iType;
19707 #endif
19708         pthread_mutex_init(&p->mutex, 0);
19709       }
19710       break;
19711     }
19712     default: {
19713       assert( iType-2 >= 0 );
19714       assert( iType-2 < ArraySize(staticMutexes) );
19715       p = &staticMutexes[iType-2];
19716 #if SQLCIPHER_MUTEX_NREF
19717       p->id = iType;
19718 #endif
19719       break;
19720     }
19721   }
19722   return p;
19723 }
19724
19725
19726 /*
19727 ** This routine deallocates a previously
19728 ** allocated mutex.  SQLite is careful to deallocate every
19729 ** mutex that it allocates.
19730 */
19731 static void pthreadMutexFree(sqlcipher3_mutex *p){
19732   assert( p->nRef==0 );
19733   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19734   pthread_mutex_destroy(&p->mutex);
19735   sqlcipher3_free(p);
19736 }
19737
19738 /*
19739 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
19740 ** to enter a mutex.  If another thread is already within the mutex,
19741 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
19742 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
19743 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
19744 ** be entered multiple times by the same thread.  In such cases the,
19745 ** mutex must be exited an equal number of times before another thread
19746 ** can enter.  If the same thread tries to enter any other kind of mutex
19747 ** more than once, the behavior is undefined.
19748 */
19749 static void pthreadMutexEnter(sqlcipher3_mutex *p){
19750   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19751
19752 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19753   /* If recursive mutexes are not available, then we have to grow
19754   ** our own.  This implementation assumes that pthread_equal()
19755   ** is atomic - that it cannot be deceived into thinking self
19756   ** and p->owner are equal if p->owner changes between two values
19757   ** that are not equal to self while the comparison is taking place.
19758   ** This implementation also assumes a coherent cache - that 
19759   ** separate processes cannot read different values from the same
19760   ** address at the same time.  If either of these two conditions
19761   ** are not met, then the mutexes will fail and problems will result.
19762   */
19763   {
19764     pthread_t self = pthread_self();
19765     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19766       p->nRef++;
19767     }else{
19768       pthread_mutex_lock(&p->mutex);
19769       assert( p->nRef==0 );
19770       p->owner = self;
19771       p->nRef = 1;
19772     }
19773   }
19774 #else
19775   /* Use the built-in recursive mutexes if they are available.
19776   */
19777   pthread_mutex_lock(&p->mutex);
19778 #if SQLCIPHER_MUTEX_NREF
19779   assert( p->nRef>0 || p->owner==0 );
19780   p->owner = pthread_self();
19781   p->nRef++;
19782 #endif
19783 #endif
19784
19785 #ifdef SQLCIPHER_DEBUG
19786   if( p->trace ){
19787     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19788   }
19789 #endif
19790 }
19791 static int pthreadMutexTry(sqlcipher3_mutex *p){
19792   int rc;
19793   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19794
19795 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19796   /* If recursive mutexes are not available, then we have to grow
19797   ** our own.  This implementation assumes that pthread_equal()
19798   ** is atomic - that it cannot be deceived into thinking self
19799   ** and p->owner are equal if p->owner changes between two values
19800   ** that are not equal to self while the comparison is taking place.
19801   ** This implementation also assumes a coherent cache - that 
19802   ** separate processes cannot read different values from the same
19803   ** address at the same time.  If either of these two conditions
19804   ** are not met, then the mutexes will fail and problems will result.
19805   */
19806   {
19807     pthread_t self = pthread_self();
19808     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19809       p->nRef++;
19810       rc = SQLCIPHER_OK;
19811     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19812       assert( p->nRef==0 );
19813       p->owner = self;
19814       p->nRef = 1;
19815       rc = SQLCIPHER_OK;
19816     }else{
19817       rc = SQLCIPHER_BUSY;
19818     }
19819   }
19820 #else
19821   /* Use the built-in recursive mutexes if they are available.
19822   */
19823   if( pthread_mutex_trylock(&p->mutex)==0 ){
19824 #if SQLCIPHER_MUTEX_NREF
19825     p->owner = pthread_self();
19826     p->nRef++;
19827 #endif
19828     rc = SQLCIPHER_OK;
19829   }else{
19830     rc = SQLCIPHER_BUSY;
19831   }
19832 #endif
19833
19834 #ifdef SQLCIPHER_DEBUG
19835   if( rc==SQLCIPHER_OK && p->trace ){
19836     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19837   }
19838 #endif
19839   return rc;
19840 }
19841
19842 /*
19843 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
19844 ** previously entered by the same thread.  The behavior
19845 ** is undefined if the mutex is not currently entered or
19846 ** is not currently allocated.  SQLite will never do either.
19847 */
19848 static void pthreadMutexLeave(sqlcipher3_mutex *p){
19849   assert( pthreadMutexHeld(p) );
19850 #if SQLCIPHER_MUTEX_NREF
19851   p->nRef--;
19852   if( p->nRef==0 ) p->owner = 0;
19853 #endif
19854   assert( p->nRef==0 || p->id==SQLCIPHER_MUTEX_RECURSIVE );
19855
19856 #ifdef SQLCIPHER_HOMEGROWN_RECURSIVE_MUTEX
19857   if( p->nRef==0 ){
19858     pthread_mutex_unlock(&p->mutex);
19859   }
19860 #else
19861   pthread_mutex_unlock(&p->mutex);
19862 #endif
19863
19864 #ifdef SQLCIPHER_DEBUG
19865   if( p->trace ){
19866     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19867   }
19868 #endif
19869 }
19870
19871 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
19872   static const sqlcipher3_mutex_methods sMutex = {
19873     pthreadMutexInit,
19874     pthreadMutexEnd,
19875     pthreadMutexAlloc,
19876     pthreadMutexFree,
19877     pthreadMutexEnter,
19878     pthreadMutexTry,
19879     pthreadMutexLeave,
19880 #ifdef SQLCIPHER_DEBUG
19881     pthreadMutexHeld,
19882     pthreadMutexNotheld
19883 #else
19884     0,
19885     0
19886 #endif
19887   };
19888
19889   return &sMutex;
19890 }
19891
19892 #endif /* SQLCIPHER_MUTEX_PTHREAD */
19893
19894 /************** End of mutex_unix.c ******************************************/
19895 /************** Begin file mutex_w32.c ***************************************/
19896 /*
19897 ** 2007 August 14
19898 **
19899 ** The author disclaims copyright to this source code.  In place of
19900 ** a legal notice, here is a blessing:
19901 **
19902 **    May you do good and not evil.
19903 **    May you find forgiveness for yourself and forgive others.
19904 **    May you share freely, never taking more than you give.
19905 **
19906 *************************************************************************
19907 ** This file contains the C functions that implement mutexes for win32
19908 */
19909
19910 /*
19911 ** The code in this file is only used if we are compiling multithreaded
19912 ** on a win32 system.
19913 */
19914 #ifdef SQLCIPHER_MUTEX_W32
19915
19916 /*
19917 ** Each recursive mutex is an instance of the following structure.
19918 */
19919 struct sqlcipher3_mutex {
19920   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
19921   int id;                    /* Mutex type */
19922 #ifdef SQLCIPHER_DEBUG
19923   volatile int nRef;         /* Number of enterances */
19924   volatile DWORD owner;      /* Thread holding this mutex */
19925   int trace;                 /* True to trace changes */
19926 #endif
19927 };
19928 #define SQLCIPHER_W32_MUTEX_INITIALIZER { 0 }
19929 #ifdef SQLCIPHER_DEBUG
19930 #define SQLCIPHER3_MUTEX_INITIALIZER { SQLCIPHER_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
19931 #else
19932 #define SQLCIPHER3_MUTEX_INITIALIZER { SQLCIPHER_W32_MUTEX_INITIALIZER, 0 }
19933 #endif
19934
19935 /*
19936 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
19937 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
19938 **
19939 ** Here is an interesting observation:  Win95, Win98, and WinME lack
19940 ** the LockFileEx() API.  But we can still statically link against that
19941 ** API as long as we don't call it win running Win95/98/ME.  A call to
19942 ** this routine is used to determine if the host is Win95/98/ME or
19943 ** WinNT/2K/XP so that we will know whether or not we can safely call
19944 ** the LockFileEx() API.
19945 **
19946 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
19947 ** which is only available if your application was compiled with 
19948 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
19949 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
19950 ** this out as well.
19951 */
19952 #if 0
19953 #if SQLCIPHER_OS_WINCE
19954 # define mutexIsNT()  (1)
19955 #else
19956   static int mutexIsNT(void){
19957     static int osType = 0;
19958     if( osType==0 ){
19959       OSVERSIONINFO sInfo;
19960       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
19961       GetVersionEx(&sInfo);
19962       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
19963     }
19964     return osType==2;
19965   }
19966 #endif /* SQLCIPHER_OS_WINCE */
19967 #endif
19968
19969 #ifdef SQLCIPHER_DEBUG
19970 /*
19971 ** The sqlcipher3_mutex_held() and sqlcipher3_mutex_notheld() routine are
19972 ** intended for use only inside assert() statements.
19973 */
19974 static int winMutexHeld(sqlcipher3_mutex *p){
19975   return p->nRef!=0 && p->owner==GetCurrentThreadId();
19976 }
19977 static int winMutexNotheld2(sqlcipher3_mutex *p, DWORD tid){
19978   return p->nRef==0 || p->owner!=tid;
19979 }
19980 static int winMutexNotheld(sqlcipher3_mutex *p){
19981   DWORD tid = GetCurrentThreadId(); 
19982   return winMutexNotheld2(p, tid);
19983 }
19984 #endif
19985
19986
19987 /*
19988 ** Initialize and deinitialize the mutex subsystem.
19989 */
19990 static sqlcipher3_mutex winMutex_staticMutexes[6] = {
19991   SQLCIPHER3_MUTEX_INITIALIZER,
19992   SQLCIPHER3_MUTEX_INITIALIZER,
19993   SQLCIPHER3_MUTEX_INITIALIZER,
19994   SQLCIPHER3_MUTEX_INITIALIZER,
19995   SQLCIPHER3_MUTEX_INITIALIZER,
19996   SQLCIPHER3_MUTEX_INITIALIZER
19997 };
19998 static int winMutex_isInit = 0;
19999 /* As winMutexInit() and winMutexEnd() are called as part
20000 ** of the sqlcipher3_initialize and sqlcipher3_shutdown()
20001 ** processing, the "interlocked" magic is probably not
20002 ** strictly necessary.
20003 */
20004 static long winMutex_lock = 0;
20005
20006 static int winMutexInit(void){ 
20007   /* The first to increment to 1 does actual initialization */
20008   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
20009     int i;
20010     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20011       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
20012     }
20013     winMutex_isInit = 1;
20014   }else{
20015     /* Someone else is in the process of initing the static mutexes */
20016     while( !winMutex_isInit ){
20017       Sleep(1);
20018     }
20019   }
20020   return SQLCIPHER_OK; 
20021 }
20022
20023 static int winMutexEnd(void){ 
20024   /* The first to decrement to 0 does actual shutdown 
20025   ** (which should be the last to shutdown.) */
20026   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
20027     if( winMutex_isInit==1 ){
20028       int i;
20029       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20030         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
20031       }
20032       winMutex_isInit = 0;
20033     }
20034   }
20035   return SQLCIPHER_OK; 
20036 }
20037
20038 /*
20039 ** The sqlcipher3_mutex_alloc() routine allocates a new
20040 ** mutex and returns a pointer to it.  If it returns NULL
20041 ** that means that a mutex could not be allocated.  SQLite
20042 ** will unwind its stack and return an error.  The argument
20043 ** to sqlcipher3_mutex_alloc() is one of these integer constants:
20044 **
20045 ** <ul>
20046 ** <li>  SQLCIPHER_MUTEX_FAST
20047 ** <li>  SQLCIPHER_MUTEX_RECURSIVE
20048 ** <li>  SQLCIPHER_MUTEX_STATIC_MASTER
20049 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM
20050 ** <li>  SQLCIPHER_MUTEX_STATIC_MEM2
20051 ** <li>  SQLCIPHER_MUTEX_STATIC_PRNG
20052 ** <li>  SQLCIPHER_MUTEX_STATIC_LRU
20053 ** <li>  SQLCIPHER_MUTEX_STATIC_PMEM
20054 ** </ul>
20055 **
20056 ** The first two constants cause sqlcipher3_mutex_alloc() to create
20057 ** a new mutex.  The new mutex is recursive when SQLCIPHER_MUTEX_RECURSIVE
20058 ** is used but not necessarily so when SQLCIPHER_MUTEX_FAST is used.
20059 ** The mutex implementation does not need to make a distinction
20060 ** between SQLCIPHER_MUTEX_RECURSIVE and SQLCIPHER_MUTEX_FAST if it does
20061 ** not want to.  But SQLite will only request a recursive mutex in
20062 ** cases where it really needs one.  If a faster non-recursive mutex
20063 ** implementation is available on the host platform, the mutex subsystem
20064 ** might return such a mutex in response to SQLCIPHER_MUTEX_FAST.
20065 **
20066 ** The other allowed parameters to sqlcipher3_mutex_alloc() each return
20067 ** a pointer to a static preexisting mutex.  Six static mutexes are
20068 ** used by the current version of SQLite.  Future versions of SQLite
20069 ** may add additional static mutexes.  Static mutexes are for internal
20070 ** use by SQLite only.  Applications that use SQLite mutexes should
20071 ** use only the dynamic mutexes returned by SQLCIPHER_MUTEX_FAST or
20072 ** SQLCIPHER_MUTEX_RECURSIVE.
20073 **
20074 ** Note that if one of the dynamic mutex parameters (SQLCIPHER_MUTEX_FAST
20075 ** or SQLCIPHER_MUTEX_RECURSIVE) is used then sqlcipher3_mutex_alloc()
20076 ** returns a different mutex on every call.  But for the static 
20077 ** mutex types, the same mutex is returned on every call that has
20078 ** the same type number.
20079 */
20080 static sqlcipher3_mutex *winMutexAlloc(int iType){
20081   sqlcipher3_mutex *p;
20082
20083   switch( iType ){
20084     case SQLCIPHER_MUTEX_FAST:
20085     case SQLCIPHER_MUTEX_RECURSIVE: {
20086       p = sqlcipher3MallocZero( sizeof(*p) );
20087       if( p ){  
20088 #ifdef SQLCIPHER_DEBUG
20089         p->id = iType;
20090 #endif
20091         InitializeCriticalSection(&p->mutex);
20092       }
20093       break;
20094     }
20095     default: {
20096       assert( winMutex_isInit==1 );
20097       assert( iType-2 >= 0 );
20098       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
20099       p = &winMutex_staticMutexes[iType-2];
20100 #ifdef SQLCIPHER_DEBUG
20101       p->id = iType;
20102 #endif
20103       break;
20104     }
20105   }
20106   return p;
20107 }
20108
20109
20110 /*
20111 ** This routine deallocates a previously
20112 ** allocated mutex.  SQLite is careful to deallocate every
20113 ** mutex that it allocates.
20114 */
20115 static void winMutexFree(sqlcipher3_mutex *p){
20116   assert( p );
20117   assert( p->nRef==0 && p->owner==0 );
20118   assert( p->id==SQLCIPHER_MUTEX_FAST || p->id==SQLCIPHER_MUTEX_RECURSIVE );
20119   DeleteCriticalSection(&p->mutex);
20120   sqlcipher3_free(p);
20121 }
20122
20123 /*
20124 ** The sqlcipher3_mutex_enter() and sqlcipher3_mutex_try() routines attempt
20125 ** to enter a mutex.  If another thread is already within the mutex,
20126 ** sqlcipher3_mutex_enter() will block and sqlcipher3_mutex_try() will return
20127 ** SQLCIPHER_BUSY.  The sqlcipher3_mutex_try() interface returns SQLCIPHER_OK
20128 ** upon successful entry.  Mutexes created using SQLCIPHER_MUTEX_RECURSIVE can
20129 ** be entered multiple times by the same thread.  In such cases the,
20130 ** mutex must be exited an equal number of times before another thread
20131 ** can enter.  If the same thread tries to enter any other kind of mutex
20132 ** more than once, the behavior is undefined.
20133 */
20134 static void winMutexEnter(sqlcipher3_mutex *p){
20135 #ifdef SQLCIPHER_DEBUG
20136   DWORD tid = GetCurrentThreadId(); 
20137   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20138 #endif
20139   EnterCriticalSection(&p->mutex);
20140 #ifdef SQLCIPHER_DEBUG
20141   assert( p->nRef>0 || p->owner==0 );
20142   p->owner = tid; 
20143   p->nRef++;
20144   if( p->trace ){
20145     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20146   }
20147 #endif
20148 }
20149 static int winMutexTry(sqlcipher3_mutex *p){
20150 #ifndef NDEBUG
20151   DWORD tid = GetCurrentThreadId(); 
20152 #endif
20153   int rc = SQLCIPHER_BUSY;
20154   assert( p->id==SQLCIPHER_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20155   /*
20156   ** The sqlcipher3_mutex_try() routine is very rarely used, and when it
20157   ** is used it is merely an optimization.  So it is OK for it to always
20158   ** fail.  
20159   **
20160   ** The TryEnterCriticalSection() interface is only available on WinNT.
20161   ** And some windows compilers complain if you try to use it without
20162   ** first doing some #defines that prevent SQLite from building on Win98.
20163   ** For that reason, we will omit this optimization for now.  See
20164   ** ticket #2685.
20165   */
20166 #if 0
20167   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
20168     p->owner = tid;
20169     p->nRef++;
20170     rc = SQLCIPHER_OK;
20171   }
20172 #else
20173   UNUSED_PARAMETER(p);
20174 #endif
20175 #ifdef SQLCIPHER_DEBUG
20176   if( rc==SQLCIPHER_OK && p->trace ){
20177     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20178   }
20179 #endif
20180   return rc;
20181 }
20182
20183 /*
20184 ** The sqlcipher3_mutex_leave() routine exits a mutex that was
20185 ** previously entered by the same thread.  The behavior
20186 ** is undefined if the mutex is not currently entered or
20187 ** is not currently allocated.  SQLite will never do either.
20188 */
20189 static void winMutexLeave(sqlcipher3_mutex *p){
20190 #ifndef NDEBUG
20191   DWORD tid = GetCurrentThreadId();
20192   assert( p->nRef>0 );
20193   assert( p->owner==tid );
20194   p->nRef--;
20195   if( p->nRef==0 ) p->owner = 0;
20196   assert( p->nRef==0 || p->id==SQLCIPHER_MUTEX_RECURSIVE );
20197 #endif
20198   LeaveCriticalSection(&p->mutex);
20199 #ifdef SQLCIPHER_DEBUG
20200   if( p->trace ){
20201     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20202   }
20203 #endif
20204 }
20205
20206 SQLCIPHER_PRIVATE sqlcipher3_mutex_methods const *sqlcipher3DefaultMutex(void){
20207   static const sqlcipher3_mutex_methods sMutex = {
20208     winMutexInit,
20209     winMutexEnd,
20210     winMutexAlloc,
20211     winMutexFree,
20212     winMutexEnter,
20213     winMutexTry,
20214     winMutexLeave,
20215 #ifdef SQLCIPHER_DEBUG
20216     winMutexHeld,
20217     winMutexNotheld
20218 #else
20219     0,
20220     0
20221 #endif
20222   };
20223
20224   return &sMutex;
20225 }
20226 #endif /* SQLCIPHER_MUTEX_W32 */
20227
20228 /************** End of mutex_w32.c *******************************************/
20229 /************** Begin file malloc.c ******************************************/
20230 /*
20231 ** 2001 September 15
20232 **
20233 ** The author disclaims copyright to this source code.  In place of
20234 ** a legal notice, here is a blessing:
20235 **
20236 **    May you do good and not evil.
20237 **    May you find forgiveness for yourself and forgive others.
20238 **    May you share freely, never taking more than you give.
20239 **
20240 *************************************************************************
20241 **
20242 ** Memory allocation functions used throughout sqlcipher.
20243 */
20244 /* #include <stdarg.h> */
20245
20246 /*
20247 ** Attempt to release up to n bytes of non-essential memory currently
20248 ** held by SQLite. An example of non-essential memory is memory used to
20249 ** cache database pages that are not currently in use.
20250 */
20251 SQLCIPHER_API int sqlcipher3_release_memory(int n){
20252 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
20253   return sqlcipher3PcacheReleaseMemory(n);
20254 #else
20255   /* IMPLEMENTATION-OF: R-34391-24921 The sqlcipher3_release_memory() routine
20256   ** is a no-op returning zero if SQLite is not compiled with
20257   ** SQLCIPHER_ENABLE_MEMORY_MANAGEMENT. */
20258   UNUSED_PARAMETER(n);
20259   return 0;
20260 #endif
20261 }
20262
20263 /*
20264 ** An instance of the following object records the location of
20265 ** each unused scratch buffer.
20266 */
20267 typedef struct ScratchFreeslot {
20268   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
20269 } ScratchFreeslot;
20270
20271 /*
20272 ** State information local to the memory allocation subsystem.
20273 */
20274 static SQLCIPHER_WSD struct Mem0Global {
20275   sqlcipher3_mutex *mutex;         /* Mutex to serialize access */
20276
20277   /*
20278   ** The alarm callback and its arguments.  The mem0.mutex lock will
20279   ** be held while the callback is running.  Recursive calls into
20280   ** the memory subsystem are allowed, but no new callbacks will be
20281   ** issued.
20282   */
20283   sqlcipher3_int64 alarmThreshold;
20284   void (*alarmCallback)(void*, sqlcipher3_int64,int);
20285   void *alarmArg;
20286
20287   /*
20288   ** Pointers to the end of sqlcipher3GlobalConfig.pScratch memory
20289   ** (so that a range test can be used to determine if an allocation
20290   ** being freed came from pScratch) and a pointer to the list of
20291   ** unused scratch allocations.
20292   */
20293   void *pScratchEnd;
20294   ScratchFreeslot *pScratchFree;
20295   u32 nScratchFree;
20296
20297   /*
20298   ** True if heap is nearly "full" where "full" is defined by the
20299   ** sqlcipher3_soft_heap_limit() setting.
20300   */
20301   int nearlyFull;
20302 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20303
20304 #define mem0 GLOBAL(struct Mem0Global, mem0)
20305
20306 /*
20307 ** This routine runs when the memory allocator sees that the
20308 ** total memory allocation is about to exceed the soft heap
20309 ** limit.
20310 */
20311 static void softHeapLimitEnforcer(
20312   void *NotUsed, 
20313   sqlcipher3_int64 NotUsed2,
20314   int allocSize
20315 ){
20316   UNUSED_PARAMETER2(NotUsed, NotUsed2);
20317   sqlcipher3_release_memory(allocSize);
20318 }
20319
20320 /*
20321 ** Change the alarm callback
20322 */
20323 static int sqlcipher3MemoryAlarm(
20324   void(*xCallback)(void *pArg, sqlcipher3_int64 used,int N),
20325   void *pArg,
20326   sqlcipher3_int64 iThreshold
20327 ){
20328   int nUsed;
20329   sqlcipher3_mutex_enter(mem0.mutex);
20330   mem0.alarmCallback = xCallback;
20331   mem0.alarmArg = pArg;
20332   mem0.alarmThreshold = iThreshold;
20333   nUsed = sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED);
20334   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20335   sqlcipher3_mutex_leave(mem0.mutex);
20336   return SQLCIPHER_OK;
20337 }
20338
20339 #ifndef SQLCIPHER_OMIT_DEPRECATED
20340 /*
20341 ** Deprecated external interface.  Internal/core SQLite code
20342 ** should call sqlcipher3MemoryAlarm.
20343 */
20344 SQLCIPHER_API int sqlcipher3_memory_alarm(
20345   void(*xCallback)(void *pArg, sqlcipher3_int64 used,int N),
20346   void *pArg,
20347   sqlcipher3_int64 iThreshold
20348 ){
20349   return sqlcipher3MemoryAlarm(xCallback, pArg, iThreshold);
20350 }
20351 #endif
20352
20353 /*
20354 ** Set the soft heap-size limit for the library. Passing a zero or 
20355 ** negative value indicates no limit.
20356 */
20357 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_soft_heap_limit64(sqlcipher3_int64 n){
20358   sqlcipher3_int64 priorLimit;
20359   sqlcipher3_int64 excess;
20360 #ifndef SQLCIPHER_OMIT_AUTOINIT
20361   sqlcipher3_initialize();
20362 #endif
20363   sqlcipher3_mutex_enter(mem0.mutex);
20364   priorLimit = mem0.alarmThreshold;
20365   sqlcipher3_mutex_leave(mem0.mutex);
20366   if( n<0 ) return priorLimit;
20367   if( n>0 ){
20368     sqlcipher3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20369   }else{
20370     sqlcipher3MemoryAlarm(0, 0, 0);
20371   }
20372   excess = sqlcipher3_memory_used() - n;
20373   if( excess>0 ) sqlcipher3_release_memory((int)(excess & 0x7fffffff));
20374   return priorLimit;
20375 }
20376 SQLCIPHER_API void sqlcipher3_soft_heap_limit(int n){
20377   if( n<0 ) n = 0;
20378   sqlcipher3_soft_heap_limit64(n);
20379 }
20380
20381 /*
20382 ** Initialize the memory allocation subsystem.
20383 */
20384 SQLCIPHER_PRIVATE int sqlcipher3MallocInit(void){
20385   if( sqlcipher3GlobalConfig.m.xMalloc==0 ){
20386     sqlcipher3MemSetDefault();
20387   }
20388   memset(&mem0, 0, sizeof(mem0));
20389   if( sqlcipher3GlobalConfig.bCoreMutex ){
20390     mem0.mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MEM);
20391   }
20392   if( sqlcipher3GlobalConfig.pScratch && sqlcipher3GlobalConfig.szScratch>=100
20393       && sqlcipher3GlobalConfig.nScratch>0 ){
20394     int i, n, sz;
20395     ScratchFreeslot *pSlot;
20396     sz = ROUNDDOWN8(sqlcipher3GlobalConfig.szScratch);
20397     sqlcipher3GlobalConfig.szScratch = sz;
20398     pSlot = (ScratchFreeslot*)sqlcipher3GlobalConfig.pScratch;
20399     n = sqlcipher3GlobalConfig.nScratch;
20400     mem0.pScratchFree = pSlot;
20401     mem0.nScratchFree = n;
20402     for(i=0; i<n-1; i++){
20403       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20404       pSlot = pSlot->pNext;
20405     }
20406     pSlot->pNext = 0;
20407     mem0.pScratchEnd = (void*)&pSlot[1];
20408   }else{
20409     mem0.pScratchEnd = 0;
20410     sqlcipher3GlobalConfig.pScratch = 0;
20411     sqlcipher3GlobalConfig.szScratch = 0;
20412     sqlcipher3GlobalConfig.nScratch = 0;
20413   }
20414   if( sqlcipher3GlobalConfig.pPage==0 || sqlcipher3GlobalConfig.szPage<512
20415       || sqlcipher3GlobalConfig.nPage<1 ){
20416     sqlcipher3GlobalConfig.pPage = 0;
20417     sqlcipher3GlobalConfig.szPage = 0;
20418     sqlcipher3GlobalConfig.nPage = 0;
20419   }
20420   return sqlcipher3GlobalConfig.m.xInit(sqlcipher3GlobalConfig.m.pAppData);
20421 }
20422
20423 /*
20424 ** Return true if the heap is currently under memory pressure - in other
20425 ** words if the amount of heap used is close to the limit set by
20426 ** sqlcipher3_soft_heap_limit().
20427 */
20428 SQLCIPHER_PRIVATE int sqlcipher3HeapNearlyFull(void){
20429   return mem0.nearlyFull;
20430 }
20431
20432 /*
20433 ** Deinitialize the memory allocation subsystem.
20434 */
20435 SQLCIPHER_PRIVATE void sqlcipher3MallocEnd(void){
20436   if( sqlcipher3GlobalConfig.m.xShutdown ){
20437     sqlcipher3GlobalConfig.m.xShutdown(sqlcipher3GlobalConfig.m.pAppData);
20438   }
20439   memset(&mem0, 0, sizeof(mem0));
20440 }
20441
20442 /*
20443 ** Return the amount of memory currently checked out.
20444 */
20445 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_used(void){
20446   int n, mx;
20447   sqlcipher3_int64 res;
20448   sqlcipher3_status(SQLCIPHER_STATUS_MEMORY_USED, &n, &mx, 0);
20449   res = (sqlcipher3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
20450   return res;
20451 }
20452
20453 /*
20454 ** Return the maximum amount of memory that has ever been
20455 ** checked out since either the beginning of this process
20456 ** or since the most recent reset.
20457 */
20458 SQLCIPHER_API sqlcipher3_int64 sqlcipher3_memory_highwater(int resetFlag){
20459   int n, mx;
20460   sqlcipher3_int64 res;
20461   sqlcipher3_status(SQLCIPHER_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20462   res = (sqlcipher3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
20463   return res;
20464 }
20465
20466 /*
20467 ** Trigger the alarm 
20468 */
20469 static void sqlcipher3MallocAlarm(int nByte){
20470   void (*xCallback)(void*,sqlcipher3_int64,int);
20471   sqlcipher3_int64 nowUsed;
20472   void *pArg;
20473   if( mem0.alarmCallback==0 ) return;
20474   xCallback = mem0.alarmCallback;
20475   nowUsed = sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED);
20476   pArg = mem0.alarmArg;
20477   mem0.alarmCallback = 0;
20478   sqlcipher3_mutex_leave(mem0.mutex);
20479   xCallback(pArg, nowUsed, nByte);
20480   sqlcipher3_mutex_enter(mem0.mutex);
20481   mem0.alarmCallback = xCallback;
20482   mem0.alarmArg = pArg;
20483 }
20484
20485 /*
20486 ** Do a memory allocation with statistics and alarms.  Assume the
20487 ** lock is already held.
20488 */
20489 static int mallocWithAlarm(int n, void **pp){
20490   int nFull;
20491   void *p;
20492   assert( sqlcipher3_mutex_held(mem0.mutex) );
20493   nFull = sqlcipher3GlobalConfig.m.xRoundup(n);
20494   sqlcipher3StatusSet(SQLCIPHER_STATUS_MALLOC_SIZE, n);
20495   if( mem0.alarmCallback!=0 ){
20496     int nUsed = sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED);
20497     if( nUsed >= mem0.alarmThreshold - nFull ){
20498       mem0.nearlyFull = 1;
20499       sqlcipher3MallocAlarm(nFull);
20500     }else{
20501       mem0.nearlyFull = 0;
20502     }
20503   }
20504   p = sqlcipher3GlobalConfig.m.xMalloc(nFull);
20505 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
20506   if( p==0 && mem0.alarmCallback ){
20507     sqlcipher3MallocAlarm(nFull);
20508     p = sqlcipher3GlobalConfig.m.xMalloc(nFull);
20509   }
20510 #endif
20511   if( p ){
20512     nFull = sqlcipher3MallocSize(p);
20513     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, nFull);
20514     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MALLOC_COUNT, 1);
20515   }
20516   *pp = p;
20517   return nFull;
20518 }
20519
20520 /*
20521 ** Allocate memory.  This routine is like sqlcipher3_malloc() except that it
20522 ** assumes the memory subsystem has already been initialized.
20523 */
20524 SQLCIPHER_PRIVATE void *sqlcipher3Malloc(int n){
20525   void *p;
20526   if( n<=0               /* IMP: R-65312-04917 */ 
20527    || n>=0x7fffff00
20528   ){
20529     /* A memory allocation of a number of bytes which is near the maximum
20530     ** signed integer value might cause an integer overflow inside of the
20531     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
20532     ** 255 bytes of overhead.  SQLite itself will never use anything near
20533     ** this amount.  The only way to reach the limit is with sqlcipher3_malloc() */
20534     p = 0;
20535   }else if( sqlcipher3GlobalConfig.bMemstat ){
20536     sqlcipher3_mutex_enter(mem0.mutex);
20537     mallocWithAlarm(n, &p);
20538     sqlcipher3_mutex_leave(mem0.mutex);
20539   }else{
20540     p = sqlcipher3GlobalConfig.m.xMalloc(n);
20541   }
20542   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
20543   return p;
20544 }
20545
20546 /*
20547 ** This version of the memory allocation is for use by the application.
20548 ** First make sure the memory subsystem is initialized, then do the
20549 ** allocation.
20550 */
20551 SQLCIPHER_API void *sqlcipher3_malloc(int n){
20552 #ifndef SQLCIPHER_OMIT_AUTOINIT
20553   if( sqlcipher3_initialize() ) return 0;
20554 #endif
20555   return sqlcipher3Malloc(n);
20556 }
20557
20558 /*
20559 ** Each thread may only have a single outstanding allocation from
20560 ** xScratchMalloc().  We verify this constraint in the single-threaded
20561 ** case by setting scratchAllocOut to 1 when an allocation
20562 ** is outstanding clearing it when the allocation is freed.
20563 */
20564 #if SQLCIPHER_THREADSAFE==0 && !defined(NDEBUG)
20565 static int scratchAllocOut = 0;
20566 #endif
20567
20568
20569 /*
20570 ** Allocate memory that is to be used and released right away.
20571 ** This routine is similar to alloca() in that it is not intended
20572 ** for situations where the memory might be held long-term.  This
20573 ** routine is intended to get memory to old large transient data
20574 ** structures that would not normally fit on the stack of an
20575 ** embedded processor.
20576 */
20577 SQLCIPHER_PRIVATE void *sqlcipher3ScratchMalloc(int n){
20578   void *p;
20579   assert( n>0 );
20580
20581   sqlcipher3_mutex_enter(mem0.mutex);
20582   if( mem0.nScratchFree && sqlcipher3GlobalConfig.szScratch>=n ){
20583     p = mem0.pScratchFree;
20584     mem0.pScratchFree = mem0.pScratchFree->pNext;
20585     mem0.nScratchFree--;
20586     sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_USED, 1);
20587     sqlcipher3StatusSet(SQLCIPHER_STATUS_SCRATCH_SIZE, n);
20588     sqlcipher3_mutex_leave(mem0.mutex);
20589   }else{
20590     if( sqlcipher3GlobalConfig.bMemstat ){
20591       sqlcipher3StatusSet(SQLCIPHER_STATUS_SCRATCH_SIZE, n);
20592       n = mallocWithAlarm(n, &p);
20593       if( p ) sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_OVERFLOW, n);
20594       sqlcipher3_mutex_leave(mem0.mutex);
20595     }else{
20596       sqlcipher3_mutex_leave(mem0.mutex);
20597       p = sqlcipher3GlobalConfig.m.xMalloc(n);
20598     }
20599     sqlcipher3MemdebugSetType(p, MEMTYPE_SCRATCH);
20600   }
20601   assert( sqlcipher3_mutex_notheld(mem0.mutex) );
20602
20603
20604 #if SQLCIPHER_THREADSAFE==0 && !defined(NDEBUG)
20605   /* Verify that no more than two scratch allocations per thread
20606   ** are outstanding at one time.  (This is only checked in the
20607   ** single-threaded case since checking in the multi-threaded case
20608   ** would be much more complicated.) */
20609   assert( scratchAllocOut<=1 );
20610   if( p ) scratchAllocOut++;
20611 #endif
20612
20613   return p;
20614 }
20615 SQLCIPHER_PRIVATE void sqlcipher3ScratchFree(void *p){
20616   if( p ){
20617
20618 #if SQLCIPHER_THREADSAFE==0 && !defined(NDEBUG)
20619     /* Verify that no more than two scratch allocation per thread
20620     ** is outstanding at one time.  (This is only checked in the
20621     ** single-threaded case since checking in the multi-threaded case
20622     ** would be much more complicated.) */
20623     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20624     scratchAllocOut--;
20625 #endif
20626
20627     if( p>=sqlcipher3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20628       /* Release memory from the SQLCIPHER_CONFIG_SCRATCH allocation */
20629       ScratchFreeslot *pSlot;
20630       pSlot = (ScratchFreeslot*)p;
20631       sqlcipher3_mutex_enter(mem0.mutex);
20632       pSlot->pNext = mem0.pScratchFree;
20633       mem0.pScratchFree = pSlot;
20634       mem0.nScratchFree++;
20635       assert( mem0.nScratchFree <= (u32)sqlcipher3GlobalConfig.nScratch );
20636       sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_USED, -1);
20637       sqlcipher3_mutex_leave(mem0.mutex);
20638     }else{
20639       /* Release memory back to the heap */
20640       assert( sqlcipher3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20641       assert( sqlcipher3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
20642       sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
20643       if( sqlcipher3GlobalConfig.bMemstat ){
20644         int iSize = sqlcipher3MallocSize(p);
20645         sqlcipher3_mutex_enter(mem0.mutex);
20646         sqlcipher3StatusAdd(SQLCIPHER_STATUS_SCRATCH_OVERFLOW, -iSize);
20647         sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, -iSize);
20648         sqlcipher3StatusAdd(SQLCIPHER_STATUS_MALLOC_COUNT, -1);
20649         sqlcipher3GlobalConfig.m.xFree(p);
20650         sqlcipher3_mutex_leave(mem0.mutex);
20651       }else{
20652         sqlcipher3GlobalConfig.m.xFree(p);
20653       }
20654     }
20655   }
20656 }
20657
20658 /*
20659 ** TRUE if p is a lookaside memory allocation from db
20660 */
20661 #ifndef SQLCIPHER_OMIT_LOOKASIDE
20662 static int isLookaside(sqlcipher3 *db, void *p){
20663   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20664 }
20665 #else
20666 #define isLookaside(A,B) 0
20667 #endif
20668
20669 /*
20670 ** Return the size of a memory allocation previously obtained from
20671 ** sqlcipher3Malloc() or sqlcipher3_malloc().
20672 */
20673 SQLCIPHER_PRIVATE int sqlcipher3MallocSize(void *p){
20674   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_HEAP) );
20675   assert( sqlcipher3MemdebugNoType(p, MEMTYPE_DB) );
20676   return sqlcipher3GlobalConfig.m.xSize(p);
20677 }
20678 SQLCIPHER_PRIVATE int sqlcipher3DbMallocSize(sqlcipher3 *db, void *p){
20679   assert( db==0 || sqlcipher3_mutex_held(db->mutex) );
20680   if( db && isLookaside(db, p) ){
20681     return db->lookaside.sz;
20682   }else{
20683     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
20684     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20685     assert( db!=0 || sqlcipher3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20686     return sqlcipher3GlobalConfig.m.xSize(p);
20687   }
20688 }
20689
20690 /*
20691 ** Free memory previously obtained from sqlcipher3Malloc().
20692 */
20693 SQLCIPHER_API void sqlcipher3_free(void *p){
20694   if( p==0 ) return;  /* IMP: R-49053-54554 */
20695   assert( sqlcipher3MemdebugNoType(p, MEMTYPE_DB) );
20696   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_HEAP) );
20697   if( sqlcipher3GlobalConfig.bMemstat ){
20698     sqlcipher3_mutex_enter(mem0.mutex);
20699     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, -sqlcipher3MallocSize(p));
20700     sqlcipher3StatusAdd(SQLCIPHER_STATUS_MALLOC_COUNT, -1);
20701     sqlcipher3GlobalConfig.m.xFree(p);
20702     sqlcipher3_mutex_leave(mem0.mutex);
20703   }else{
20704     sqlcipher3GlobalConfig.m.xFree(p);
20705   }
20706 }
20707
20708 /*
20709 ** Free memory that might be associated with a particular database
20710 ** connection.
20711 */
20712 SQLCIPHER_PRIVATE void sqlcipher3DbFree(sqlcipher3 *db, void *p){
20713   assert( db==0 || sqlcipher3_mutex_held(db->mutex) );
20714   if( db ){
20715     if( db->pnBytesFreed ){
20716       *db->pnBytesFreed += sqlcipher3DbMallocSize(db, p);
20717       return;
20718     }
20719     if( isLookaside(db, p) ){
20720       LookasideSlot *pBuf = (LookasideSlot*)p;
20721       pBuf->pNext = db->lookaside.pFree;
20722       db->lookaside.pFree = pBuf;
20723       db->lookaside.nOut--;
20724       return;
20725     }
20726   }
20727   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
20728   assert( sqlcipher3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20729   assert( db!=0 || sqlcipher3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20730   sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
20731   sqlcipher3_free(p);
20732 }
20733
20734 /*
20735 ** Change the size of an existing memory allocation
20736 */
20737 SQLCIPHER_PRIVATE void *sqlcipher3Realloc(void *pOld, int nBytes){
20738   int nOld, nNew, nDiff;
20739   void *pNew;
20740   if( pOld==0 ){
20741     return sqlcipher3Malloc(nBytes); /* IMP: R-28354-25769 */
20742   }
20743   if( nBytes<=0 ){
20744     sqlcipher3_free(pOld); /* IMP: R-31593-10574 */
20745     return 0;
20746   }
20747   if( nBytes>=0x7fffff00 ){
20748     /* The 0x7ffff00 limit term is explained in comments on sqlcipher3Malloc() */
20749     return 0;
20750   }
20751   nOld = sqlcipher3MallocSize(pOld);
20752   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
20753   ** argument to xRealloc is always a value returned by a prior call to
20754   ** xRoundup. */
20755   nNew = sqlcipher3GlobalConfig.m.xRoundup(nBytes);
20756   if( nOld==nNew ){
20757     pNew = pOld;
20758   }else if( sqlcipher3GlobalConfig.bMemstat ){
20759     sqlcipher3_mutex_enter(mem0.mutex);
20760     sqlcipher3StatusSet(SQLCIPHER_STATUS_MALLOC_SIZE, nBytes);
20761     nDiff = nNew - nOld;
20762     if( sqlcipher3StatusValue(SQLCIPHER_STATUS_MEMORY_USED) >= 
20763           mem0.alarmThreshold-nDiff ){
20764       sqlcipher3MallocAlarm(nDiff);
20765     }
20766     assert( sqlcipher3MemdebugHasType(pOld, MEMTYPE_HEAP) );
20767     assert( sqlcipher3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
20768     pNew = sqlcipher3GlobalConfig.m.xRealloc(pOld, nNew);
20769     if( pNew==0 && mem0.alarmCallback ){
20770       sqlcipher3MallocAlarm(nBytes);
20771       pNew = sqlcipher3GlobalConfig.m.xRealloc(pOld, nNew);
20772     }
20773     if( pNew ){
20774       nNew = sqlcipher3MallocSize(pNew);
20775       sqlcipher3StatusAdd(SQLCIPHER_STATUS_MEMORY_USED, nNew-nOld);
20776     }
20777     sqlcipher3_mutex_leave(mem0.mutex);
20778   }else{
20779     pNew = sqlcipher3GlobalConfig.m.xRealloc(pOld, nNew);
20780   }
20781   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
20782   return pNew;
20783 }
20784
20785 /*
20786 ** The public interface to sqlcipher3Realloc.  Make sure that the memory
20787 ** subsystem is initialized prior to invoking sqlcipherRealloc.
20788 */
20789 SQLCIPHER_API void *sqlcipher3_realloc(void *pOld, int n){
20790 #ifndef SQLCIPHER_OMIT_AUTOINIT
20791   if( sqlcipher3_initialize() ) return 0;
20792 #endif
20793   return sqlcipher3Realloc(pOld, n);
20794 }
20795
20796
20797 /*
20798 ** Allocate and zero memory.
20799 */ 
20800 SQLCIPHER_PRIVATE void *sqlcipher3MallocZero(int n){
20801   void *p = sqlcipher3Malloc(n);
20802   if( p ){
20803     memset(p, 0, n);
20804   }
20805   return p;
20806 }
20807
20808 /*
20809 ** Allocate and zero memory.  If the allocation fails, make
20810 ** the mallocFailed flag in the connection pointer.
20811 */
20812 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocZero(sqlcipher3 *db, int n){
20813   void *p = sqlcipher3DbMallocRaw(db, n);
20814   if( p ){
20815     memset(p, 0, n);
20816   }
20817   return p;
20818 }
20819
20820 /*
20821 ** Allocate and zero memory.  If the allocation fails, make
20822 ** the mallocFailed flag in the connection pointer.
20823 **
20824 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
20825 ** failure on the same database connection) then always return 0.
20826 ** Hence for a particular database connection, once malloc starts
20827 ** failing, it fails consistently until mallocFailed is reset.
20828 ** This is an important assumption.  There are many places in the
20829 ** code that do things like this:
20830 **
20831 **         int *a = (int*)sqlcipher3DbMallocRaw(db, 100);
20832 **         int *b = (int*)sqlcipher3DbMallocRaw(db, 200);
20833 **         if( b ) a[10] = 9;
20834 **
20835 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
20836 ** that all prior mallocs (ex: "a") worked too.
20837 */
20838 SQLCIPHER_PRIVATE void *sqlcipher3DbMallocRaw(sqlcipher3 *db, int n){
20839   void *p;
20840   assert( db==0 || sqlcipher3_mutex_held(db->mutex) );
20841   assert( db==0 || db->pnBytesFreed==0 );
20842 #ifndef SQLCIPHER_OMIT_LOOKASIDE
20843   if( db ){
20844     LookasideSlot *pBuf;
20845     if( db->mallocFailed ){
20846       return 0;
20847     }
20848     if( db->lookaside.bEnabled ){
20849       if( n>db->lookaside.sz ){
20850         db->lookaside.anStat[1]++;
20851       }else if( (pBuf = db->lookaside.pFree)==0 ){
20852         db->lookaside.anStat[2]++;
20853       }else{
20854         db->lookaside.pFree = pBuf->pNext;
20855         db->lookaside.nOut++;
20856         db->lookaside.anStat[0]++;
20857         if( db->lookaside.nOut>db->lookaside.mxOut ){
20858           db->lookaside.mxOut = db->lookaside.nOut;
20859         }
20860         return (void*)pBuf;
20861       }
20862     }
20863   }
20864 #else
20865   if( db && db->mallocFailed ){
20866     return 0;
20867   }
20868 #endif
20869   p = sqlcipher3Malloc(n);
20870   if( !p && db ){
20871     db->mallocFailed = 1;
20872   }
20873   sqlcipher3MemdebugSetType(p, MEMTYPE_DB |
20874          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20875   return p;
20876 }
20877
20878 /*
20879 ** Resize the block of memory pointed to by p to n bytes. If the
20880 ** resize fails, set the mallocFailed flag in the connection object.
20881 */
20882 SQLCIPHER_PRIVATE void *sqlcipher3DbRealloc(sqlcipher3 *db, void *p, int n){
20883   void *pNew = 0;
20884   assert( db!=0 );
20885   assert( sqlcipher3_mutex_held(db->mutex) );
20886   if( db->mallocFailed==0 ){
20887     if( p==0 ){
20888       return sqlcipher3DbMallocRaw(db, n);
20889     }
20890     if( isLookaside(db, p) ){
20891       if( n<=db->lookaside.sz ){
20892         return p;
20893       }
20894       pNew = sqlcipher3DbMallocRaw(db, n);
20895       if( pNew ){
20896         memcpy(pNew, p, db->lookaside.sz);
20897         sqlcipher3DbFree(db, p);
20898       }
20899     }else{
20900       assert( sqlcipher3MemdebugHasType(p, MEMTYPE_DB) );
20901       assert( sqlcipher3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20902       sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
20903       pNew = sqlcipher3_realloc(p, n);
20904       if( !pNew ){
20905         sqlcipher3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
20906         db->mallocFailed = 1;
20907       }
20908       sqlcipher3MemdebugSetType(pNew, MEMTYPE_DB | 
20909             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20910     }
20911   }
20912   return pNew;
20913 }
20914
20915 /*
20916 ** Attempt to reallocate p.  If the reallocation fails, then free p
20917 ** and set the mallocFailed flag in the database connection.
20918 */
20919 SQLCIPHER_PRIVATE void *sqlcipher3DbReallocOrFree(sqlcipher3 *db, void *p, int n){
20920   void *pNew;
20921   pNew = sqlcipher3DbRealloc(db, p, n);
20922   if( !pNew ){
20923     sqlcipher3DbFree(db, p);
20924   }
20925   return pNew;
20926 }
20927
20928 /*
20929 ** Make a copy of a string in memory obtained from sqlcipherMalloc(). These 
20930 ** functions call sqlcipher3MallocRaw() directly instead of sqlcipherMalloc(). This
20931 ** is because when memory debugging is turned on, these two functions are 
20932 ** called via macros that record the current file and line number in the
20933 ** ThreadData structure.
20934 */
20935 SQLCIPHER_PRIVATE char *sqlcipher3DbStrDup(sqlcipher3 *db, const char *z){
20936   char *zNew;
20937   size_t n;
20938   if( z==0 ){
20939     return 0;
20940   }
20941   n = sqlcipher3Strlen30(z) + 1;
20942   assert( (n&0x7fffffff)==n );
20943   zNew = sqlcipher3DbMallocRaw(db, (int)n);
20944   if( zNew ){
20945     memcpy(zNew, z, n);
20946   }
20947   return zNew;
20948 }
20949 SQLCIPHER_PRIVATE char *sqlcipher3DbStrNDup(sqlcipher3 *db, const char *z, int n){
20950   char *zNew;
20951   if( z==0 ){
20952     return 0;
20953   }
20954   assert( (n&0x7fffffff)==n );
20955   zNew = sqlcipher3DbMallocRaw(db, n+1);
20956   if( zNew ){
20957     memcpy(zNew, z, n);
20958     zNew[n] = 0;
20959   }
20960   return zNew;
20961 }
20962
20963 /*
20964 ** Create a string from the zFromat argument and the va_list that follows.
20965 ** Store the string in memory obtained from sqlcipherMalloc() and make *pz
20966 ** point to that string.
20967 */
20968 SQLCIPHER_PRIVATE void sqlcipher3SetString(char **pz, sqlcipher3 *db, const char *zFormat, ...){
20969   va_list ap;
20970   char *z;
20971
20972   va_start(ap, zFormat);
20973   z = sqlcipher3VMPrintf(db, zFormat, ap);
20974   va_end(ap);
20975   sqlcipher3DbFree(db, *pz);
20976   *pz = z;
20977 }
20978
20979
20980 /*
20981 ** This function must be called before exiting any API function (i.e. 
20982 ** returning control to the user) that has called sqlcipher3_malloc or
20983 ** sqlcipher3_realloc.
20984 **
20985 ** The returned value is normally a copy of the second argument to this
20986 ** function. However, if a malloc() failure has occurred since the previous
20987 ** invocation SQLCIPHER_NOMEM is returned instead. 
20988 **
20989 ** If the first argument, db, is not NULL and a malloc() error has occurred,
20990 ** then the connection error-code (the value returned by sqlcipher3_errcode())
20991 ** is set to SQLCIPHER_NOMEM.
20992 */
20993 SQLCIPHER_PRIVATE int sqlcipher3ApiExit(sqlcipher3* db, int rc){
20994   /* If the db handle is not NULL, then we must hold the connection handle
20995   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
20996   ** is unsafe, as is the call to sqlcipher3Error().
20997   */
20998   assert( !db || sqlcipher3_mutex_held(db->mutex) );
20999   if( db && (db->mallocFailed || rc==SQLCIPHER_IOERR_NOMEM) ){
21000     sqlcipher3Error(db, SQLCIPHER_NOMEM, 0);
21001     db->mallocFailed = 0;
21002     rc = SQLCIPHER_NOMEM;
21003   }
21004   return rc & (db ? db->errMask : 0xff);
21005 }
21006
21007 /************** End of malloc.c **********************************************/
21008 /************** Begin file printf.c ******************************************/
21009 /*
21010 ** The "printf" code that follows dates from the 1980's.  It is in
21011 ** the public domain.  The original comments are included here for
21012 ** completeness.  They are very out-of-date but might be useful as
21013 ** an historical reference.  Most of the "enhancements" have been backed
21014 ** out so that the functionality is now the same as standard printf().
21015 **
21016 **************************************************************************
21017 **
21018 ** This file contains code for a set of "printf"-like routines.  These
21019 ** routines format strings much like the printf() from the standard C
21020 ** library, though the implementation here has enhancements to support
21021 ** SQLlite.
21022 */
21023
21024 /*
21025 ** Conversion types fall into various categories as defined by the
21026 ** following enumeration.
21027 */
21028 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
21029 #define etFLOAT       2 /* Floating point.  %f */
21030 #define etEXP         3 /* Exponentional notation. %e and %E */
21031 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
21032 #define etSIZE        5 /* Return number of characters processed so far. %n */
21033 #define etSTRING      6 /* Strings. %s */
21034 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
21035 #define etPERCENT     8 /* Percent symbol. %% */
21036 #define etCHARX       9 /* Characters. %c */
21037 /* The rest are extensions, not normally found in printf() */
21038 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
21039 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
21040                           NULL pointers replaced by SQL NULL.  %Q */
21041 #define etTOKEN      12 /* a pointer to a Token structure */
21042 #define etSRCLIST    13 /* a pointer to a SrcList */
21043 #define etPOINTER    14 /* The %p conversion */
21044 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
21045 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
21046
21047 #define etINVALID     0 /* Any unrecognized conversion type */
21048
21049
21050 /*
21051 ** An "etByte" is an 8-bit unsigned value.
21052 */
21053 typedef unsigned char etByte;
21054
21055 /*
21056 ** Each builtin conversion character (ex: the 'd' in "%d") is described
21057 ** by an instance of the following structure
21058 */
21059 typedef struct et_info {   /* Information about each format field */
21060   char fmttype;            /* The format field code letter */
21061   etByte base;             /* The base for radix conversion */
21062   etByte flags;            /* One or more of FLAG_ constants below */
21063   etByte type;             /* Conversion paradigm */
21064   etByte charset;          /* Offset into aDigits[] of the digits string */
21065   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
21066 } et_info;
21067
21068 /*
21069 ** Allowed values for et_info.flags
21070 */
21071 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
21072 #define FLAG_INTERN  2     /* True if for internal use only */
21073 #define FLAG_STRING  4     /* Allow infinity precision */
21074
21075
21076 /*
21077 ** The following table is searched linearly, so it is good to put the
21078 ** most frequently used conversion types first.
21079 */
21080 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
21081 static const char aPrefix[] = "-x0\000X0";
21082 static const et_info fmtinfo[] = {
21083   {  'd', 10, 1, etRADIX,      0,  0 },
21084   {  's',  0, 4, etSTRING,     0,  0 },
21085   {  'g',  0, 1, etGENERIC,    30, 0 },
21086   {  'z',  0, 4, etDYNSTRING,  0,  0 },
21087   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
21088   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
21089   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
21090   {  'c',  0, 0, etCHARX,      0,  0 },
21091   {  'o',  8, 0, etRADIX,      0,  2 },
21092   {  'u', 10, 0, etRADIX,      0,  0 },
21093   {  'x', 16, 0, etRADIX,      16, 1 },
21094   {  'X', 16, 0, etRADIX,      0,  4 },
21095 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
21096   {  'f',  0, 1, etFLOAT,      0,  0 },
21097   {  'e',  0, 1, etEXP,        30, 0 },
21098   {  'E',  0, 1, etEXP,        14, 0 },
21099   {  'G',  0, 1, etGENERIC,    14, 0 },
21100 #endif
21101   {  'i', 10, 1, etRADIX,      0,  0 },
21102   {  'n',  0, 0, etSIZE,       0,  0 },
21103   {  '%',  0, 0, etPERCENT,    0,  0 },
21104   {  'p', 16, 0, etPOINTER,    0,  1 },
21105
21106 /* All the rest have the FLAG_INTERN bit set and are thus for internal
21107 ** use only */
21108   {  'T',  0, 2, etTOKEN,      0,  0 },
21109   {  'S',  0, 2, etSRCLIST,    0,  0 },
21110   {  'r', 10, 3, etORDINAL,    0,  0 },
21111 };
21112
21113 /*
21114 ** If SQLCIPHER_OMIT_FLOATING_POINT is defined, then none of the floating point
21115 ** conversions will work.
21116 */
21117 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
21118 /*
21119 ** "*val" is a double such that 0.1 <= *val < 10.0
21120 ** Return the ascii code for the leading digit of *val, then
21121 ** multiply "*val" by 10.0 to renormalize.
21122 **
21123 ** Example:
21124 **     input:     *val = 3.14159
21125 **     output:    *val = 1.4159    function return = '3'
21126 **
21127 ** The counter *cnt is incremented each time.  After counter exceeds
21128 ** 16 (the number of significant digits in a 64-bit float) '0' is
21129 ** always returned.
21130 */
21131 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
21132   int digit;
21133   LONGDOUBLE_TYPE d;
21134   if( (*cnt)++ >= 16 ) return '0';
21135   digit = (int)*val;
21136   d = digit;
21137   digit += '0';
21138   *val = (*val - d)*10.0;
21139   return (char)digit;
21140 }
21141 #endif /* SQLCIPHER_OMIT_FLOATING_POINT */
21142
21143 /*
21144 ** Append N space characters to the given string buffer.
21145 */
21146 static void appendSpace(StrAccum *pAccum, int N){
21147   static const char zSpaces[] = "                             ";
21148   while( N>=(int)sizeof(zSpaces)-1 ){
21149     sqlcipher3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
21150     N -= sizeof(zSpaces)-1;
21151   }
21152   if( N>0 ){
21153     sqlcipher3StrAccumAppend(pAccum, zSpaces, N);
21154   }
21155 }
21156
21157 /*
21158 ** On machines with a small stack size, you can redefine the
21159 ** SQLCIPHER_PRINT_BUF_SIZE to be something smaller, if desired.
21160 */
21161 #ifndef SQLCIPHER_PRINT_BUF_SIZE
21162 # define SQLCIPHER_PRINT_BUF_SIZE 70
21163 #endif
21164 #define etBUFSIZE SQLCIPHER_PRINT_BUF_SIZE  /* Size of the output buffer */
21165
21166 /*
21167 ** Render a string given by "fmt" into the StrAccum object.
21168 */
21169 SQLCIPHER_PRIVATE void sqlcipher3VXPrintf(
21170   StrAccum *pAccum,                  /* Accumulate results here */
21171   int useExtended,                   /* Allow extended %-conversions */
21172   const char *fmt,                   /* Format string */
21173   va_list ap                         /* arguments */
21174 ){
21175   int c;                     /* Next character in the format string */
21176   char *bufpt;               /* Pointer to the conversion buffer */
21177   int precision;             /* Precision of the current field */
21178   int length;                /* Length of the field */
21179   int idx;                   /* A general purpose loop counter */
21180   int width;                 /* Width of the current field */
21181   etByte flag_leftjustify;   /* True if "-" flag is present */
21182   etByte flag_plussign;      /* True if "+" flag is present */
21183   etByte flag_blanksign;     /* True if " " flag is present */
21184   etByte flag_alternateform; /* True if "#" flag is present */
21185   etByte flag_altform2;      /* True if "!" flag is present */
21186   etByte flag_zeropad;       /* True if field width constant starts with zero */
21187   etByte flag_long;          /* True if "l" flag is present */
21188   etByte flag_longlong;      /* True if the "ll" flag is present */
21189   etByte done;               /* Loop termination flag */
21190   etByte xtype = 0;          /* Conversion paradigm */
21191   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
21192   sqlcipher_uint64 longvalue;   /* Value for integer types */
21193   LONGDOUBLE_TYPE realvalue; /* Value for real types */
21194   const et_info *infop;      /* Pointer to the appropriate info structure */
21195   char *zOut;                /* Rendering buffer */
21196   int nOut;                  /* Size of the rendering buffer */
21197   char *zExtra;              /* Malloced memory used by some conversion */
21198 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
21199   int  exp, e2;              /* exponent of real numbers */
21200   int nsd;                   /* Number of significant digits returned */
21201   double rounder;            /* Used for rounding floating point values */
21202   etByte flag_dp;            /* True if decimal point should be shown */
21203   etByte flag_rtz;           /* True if trailing zeros should be removed */
21204 #endif
21205   char buf[etBUFSIZE];       /* Conversion buffer */
21206
21207   bufpt = 0;
21208   for(; (c=(*fmt))!=0; ++fmt){
21209     if( c!='%' ){
21210       int amt;
21211       bufpt = (char *)fmt;
21212       amt = 1;
21213       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
21214       sqlcipher3StrAccumAppend(pAccum, bufpt, amt);
21215       if( c==0 ) break;
21216     }
21217     if( (c=(*++fmt))==0 ){
21218       sqlcipher3StrAccumAppend(pAccum, "%", 1);
21219       break;
21220     }
21221     /* Find out what flags are present */
21222     flag_leftjustify = flag_plussign = flag_blanksign = 
21223      flag_alternateform = flag_altform2 = flag_zeropad = 0;
21224     done = 0;
21225     do{
21226       switch( c ){
21227         case '-':   flag_leftjustify = 1;     break;
21228         case '+':   flag_plussign = 1;        break;
21229         case ' ':   flag_blanksign = 1;       break;
21230         case '#':   flag_alternateform = 1;   break;
21231         case '!':   flag_altform2 = 1;        break;
21232         case '0':   flag_zeropad = 1;         break;
21233         default:    done = 1;                 break;
21234       }
21235     }while( !done && (c=(*++fmt))!=0 );
21236     /* Get the field width */
21237     width = 0;
21238     if( c=='*' ){
21239       width = va_arg(ap,int);
21240       if( width<0 ){
21241         flag_leftjustify = 1;
21242         width = -width;
21243       }
21244       c = *++fmt;
21245     }else{
21246       while( c>='0' && c<='9' ){
21247         width = width*10 + c - '0';
21248         c = *++fmt;
21249       }
21250     }
21251     /* Get the precision */
21252     if( c=='.' ){
21253       precision = 0;
21254       c = *++fmt;
21255       if( c=='*' ){
21256         precision = va_arg(ap,int);
21257         if( precision<0 ) precision = -precision;
21258         c = *++fmt;
21259       }else{
21260         while( c>='0' && c<='9' ){
21261           precision = precision*10 + c - '0';
21262           c = *++fmt;
21263         }
21264       }
21265     }else{
21266       precision = -1;
21267     }
21268     /* Get the conversion type modifier */
21269     if( c=='l' ){
21270       flag_long = 1;
21271       c = *++fmt;
21272       if( c=='l' ){
21273         flag_longlong = 1;
21274         c = *++fmt;
21275       }else{
21276         flag_longlong = 0;
21277       }
21278     }else{
21279       flag_long = flag_longlong = 0;
21280     }
21281     /* Fetch the info entry for the field */
21282     infop = &fmtinfo[0];
21283     xtype = etINVALID;
21284     for(idx=0; idx<ArraySize(fmtinfo); idx++){
21285       if( c==fmtinfo[idx].fmttype ){
21286         infop = &fmtinfo[idx];
21287         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
21288           xtype = infop->type;
21289         }else{
21290           return;
21291         }
21292         break;
21293       }
21294     }
21295     zExtra = 0;
21296
21297     /*
21298     ** At this point, variables are initialized as follows:
21299     **
21300     **   flag_alternateform          TRUE if a '#' is present.
21301     **   flag_altform2               TRUE if a '!' is present.
21302     **   flag_plussign               TRUE if a '+' is present.
21303     **   flag_leftjustify            TRUE if a '-' is present or if the
21304     **                               field width was negative.
21305     **   flag_zeropad                TRUE if the width began with 0.
21306     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
21307     **                               the conversion character.
21308     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
21309     **                               the conversion character.
21310     **   flag_blanksign              TRUE if a ' ' is present.
21311     **   width                       The specified field width.  This is
21312     **                               always non-negative.  Zero is the default.
21313     **   precision                   The specified precision.  The default
21314     **                               is -1.
21315     **   xtype                       The class of the conversion.
21316     **   infop                       Pointer to the appropriate info struct.
21317     */
21318     switch( xtype ){
21319       case etPOINTER:
21320         flag_longlong = sizeof(char*)==sizeof(i64);
21321         flag_long = sizeof(char*)==sizeof(long int);
21322         /* Fall through into the next case */
21323       case etORDINAL:
21324       case etRADIX:
21325         if( infop->flags & FLAG_SIGNED ){
21326           i64 v;
21327           if( flag_longlong ){
21328             v = va_arg(ap,i64);
21329           }else if( flag_long ){
21330             v = va_arg(ap,long int);
21331           }else{
21332             v = va_arg(ap,int);
21333           }
21334           if( v<0 ){
21335             if( v==SMALLEST_INT64 ){
21336               longvalue = ((u64)1)<<63;
21337             }else{
21338               longvalue = -v;
21339             }
21340             prefix = '-';
21341           }else{
21342             longvalue = v;
21343             if( flag_plussign )        prefix = '+';
21344             else if( flag_blanksign )  prefix = ' ';
21345             else                       prefix = 0;
21346           }
21347         }else{
21348           if( flag_longlong ){
21349             longvalue = va_arg(ap,u64);
21350           }else if( flag_long ){
21351             longvalue = va_arg(ap,unsigned long int);
21352           }else{
21353             longvalue = va_arg(ap,unsigned int);
21354           }
21355           prefix = 0;
21356         }
21357         if( longvalue==0 ) flag_alternateform = 0;
21358         if( flag_zeropad && precision<width-(prefix!=0) ){
21359           precision = width-(prefix!=0);
21360         }
21361         if( precision<etBUFSIZE-10 ){
21362           nOut = etBUFSIZE;
21363           zOut = buf;
21364         }else{
21365           nOut = precision + 10;
21366           zOut = zExtra = sqlcipher3Malloc( nOut );
21367           if( zOut==0 ){
21368             pAccum->mallocFailed = 1;
21369             return;
21370           }
21371         }
21372         bufpt = &zOut[nOut-1];
21373         if( xtype==etORDINAL ){
21374           static const char zOrd[] = "thstndrd";
21375           int x = (int)(longvalue % 10);
21376           if( x>=4 || (longvalue/10)%10==1 ){
21377             x = 0;
21378           }
21379           *(--bufpt) = zOrd[x*2+1];
21380           *(--bufpt) = zOrd[x*2];
21381         }
21382         {
21383           register const char *cset;      /* Use registers for speed */
21384           register int base;
21385           cset = &aDigits[infop->charset];
21386           base = infop->base;
21387           do{                                           /* Convert to ascii */
21388             *(--bufpt) = cset[longvalue%base];
21389             longvalue = longvalue/base;
21390           }while( longvalue>0 );
21391         }
21392         length = (int)(&zOut[nOut-1]-bufpt);
21393         for(idx=precision-length; idx>0; idx--){
21394           *(--bufpt) = '0';                             /* Zero pad */
21395         }
21396         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
21397         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
21398           const char *pre;
21399           char x;
21400           pre = &aPrefix[infop->prefix];
21401           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21402         }
21403         length = (int)(&zOut[nOut-1]-bufpt);
21404         break;
21405       case etFLOAT:
21406       case etEXP:
21407       case etGENERIC:
21408         realvalue = va_arg(ap,double);
21409 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
21410         length = 0;
21411 #else
21412         if( precision<0 ) precision = 6;         /* Set default precision */
21413         if( realvalue<0.0 ){
21414           realvalue = -realvalue;
21415           prefix = '-';
21416         }else{
21417           if( flag_plussign )          prefix = '+';
21418           else if( flag_blanksign )    prefix = ' ';
21419           else                         prefix = 0;
21420         }
21421         if( xtype==etGENERIC && precision>0 ) precision--;
21422 #if 0
21423         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
21424         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
21425 #else
21426         /* It makes more sense to use 0.5 */
21427         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21428 #endif
21429         if( xtype==etFLOAT ) realvalue += rounder;
21430         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21431         exp = 0;
21432         if( sqlcipher3IsNaN((double)realvalue) ){
21433           bufpt = "NaN";
21434           length = 3;
21435           break;
21436         }
21437         if( realvalue>0.0 ){
21438           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
21439           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
21440           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
21441           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21442           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21443           if( exp>350 ){
21444             if( prefix=='-' ){
21445               bufpt = "-Inf";
21446             }else if( prefix=='+' ){
21447               bufpt = "+Inf";
21448             }else{
21449               bufpt = "Inf";
21450             }
21451             length = sqlcipher3Strlen30(bufpt);
21452             break;
21453           }
21454         }
21455         bufpt = buf;
21456         /*
21457         ** If the field type is etGENERIC, then convert to either etEXP
21458         ** or etFLOAT, as appropriate.
21459         */
21460         if( xtype!=etFLOAT ){
21461           realvalue += rounder;
21462           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21463         }
21464         if( xtype==etGENERIC ){
21465           flag_rtz = !flag_alternateform;
21466           if( exp<-4 || exp>precision ){
21467             xtype = etEXP;
21468           }else{
21469             precision = precision - exp;
21470             xtype = etFLOAT;
21471           }
21472         }else{
21473           flag_rtz = 0;
21474         }
21475         if( xtype==etEXP ){
21476           e2 = 0;
21477         }else{
21478           e2 = exp;
21479         }
21480         if( e2+precision+width > etBUFSIZE - 15 ){
21481           bufpt = zExtra = sqlcipher3Malloc( e2+precision+width+15 );
21482           if( bufpt==0 ){
21483             pAccum->mallocFailed = 1;
21484             return;
21485           }
21486         }
21487         zOut = bufpt;
21488         nsd = 0;
21489         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21490         /* The sign in front of the number */
21491         if( prefix ){
21492           *(bufpt++) = prefix;
21493         }
21494         /* Digits prior to the decimal point */
21495         if( e2<0 ){
21496           *(bufpt++) = '0';
21497         }else{
21498           for(; e2>=0; e2--){
21499             *(bufpt++) = et_getdigit(&realvalue,&nsd);
21500           }
21501         }
21502         /* The decimal point */
21503         if( flag_dp ){
21504           *(bufpt++) = '.';
21505         }
21506         /* "0" digits after the decimal point but before the first
21507         ** significant digit of the number */
21508         for(e2++; e2<0; precision--, e2++){
21509           assert( precision>0 );
21510           *(bufpt++) = '0';
21511         }
21512         /* Significant digits after the decimal point */
21513         while( (precision--)>0 ){
21514           *(bufpt++) = et_getdigit(&realvalue,&nsd);
21515         }
21516         /* Remove trailing zeros and the "." if no digits follow the "." */
21517         if( flag_rtz && flag_dp ){
21518           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21519           assert( bufpt>zOut );
21520           if( bufpt[-1]=='.' ){
21521             if( flag_altform2 ){
21522               *(bufpt++) = '0';
21523             }else{
21524               *(--bufpt) = 0;
21525             }
21526           }
21527         }
21528         /* Add the "eNNN" suffix */
21529         if( xtype==etEXP ){
21530           *(bufpt++) = aDigits[infop->charset];
21531           if( exp<0 ){
21532             *(bufpt++) = '-'; exp = -exp;
21533           }else{
21534             *(bufpt++) = '+';
21535           }
21536           if( exp>=100 ){
21537             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
21538             exp %= 100;
21539           }
21540           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
21541           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
21542         }
21543         *bufpt = 0;
21544
21545         /* The converted number is in buf[] and zero terminated. Output it.
21546         ** Note that the number is in the usual order, not reversed as with
21547         ** integer conversions. */
21548         length = (int)(bufpt-zOut);
21549         bufpt = zOut;
21550
21551         /* Special case:  Add leading zeros if the flag_zeropad flag is
21552         ** set and we are not left justified */
21553         if( flag_zeropad && !flag_leftjustify && length < width){
21554           int i;
21555           int nPad = width - length;
21556           for(i=width; i>=nPad; i--){
21557             bufpt[i] = bufpt[i-nPad];
21558           }
21559           i = prefix!=0;
21560           while( nPad-- ) bufpt[i++] = '0';
21561           length = width;
21562         }
21563 #endif /* !defined(SQLCIPHER_OMIT_FLOATING_POINT) */
21564         break;
21565       case etSIZE:
21566         *(va_arg(ap,int*)) = pAccum->nChar;
21567         length = width = 0;
21568         break;
21569       case etPERCENT:
21570         buf[0] = '%';
21571         bufpt = buf;
21572         length = 1;
21573         break;
21574       case etCHARX:
21575         c = va_arg(ap,int);
21576         buf[0] = (char)c;
21577         if( precision>=0 ){
21578           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
21579           length = precision;
21580         }else{
21581           length =1;
21582         }
21583         bufpt = buf;
21584         break;
21585       case etSTRING:
21586       case etDYNSTRING:
21587         bufpt = va_arg(ap,char*);
21588         if( bufpt==0 ){
21589           bufpt = "";
21590         }else if( xtype==etDYNSTRING ){
21591           zExtra = bufpt;
21592         }
21593         if( precision>=0 ){
21594           for(length=0; length<precision && bufpt[length]; length++){}
21595         }else{
21596           length = sqlcipher3Strlen30(bufpt);
21597         }
21598         break;
21599       case etSQLESCAPE:
21600       case etSQLESCAPE2:
21601       case etSQLESCAPE3: {
21602         int i, j, k, n, isnull;
21603         int needQuote;
21604         char ch;
21605         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
21606         char *escarg = va_arg(ap,char*);
21607         isnull = escarg==0;
21608         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
21609         k = precision;
21610         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
21611           if( ch==q )  n++;
21612         }
21613         needQuote = !isnull && xtype==etSQLESCAPE2;
21614         n += i + 1 + needQuote*2;
21615         if( n>etBUFSIZE ){
21616           bufpt = zExtra = sqlcipher3Malloc( n );
21617           if( bufpt==0 ){
21618             pAccum->mallocFailed = 1;
21619             return;
21620           }
21621         }else{
21622           bufpt = buf;
21623         }
21624         j = 0;
21625         if( needQuote ) bufpt[j++] = q;
21626         k = i;
21627         for(i=0; i<k; i++){
21628           bufpt[j++] = ch = escarg[i];
21629           if( ch==q ) bufpt[j++] = ch;
21630         }
21631         if( needQuote ) bufpt[j++] = q;
21632         bufpt[j] = 0;
21633         length = j;
21634         /* The precision in %q and %Q means how many input characters to
21635         ** consume, not the length of the output...
21636         ** if( precision>=0 && precision<length ) length = precision; */
21637         break;
21638       }
21639       case etTOKEN: {
21640         Token *pToken = va_arg(ap, Token*);
21641         if( pToken ){
21642           sqlcipher3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
21643         }
21644         length = width = 0;
21645         break;
21646       }
21647       case etSRCLIST: {
21648         SrcList *pSrc = va_arg(ap, SrcList*);
21649         int k = va_arg(ap, int);
21650         struct SrcList_item *pItem = &pSrc->a[k];
21651         assert( k>=0 && k<pSrc->nSrc );
21652         if( pItem->zDatabase ){
21653           sqlcipher3StrAccumAppend(pAccum, pItem->zDatabase, -1);
21654           sqlcipher3StrAccumAppend(pAccum, ".", 1);
21655         }
21656         sqlcipher3StrAccumAppend(pAccum, pItem->zName, -1);
21657         length = width = 0;
21658         break;
21659       }
21660       default: {
21661         assert( xtype==etINVALID );
21662         return;
21663       }
21664     }/* End switch over the format type */
21665     /*
21666     ** The text of the conversion is pointed to by "bufpt" and is
21667     ** "length" characters long.  The field width is "width".  Do
21668     ** the output.
21669     */
21670     if( !flag_leftjustify ){
21671       register int nspace;
21672       nspace = width-length;
21673       if( nspace>0 ){
21674         appendSpace(pAccum, nspace);
21675       }
21676     }
21677     if( length>0 ){
21678       sqlcipher3StrAccumAppend(pAccum, bufpt, length);
21679     }
21680     if( flag_leftjustify ){
21681       register int nspace;
21682       nspace = width-length;
21683       if( nspace>0 ){
21684         appendSpace(pAccum, nspace);
21685       }
21686     }
21687     sqlcipher3_free(zExtra);
21688   }/* End for loop over the format string */
21689 } /* End of function */
21690
21691 /*
21692 ** Append N bytes of text from z to the StrAccum object.
21693 */
21694 SQLCIPHER_PRIVATE void sqlcipher3StrAccumAppend(StrAccum *p, const char *z, int N){
21695   assert( z!=0 || N==0 );
21696   if( p->tooBig | p->mallocFailed ){
21697     testcase(p->tooBig);
21698     testcase(p->mallocFailed);
21699     return;
21700   }
21701   assert( p->zText!=0 || p->nChar==0 );
21702   if( N<0 ){
21703     N = sqlcipher3Strlen30(z);
21704   }
21705   if( N==0 || NEVER(z==0) ){
21706     return;
21707   }
21708   if( p->nChar+N >= p->nAlloc ){
21709     char *zNew;
21710     if( !p->useMalloc ){
21711       p->tooBig = 1;
21712       N = p->nAlloc - p->nChar - 1;
21713       if( N<=0 ){
21714         return;
21715       }
21716     }else{
21717       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
21718       i64 szNew = p->nChar;
21719       szNew += N + 1;
21720       if( szNew > p->mxAlloc ){
21721         sqlcipher3StrAccumReset(p);
21722         p->tooBig = 1;
21723         return;
21724       }else{
21725         p->nAlloc = (int)szNew;
21726       }
21727       if( p->useMalloc==1 ){
21728         zNew = sqlcipher3DbRealloc(p->db, zOld, p->nAlloc);
21729       }else{
21730         zNew = sqlcipher3_realloc(zOld, p->nAlloc);
21731       }
21732       if( zNew ){
21733         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
21734         p->zText = zNew;
21735       }else{
21736         p->mallocFailed = 1;
21737         sqlcipher3StrAccumReset(p);
21738         return;
21739       }
21740     }
21741   }
21742   assert( p->zText );
21743   memcpy(&p->zText[p->nChar], z, N);
21744   p->nChar += N;
21745 }
21746
21747 /*
21748 ** Finish off a string by making sure it is zero-terminated.
21749 ** Return a pointer to the resulting string.  Return a NULL
21750 ** pointer if any kind of error was encountered.
21751 */
21752 SQLCIPHER_PRIVATE char *sqlcipher3StrAccumFinish(StrAccum *p){
21753   if( p->zText ){
21754     p->zText[p->nChar] = 0;
21755     if( p->useMalloc && p->zText==p->zBase ){
21756       if( p->useMalloc==1 ){
21757         p->zText = sqlcipher3DbMallocRaw(p->db, p->nChar+1 );
21758       }else{
21759         p->zText = sqlcipher3_malloc(p->nChar+1);
21760       }
21761       if( p->zText ){
21762         memcpy(p->zText, p->zBase, p->nChar+1);
21763       }else{
21764         p->mallocFailed = 1;
21765       }
21766     }
21767   }
21768   return p->zText;
21769 }
21770
21771 /*
21772 ** Reset an StrAccum string.  Reclaim all malloced memory.
21773 */
21774 SQLCIPHER_PRIVATE void sqlcipher3StrAccumReset(StrAccum *p){
21775   if( p->zText!=p->zBase ){
21776     if( p->useMalloc==1 ){
21777       sqlcipher3DbFree(p->db, p->zText);
21778     }else{
21779       sqlcipher3_free(p->zText);
21780     }
21781   }
21782   p->zText = 0;
21783 }
21784
21785 /*
21786 ** Initialize a string accumulator
21787 */
21788 SQLCIPHER_PRIVATE void sqlcipher3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
21789   p->zText = p->zBase = zBase;
21790   p->db = 0;
21791   p->nChar = 0;
21792   p->nAlloc = n;
21793   p->mxAlloc = mx;
21794   p->useMalloc = 1;
21795   p->tooBig = 0;
21796   p->mallocFailed = 0;
21797 }
21798
21799 /*
21800 ** Print into memory obtained from sqlcipherMalloc().  Use the internal
21801 ** %-conversion extensions.
21802 */
21803 SQLCIPHER_PRIVATE char *sqlcipher3VMPrintf(sqlcipher3 *db, const char *zFormat, va_list ap){
21804   char *z;
21805   char zBase[SQLCIPHER_PRINT_BUF_SIZE];
21806   StrAccum acc;
21807   assert( db!=0 );
21808   sqlcipher3StrAccumInit(&acc, zBase, sizeof(zBase),
21809                       db->aLimit[SQLCIPHER_LIMIT_LENGTH]);
21810   acc.db = db;
21811   sqlcipher3VXPrintf(&acc, 1, zFormat, ap);
21812   z = sqlcipher3StrAccumFinish(&acc);
21813   if( acc.mallocFailed ){
21814     db->mallocFailed = 1;
21815   }
21816   return z;
21817 }
21818
21819 /*
21820 ** Print into memory obtained from sqlcipherMalloc().  Use the internal
21821 ** %-conversion extensions.
21822 */
21823 SQLCIPHER_PRIVATE char *sqlcipher3MPrintf(sqlcipher3 *db, const char *zFormat, ...){
21824   va_list ap;
21825   char *z;
21826   va_start(ap, zFormat);
21827   z = sqlcipher3VMPrintf(db, zFormat, ap);
21828   va_end(ap);
21829   return z;
21830 }
21831
21832 /*
21833 ** Like sqlcipher3MPrintf(), but call sqlcipher3DbFree() on zStr after formatting
21834 ** the string and before returnning.  This routine is intended to be used
21835 ** to modify an existing string.  For example:
21836 **
21837 **       x = sqlcipher3MPrintf(db, x, "prefix %s suffix", x);
21838 **
21839 */
21840 SQLCIPHER_PRIVATE char *sqlcipher3MAppendf(sqlcipher3 *db, char *zStr, const char *zFormat, ...){
21841   va_list ap;
21842   char *z;
21843   va_start(ap, zFormat);
21844   z = sqlcipher3VMPrintf(db, zFormat, ap);
21845   va_end(ap);
21846   sqlcipher3DbFree(db, zStr);
21847   return z;
21848 }
21849
21850 /*
21851 ** Print into memory obtained from sqlcipher3_malloc().  Omit the internal
21852 ** %-conversion extensions.
21853 */
21854 SQLCIPHER_API char *sqlcipher3_vmprintf(const char *zFormat, va_list ap){
21855   char *z;
21856   char zBase[SQLCIPHER_PRINT_BUF_SIZE];
21857   StrAccum acc;
21858 #ifndef SQLCIPHER_OMIT_AUTOINIT
21859   if( sqlcipher3_initialize() ) return 0;
21860 #endif
21861   sqlcipher3StrAccumInit(&acc, zBase, sizeof(zBase), SQLCIPHER_MAX_LENGTH);
21862   acc.useMalloc = 2;
21863   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21864   z = sqlcipher3StrAccumFinish(&acc);
21865   return z;
21866 }
21867
21868 /*
21869 ** Print into memory obtained from sqlcipher3_malloc()().  Omit the internal
21870 ** %-conversion extensions.
21871 */
21872 SQLCIPHER_API char *sqlcipher3_mprintf(const char *zFormat, ...){
21873   va_list ap;
21874   char *z;
21875 #ifndef SQLCIPHER_OMIT_AUTOINIT
21876   if( sqlcipher3_initialize() ) return 0;
21877 #endif
21878   va_start(ap, zFormat);
21879   z = sqlcipher3_vmprintf(zFormat, ap);
21880   va_end(ap);
21881   return z;
21882 }
21883
21884 /*
21885 ** sqlcipher3_snprintf() works like snprintf() except that it ignores the
21886 ** current locale settings.  This is important for SQLite because we
21887 ** are not able to use a "," as the decimal point in place of "." as
21888 ** specified by some locales.
21889 **
21890 ** Oops:  The first two arguments of sqlcipher3_snprintf() are backwards
21891 ** from the snprintf() standard.  Unfortunately, it is too late to change
21892 ** this without breaking compatibility, so we just have to live with the
21893 ** mistake.
21894 **
21895 ** sqlcipher3_vsnprintf() is the varargs version.
21896 */
21897 SQLCIPHER_API char *sqlcipher3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
21898   StrAccum acc;
21899   if( n<=0 ) return zBuf;
21900   sqlcipher3StrAccumInit(&acc, zBuf, n, 0);
21901   acc.useMalloc = 0;
21902   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21903   return sqlcipher3StrAccumFinish(&acc);
21904 }
21905 SQLCIPHER_API char *sqlcipher3_snprintf(int n, char *zBuf, const char *zFormat, ...){
21906   char *z;
21907   va_list ap;
21908   va_start(ap,zFormat);
21909   z = sqlcipher3_vsnprintf(n, zBuf, zFormat, ap);
21910   va_end(ap);
21911   return z;
21912 }
21913
21914 /*
21915 ** This is the routine that actually formats the sqlcipher3_log() message.
21916 ** We house it in a separate routine from sqlcipher3_log() to avoid using
21917 ** stack space on small-stack systems when logging is disabled.
21918 **
21919 ** sqlcipher3_log() must render into a static buffer.  It cannot dynamically
21920 ** allocate memory because it might be called while the memory allocator
21921 ** mutex is held.
21922 */
21923 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
21924   StrAccum acc;                          /* String accumulator */
21925   char zMsg[SQLCIPHER_PRINT_BUF_SIZE*3];    /* Complete log message */
21926
21927   sqlcipher3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
21928   acc.useMalloc = 0;
21929   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21930   sqlcipher3GlobalConfig.xLog(sqlcipher3GlobalConfig.pLogArg, iErrCode,
21931                            sqlcipher3StrAccumFinish(&acc));
21932 }
21933
21934 /*
21935 ** Format and write a message to the log if logging is enabled.
21936 */
21937 SQLCIPHER_API void sqlcipher3_log(int iErrCode, const char *zFormat, ...){
21938   va_list ap;                             /* Vararg list */
21939   if( sqlcipher3GlobalConfig.xLog ){
21940     va_start(ap, zFormat);
21941     renderLogMsg(iErrCode, zFormat, ap);
21942     va_end(ap);
21943   }
21944 }
21945
21946 #if defined(SQLCIPHER_DEBUG)
21947 /*
21948 ** A version of printf() that understands %lld.  Used for debugging.
21949 ** The printf() built into some versions of windows does not understand %lld
21950 ** and segfaults if you give it a long long int.
21951 */
21952 SQLCIPHER_PRIVATE void sqlcipher3DebugPrintf(const char *zFormat, ...){
21953   va_list ap;
21954   StrAccum acc;
21955   char zBuf[500];
21956   sqlcipher3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21957   acc.useMalloc = 0;
21958   va_start(ap,zFormat);
21959   sqlcipher3VXPrintf(&acc, 0, zFormat, ap);
21960   va_end(ap);
21961   sqlcipher3StrAccumFinish(&acc);
21962   fprintf(stdout,"%s", zBuf);
21963   fflush(stdout);
21964 }
21965 #endif
21966
21967 #ifndef SQLCIPHER_OMIT_TRACE
21968 /*
21969 ** variable-argument wrapper around sqlcipher3VXPrintf().
21970 */
21971 SQLCIPHER_PRIVATE void sqlcipher3XPrintf(StrAccum *p, const char *zFormat, ...){
21972   va_list ap;
21973   va_start(ap,zFormat);
21974   sqlcipher3VXPrintf(p, 1, zFormat, ap);
21975   va_end(ap);
21976 }
21977 #endif
21978
21979 /************** End of printf.c **********************************************/
21980 /************** Begin file random.c ******************************************/
21981 /*
21982 ** 2001 September 15
21983 **
21984 ** The author disclaims copyright to this source code.  In place of
21985 ** a legal notice, here is a blessing:
21986 **
21987 **    May you do good and not evil.
21988 **    May you find forgiveness for yourself and forgive others.
21989 **    May you share freely, never taking more than you give.
21990 **
21991 *************************************************************************
21992 ** This file contains code to implement a pseudo-random number
21993 ** generator (PRNG) for SQLite.
21994 **
21995 ** Random numbers are used by some of the database backends in order
21996 ** to generate random integer keys for tables or random filenames.
21997 */
21998
21999
22000 /* All threads share a single random number generator.
22001 ** This structure is the current state of the generator.
22002 */
22003 static SQLCIPHER_WSD struct sqlcipher3PrngType {
22004   unsigned char isInit;          /* True if initialized */
22005   unsigned char i, j;            /* State variables */
22006   unsigned char s[256];          /* State variables */
22007 } sqlcipher3Prng;
22008
22009 /*
22010 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
22011 ** must be held while executing this routine.
22012 **
22013 ** Why not just use a library random generator like lrand48() for this?
22014 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
22015 ** good source of random numbers.  The lrand48() library function may
22016 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
22017 ** subtle problems on some systems that could cause problems.  It is hard
22018 ** to know.  To minimize the risk of problems due to bad lrand48()
22019 ** implementations, SQLite uses this random number generator based
22020 ** on RC4, which we know works very well.
22021 **
22022 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
22023 ** randomness any more.  But we will leave this code in all the same.
22024 */
22025 static u8 randomByte(void){
22026   unsigned char t;
22027
22028
22029   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
22030   ** state vector.  If writable static data is unsupported on the target,
22031   ** we have to locate the state vector at run-time.  In the more common
22032   ** case where writable static data is supported, wsdPrng can refer directly
22033   ** to the "sqlcipher3Prng" state vector declared above.
22034   */
22035 #ifdef SQLCIPHER_OMIT_WSD
22036   struct sqlcipher3PrngType *p = &GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng);
22037 # define wsdPrng p[0]
22038 #else
22039 # define wsdPrng sqlcipher3Prng
22040 #endif
22041
22042
22043   /* Initialize the state of the random number generator once,
22044   ** the first time this routine is called.  The seed value does
22045   ** not need to contain a lot of randomness since we are not
22046   ** trying to do secure encryption or anything like that...
22047   **
22048   ** Nothing in this file or anywhere else in SQLite does any kind of
22049   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
22050   ** number generator) not as an encryption device.
22051   */
22052   if( !wsdPrng.isInit ){
22053     int i;
22054     char k[256];
22055     wsdPrng.j = 0;
22056     wsdPrng.i = 0;
22057     sqlcipher3OsRandomness(sqlcipher3_vfs_find(0), 256, k);
22058     for(i=0; i<256; i++){
22059       wsdPrng.s[i] = (u8)i;
22060     }
22061     for(i=0; i<256; i++){
22062       wsdPrng.j += wsdPrng.s[i] + k[i];
22063       t = wsdPrng.s[wsdPrng.j];
22064       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
22065       wsdPrng.s[i] = t;
22066     }
22067     wsdPrng.isInit = 1;
22068   }
22069
22070   /* Generate and return single random byte
22071   */
22072   wsdPrng.i++;
22073   t = wsdPrng.s[wsdPrng.i];
22074   wsdPrng.j += t;
22075   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
22076   wsdPrng.s[wsdPrng.j] = t;
22077   t += wsdPrng.s[wsdPrng.i];
22078   return wsdPrng.s[t];
22079 }
22080
22081 /*
22082 ** Return N random bytes.
22083 */
22084 SQLCIPHER_API void sqlcipher3_randomness(int N, void *pBuf){
22085   unsigned char *zBuf = pBuf;
22086 #if SQLCIPHER_THREADSAFE
22087   sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_PRNG);
22088 #endif
22089   sqlcipher3_mutex_enter(mutex);
22090   while( N-- ){
22091     *(zBuf++) = randomByte();
22092   }
22093   sqlcipher3_mutex_leave(mutex);
22094 }
22095
22096 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
22097 /*
22098 ** For testing purposes, we sometimes want to preserve the state of
22099 ** PRNG and restore the PRNG to its saved state at a later time, or
22100 ** to reset the PRNG to its initial state.  These routines accomplish
22101 ** those tasks.
22102 **
22103 ** The sqlcipher3_test_control() interface calls these routines to
22104 ** control the PRNG.
22105 */
22106 static SQLCIPHER_WSD struct sqlcipher3PrngType sqlcipher3SavedPrng;
22107 SQLCIPHER_PRIVATE void sqlcipher3PrngSaveState(void){
22108   memcpy(
22109     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3SavedPrng),
22110     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng),
22111     sizeof(sqlcipher3Prng)
22112   );
22113 }
22114 SQLCIPHER_PRIVATE void sqlcipher3PrngRestoreState(void){
22115   memcpy(
22116     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng),
22117     &GLOBAL(struct sqlcipher3PrngType, sqlcipher3SavedPrng),
22118     sizeof(sqlcipher3Prng)
22119   );
22120 }
22121 SQLCIPHER_PRIVATE void sqlcipher3PrngResetState(void){
22122   GLOBAL(struct sqlcipher3PrngType, sqlcipher3Prng).isInit = 0;
22123 }
22124 #endif /* SQLCIPHER_OMIT_BUILTIN_TEST */
22125
22126 /************** End of random.c **********************************************/
22127 /************** Begin file utf.c *********************************************/
22128 /*
22129 ** 2004 April 13
22130 **
22131 ** The author disclaims copyright to this source code.  In place of
22132 ** a legal notice, here is a blessing:
22133 **
22134 **    May you do good and not evil.
22135 **    May you find forgiveness for yourself and forgive others.
22136 **    May you share freely, never taking more than you give.
22137 **
22138 *************************************************************************
22139 ** This file contains routines used to translate between UTF-8, 
22140 ** UTF-16, UTF-16BE, and UTF-16LE.
22141 **
22142 ** Notes on UTF-8:
22143 **
22144 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
22145 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
22146 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22147 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
22148 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
22149 **
22150 **
22151 ** Notes on UTF-16:  (with wwww+1==uuuuu)
22152 **
22153 **      Word-0               Word-1          Value
22154 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
22155 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
22156 **
22157 **
22158 ** BOM or Byte Order Mark:
22159 **     0xff 0xfe   little-endian utf-16 follows
22160 **     0xfe 0xff   big-endian utf-16 follows
22161 **
22162 */
22163 /* #include <assert.h> */
22164
22165 #ifndef SQLCIPHER_AMALGAMATION
22166 /*
22167 ** The following constant value is used by the SQLCIPHER_BIGENDIAN and
22168 ** SQLCIPHER_LITTLEENDIAN macros.
22169 */
22170 SQLCIPHER_PRIVATE const int sqlcipher3one = 1;
22171 #endif /* SQLCIPHER_AMALGAMATION */
22172
22173 /*
22174 ** This lookup table is used to help decode the first byte of
22175 ** a multi-byte UTF8 character.
22176 */
22177 static const unsigned char sqlcipher3Utf8Trans1[] = {
22178   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22179   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22180   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22181   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22182   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22183   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22184   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22185   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22186 };
22187
22188
22189 #define WRITE_UTF8(zOut, c) {                          \
22190   if( c<0x00080 ){                                     \
22191     *zOut++ = (u8)(c&0xFF);                            \
22192   }                                                    \
22193   else if( c<0x00800 ){                                \
22194     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
22195     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22196   }                                                    \
22197   else if( c<0x10000 ){                                \
22198     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
22199     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22200     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22201   }else{                                               \
22202     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
22203     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
22204     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22205     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22206   }                                                    \
22207 }
22208
22209 #define WRITE_UTF16LE(zOut, c) {                                    \
22210   if( c<=0xFFFF ){                                                  \
22211     *zOut++ = (u8)(c&0x00FF);                                       \
22212     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22213   }else{                                                            \
22214     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22215     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22216     *zOut++ = (u8)(c&0x00FF);                                       \
22217     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22218   }                                                                 \
22219 }
22220
22221 #define WRITE_UTF16BE(zOut, c) {                                    \
22222   if( c<=0xFFFF ){                                                  \
22223     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22224     *zOut++ = (u8)(c&0x00FF);                                       \
22225   }else{                                                            \
22226     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22227     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22228     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22229     *zOut++ = (u8)(c&0x00FF);                                       \
22230   }                                                                 \
22231 }
22232
22233 #define READ_UTF16LE(zIn, TERM, c){                                   \
22234   c = (*zIn++);                                                       \
22235   c += ((*zIn++)<<8);                                                 \
22236   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22237     int c2 = (*zIn++);                                                \
22238     c2 += ((*zIn++)<<8);                                              \
22239     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22240   }                                                                   \
22241 }
22242
22243 #define READ_UTF16BE(zIn, TERM, c){                                   \
22244   c = ((*zIn++)<<8);                                                  \
22245   c += (*zIn++);                                                      \
22246   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22247     int c2 = ((*zIn++)<<8);                                           \
22248     c2 += (*zIn++);                                                   \
22249     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22250   }                                                                   \
22251 }
22252
22253 /*
22254 ** Translate a single UTF-8 character.  Return the unicode value.
22255 **
22256 ** During translation, assume that the byte that zTerm points
22257 ** is a 0x00.
22258 **
22259 ** Write a pointer to the next unread byte back into *pzNext.
22260 **
22261 ** Notes On Invalid UTF-8:
22262 **
22263 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
22264 **     be encoded as a multi-byte character.  Any multi-byte character that
22265 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22266 **
22267 **  *  This routine never allows a UTF16 surrogate value to be encoded.
22268 **     If a multi-byte character attempts to encode a value between
22269 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
22270 **
22271 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
22272 **     byte of a character are interpreted as single-byte characters
22273 **     and rendered as themselves even though they are technically
22274 **     invalid characters.
22275 **
22276 **  *  This routine accepts an infinite number of different UTF8 encodings
22277 **     for unicode values 0x80 and greater.  It do not change over-length
22278 **     encodings to 0xfffd as some systems recommend.
22279 */
22280 #define READ_UTF8(zIn, zTerm, c)                           \
22281   c = *(zIn++);                                            \
22282   if( c>=0xc0 ){                                           \
22283     c = sqlcipher3Utf8Trans1[c-0xc0];                         \
22284     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
22285       c = (c<<6) + (0x3f & *(zIn++));                      \
22286     }                                                      \
22287     if( c<0x80                                             \
22288         || (c&0xFFFFF800)==0xD800                          \
22289         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
22290   }
22291 SQLCIPHER_PRIVATE u32 sqlcipher3Utf8Read(
22292   const unsigned char *zIn,       /* First byte of UTF-8 character */
22293   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
22294 ){
22295   unsigned int c;
22296
22297   /* Same as READ_UTF8() above but without the zTerm parameter.
22298   ** For this routine, we assume the UTF8 string is always zero-terminated.
22299   */
22300   c = *(zIn++);
22301   if( c>=0xc0 ){
22302     c = sqlcipher3Utf8Trans1[c-0xc0];
22303     while( (*zIn & 0xc0)==0x80 ){
22304       c = (c<<6) + (0x3f & *(zIn++));
22305     }
22306     if( c<0x80
22307         || (c&0xFFFFF800)==0xD800
22308         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
22309   }
22310   *pzNext = zIn;
22311   return c;
22312 }
22313
22314
22315
22316
22317 /*
22318 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
22319 ** printed on stderr on the way into and out of sqlcipher3VdbeMemTranslate().
22320 */ 
22321 /* #define TRANSLATE_TRACE 1 */
22322
22323 #ifndef SQLCIPHER_OMIT_UTF16
22324 /*
22325 ** This routine transforms the internal text encoding used by pMem to
22326 ** desiredEnc. It is an error if the string is already of the desired
22327 ** encoding, or if *pMem does not contain a string value.
22328 */
22329 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
22330   int len;                    /* Maximum length of output string in bytes */
22331   unsigned char *zOut;                  /* Output buffer */
22332   unsigned char *zIn;                   /* Input iterator */
22333   unsigned char *zTerm;                 /* End of input */
22334   unsigned char *z;                     /* Output iterator */
22335   unsigned int c;
22336
22337   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
22338   assert( pMem->flags&MEM_Str );
22339   assert( pMem->enc!=desiredEnc );
22340   assert( pMem->enc!=0 );
22341   assert( pMem->n>=0 );
22342
22343 #if defined(TRANSLATE_TRACE) && defined(SQLCIPHER_DEBUG)
22344   {
22345     char zBuf[100];
22346     sqlcipher3VdbeMemPrettyPrint(pMem, zBuf);
22347     fprintf(stderr, "INPUT:  %s\n", zBuf);
22348   }
22349 #endif
22350
22351   /* If the translation is between UTF-16 little and big endian, then 
22352   ** all that is required is to swap the byte order. This case is handled
22353   ** differently from the others.
22354   */
22355   if( pMem->enc!=SQLCIPHER_UTF8 && desiredEnc!=SQLCIPHER_UTF8 ){
22356     u8 temp;
22357     int rc;
22358     rc = sqlcipher3VdbeMemMakeWriteable(pMem);
22359     if( rc!=SQLCIPHER_OK ){
22360       assert( rc==SQLCIPHER_NOMEM );
22361       return SQLCIPHER_NOMEM;
22362     }
22363     zIn = (u8*)pMem->z;
22364     zTerm = &zIn[pMem->n&~1];
22365     while( zIn<zTerm ){
22366       temp = *zIn;
22367       *zIn = *(zIn+1);
22368       zIn++;
22369       *zIn++ = temp;
22370     }
22371     pMem->enc = desiredEnc;
22372     goto translate_out;
22373   }
22374
22375   /* Set len to the maximum number of bytes required in the output buffer. */
22376   if( desiredEnc==SQLCIPHER_UTF8 ){
22377     /* When converting from UTF-16, the maximum growth results from
22378     ** translating a 2-byte character to a 4-byte UTF-8 character.
22379     ** A single byte is required for the output string
22380     ** nul-terminator.
22381     */
22382     pMem->n &= ~1;
22383     len = pMem->n * 2 + 1;
22384   }else{
22385     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
22386     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
22387     ** character. Two bytes are required in the output buffer for the
22388     ** nul-terminator.
22389     */
22390     len = pMem->n * 2 + 2;
22391   }
22392
22393   /* Set zIn to point at the start of the input buffer and zTerm to point 1
22394   ** byte past the end.
22395   **
22396   ** Variable zOut is set to point at the output buffer, space obtained
22397   ** from sqlcipher3_malloc().
22398   */
22399   zIn = (u8*)pMem->z;
22400   zTerm = &zIn[pMem->n];
22401   zOut = sqlcipher3DbMallocRaw(pMem->db, len);
22402   if( !zOut ){
22403     return SQLCIPHER_NOMEM;
22404   }
22405   z = zOut;
22406
22407   if( pMem->enc==SQLCIPHER_UTF8 ){
22408     if( desiredEnc==SQLCIPHER_UTF16LE ){
22409       /* UTF-8 -> UTF-16 Little-endian */
22410       while( zIn<zTerm ){
22411         /* c = sqlcipher3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
22412         READ_UTF8(zIn, zTerm, c);
22413         WRITE_UTF16LE(z, c);
22414       }
22415     }else{
22416       assert( desiredEnc==SQLCIPHER_UTF16BE );
22417       /* UTF-8 -> UTF-16 Big-endian */
22418       while( zIn<zTerm ){
22419         /* c = sqlcipher3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
22420         READ_UTF8(zIn, zTerm, c);
22421         WRITE_UTF16BE(z, c);
22422       }
22423     }
22424     pMem->n = (int)(z - zOut);
22425     *z++ = 0;
22426   }else{
22427     assert( desiredEnc==SQLCIPHER_UTF8 );
22428     if( pMem->enc==SQLCIPHER_UTF16LE ){
22429       /* UTF-16 Little-endian -> UTF-8 */
22430       while( zIn<zTerm ){
22431         READ_UTF16LE(zIn, zIn<zTerm, c); 
22432         WRITE_UTF8(z, c);
22433       }
22434     }else{
22435       /* UTF-16 Big-endian -> UTF-8 */
22436       while( zIn<zTerm ){
22437         READ_UTF16BE(zIn, zIn<zTerm, c); 
22438         WRITE_UTF8(z, c);
22439       }
22440     }
22441     pMem->n = (int)(z - zOut);
22442   }
22443   *z = 0;
22444   assert( (pMem->n+(desiredEnc==SQLCIPHER_UTF8?1:2))<=len );
22445
22446   sqlcipher3VdbeMemRelease(pMem);
22447   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
22448   pMem->enc = desiredEnc;
22449   pMem->flags |= (MEM_Term|MEM_Dyn);
22450   pMem->z = (char*)zOut;
22451   pMem->zMalloc = pMem->z;
22452
22453 translate_out:
22454 #if defined(TRANSLATE_TRACE) && defined(SQLCIPHER_DEBUG)
22455   {
22456     char zBuf[100];
22457     sqlcipher3VdbeMemPrettyPrint(pMem, zBuf);
22458     fprintf(stderr, "OUTPUT: %s\n", zBuf);
22459   }
22460 #endif
22461   return SQLCIPHER_OK;
22462 }
22463
22464 /*
22465 ** This routine checks for a byte-order mark at the beginning of the 
22466 ** UTF-16 string stored in *pMem. If one is present, it is removed and
22467 ** the encoding of the Mem adjusted. This routine does not do any
22468 ** byte-swapping, it just sets Mem.enc appropriately.
22469 **
22470 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
22471 ** changed by this function.
22472 */
22473 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemHandleBom(Mem *pMem){
22474   int rc = SQLCIPHER_OK;
22475   u8 bom = 0;
22476
22477   assert( pMem->n>=0 );
22478   if( pMem->n>1 ){
22479     u8 b1 = *(u8 *)pMem->z;
22480     u8 b2 = *(((u8 *)pMem->z) + 1);
22481     if( b1==0xFE && b2==0xFF ){
22482       bom = SQLCIPHER_UTF16BE;
22483     }
22484     if( b1==0xFF && b2==0xFE ){
22485       bom = SQLCIPHER_UTF16LE;
22486     }
22487   }
22488   
22489   if( bom ){
22490     rc = sqlcipher3VdbeMemMakeWriteable(pMem);
22491     if( rc==SQLCIPHER_OK ){
22492       pMem->n -= 2;
22493       memmove(pMem->z, &pMem->z[2], pMem->n);
22494       pMem->z[pMem->n] = '\0';
22495       pMem->z[pMem->n+1] = '\0';
22496       pMem->flags |= MEM_Term;
22497       pMem->enc = bom;
22498     }
22499   }
22500   return rc;
22501 }
22502 #endif /* SQLCIPHER_OMIT_UTF16 */
22503
22504 /*
22505 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
22506 ** return the number of unicode characters in pZ up to (but not including)
22507 ** the first 0x00 byte. If nByte is not less than zero, return the
22508 ** number of unicode characters in the first nByte of pZ (or up to 
22509 ** the first 0x00, whichever comes first).
22510 */
22511 SQLCIPHER_PRIVATE int sqlcipher3Utf8CharLen(const char *zIn, int nByte){
22512   int r = 0;
22513   const u8 *z = (const u8*)zIn;
22514   const u8 *zTerm;
22515   if( nByte>=0 ){
22516     zTerm = &z[nByte];
22517   }else{
22518     zTerm = (const u8*)(-1);
22519   }
22520   assert( z<=zTerm );
22521   while( *z!=0 && z<zTerm ){
22522     SQLCIPHER_SKIP_UTF8(z);
22523     r++;
22524   }
22525   return r;
22526 }
22527
22528 /* This test function is not currently used by the automated test-suite. 
22529 ** Hence it is only available in debug builds.
22530 */
22531 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
22532 /*
22533 ** Translate UTF-8 to UTF-8.
22534 **
22535 ** This has the effect of making sure that the string is well-formed
22536 ** UTF-8.  Miscoded characters are removed.
22537 **
22538 ** The translation is done in-place and aborted if the output
22539 ** overruns the input.
22540 */
22541 SQLCIPHER_PRIVATE int sqlcipher3Utf8To8(unsigned char *zIn){
22542   unsigned char *zOut = zIn;
22543   unsigned char *zStart = zIn;
22544   u32 c;
22545
22546   while( zIn[0] && zOut<=zIn ){
22547     c = sqlcipher3Utf8Read(zIn, (const u8**)&zIn);
22548     if( c!=0xfffd ){
22549       WRITE_UTF8(zOut, c);
22550     }
22551   }
22552   *zOut = 0;
22553   return (int)(zOut - zStart);
22554 }
22555 #endif
22556
22557 #ifndef SQLCIPHER_OMIT_UTF16
22558 /*
22559 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
22560 ** Memory to hold the UTF-8 string is obtained from sqlcipher3_malloc and must
22561 ** be freed by the calling function.
22562 **
22563 ** NULL is returned if there is an allocation error.
22564 */
22565 SQLCIPHER_PRIVATE char *sqlcipher3Utf16to8(sqlcipher3 *db, const void *z, int nByte, u8 enc){
22566   Mem m;
22567   memset(&m, 0, sizeof(m));
22568   m.db = db;
22569   sqlcipher3VdbeMemSetStr(&m, z, nByte, enc, SQLCIPHER_STATIC);
22570   sqlcipher3VdbeChangeEncoding(&m, SQLCIPHER_UTF8);
22571   if( db->mallocFailed ){
22572     sqlcipher3VdbeMemRelease(&m);
22573     m.z = 0;
22574   }
22575   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
22576   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
22577   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
22578   assert( m.z || db->mallocFailed );
22579   return m.z;
22580 }
22581
22582 /*
22583 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
22584 ** enc. A pointer to the new string is returned, and the value of *pnOut
22585 ** is set to the length of the returned string in bytes. The call should
22586 ** arrange to call sqlcipher3DbFree() on the returned pointer when it is
22587 ** no longer required.
22588 ** 
22589 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
22590 ** flag set.
22591 */
22592 #ifdef SQLCIPHER_ENABLE_STAT3
22593 SQLCIPHER_PRIVATE char *sqlcipher3Utf8to16(sqlcipher3 *db, u8 enc, char *z, int n, int *pnOut){
22594   Mem m;
22595   memset(&m, 0, sizeof(m));
22596   m.db = db;
22597   sqlcipher3VdbeMemSetStr(&m, z, n, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
22598   if( sqlcipher3VdbeMemTranslate(&m, enc) ){
22599     assert( db->mallocFailed );
22600     return 0;
22601   }
22602   assert( m.z==m.zMalloc );
22603   *pnOut = m.n;
22604   return m.z;
22605 }
22606 #endif
22607
22608 /*
22609 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
22610 ** Return the number of bytes in the first nChar unicode characters
22611 ** in pZ.  nChar must be non-negative.
22612 */
22613 SQLCIPHER_PRIVATE int sqlcipher3Utf16ByteLen(const void *zIn, int nChar){
22614   int c;
22615   unsigned char const *z = zIn;
22616   int n = 0;
22617   
22618   if( SQLCIPHER_UTF16NATIVE==SQLCIPHER_UTF16BE ){
22619     while( n<nChar ){
22620       READ_UTF16BE(z, 1, c);
22621       n++;
22622     }
22623   }else{
22624     while( n<nChar ){
22625       READ_UTF16LE(z, 1, c);
22626       n++;
22627     }
22628   }
22629   return (int)(z-(unsigned char const *)zIn);
22630 }
22631
22632 #if defined(SQLCIPHER_TEST)
22633 /*
22634 ** This routine is called from the TCL test function "translate_selftest".
22635 ** It checks that the primitives for serializing and deserializing
22636 ** characters in each encoding are inverses of each other.
22637 */
22638 SQLCIPHER_PRIVATE void sqlcipher3UtfSelfTest(void){
22639   unsigned int i, t;
22640   unsigned char zBuf[20];
22641   unsigned char *z;
22642   int n;
22643   unsigned int c;
22644
22645   for(i=0; i<0x00110000; i++){
22646     z = zBuf;
22647     WRITE_UTF8(z, i);
22648     n = (int)(z-zBuf);
22649     assert( n>0 && n<=4 );
22650     z[0] = 0;
22651     z = zBuf;
22652     c = sqlcipher3Utf8Read(z, (const u8**)&z);
22653     t = i;
22654     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
22655     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
22656     assert( c==t );
22657     assert( (z-zBuf)==n );
22658   }
22659   for(i=0; i<0x00110000; i++){
22660     if( i>=0xD800 && i<0xE000 ) continue;
22661     z = zBuf;
22662     WRITE_UTF16LE(z, i);
22663     n = (int)(z-zBuf);
22664     assert( n>0 && n<=4 );
22665     z[0] = 0;
22666     z = zBuf;
22667     READ_UTF16LE(z, 1, c);
22668     assert( c==i );
22669     assert( (z-zBuf)==n );
22670   }
22671   for(i=0; i<0x00110000; i++){
22672     if( i>=0xD800 && i<0xE000 ) continue;
22673     z = zBuf;
22674     WRITE_UTF16BE(z, i);
22675     n = (int)(z-zBuf);
22676     assert( n>0 && n<=4 );
22677     z[0] = 0;
22678     z = zBuf;
22679     READ_UTF16BE(z, 1, c);
22680     assert( c==i );
22681     assert( (z-zBuf)==n );
22682   }
22683 }
22684 #endif /* SQLCIPHER_TEST */
22685 #endif /* SQLCIPHER_OMIT_UTF16 */
22686
22687 /************** End of utf.c *************************************************/
22688 /************** Begin file util.c ********************************************/
22689 /*
22690 ** 2001 September 15
22691 **
22692 ** The author disclaims copyright to this source code.  In place of
22693 ** a legal notice, here is a blessing:
22694 **
22695 **    May you do good and not evil.
22696 **    May you find forgiveness for yourself and forgive others.
22697 **    May you share freely, never taking more than you give.
22698 **
22699 *************************************************************************
22700 ** Utility functions used throughout sqlcipher.
22701 **
22702 ** This file contains functions for allocating memory, comparing
22703 ** strings, and stuff like that.
22704 **
22705 */
22706 /* #include <stdarg.h> */
22707 #ifdef SQLCIPHER_HAVE_ISNAN
22708 # include <math.h>
22709 #endif
22710
22711 /*
22712 ** Routine needed to support the testcase() macro.
22713 */
22714 #ifdef SQLCIPHER_COVERAGE_TEST
22715 SQLCIPHER_PRIVATE void sqlcipher3Coverage(int x){
22716   static unsigned dummy = 0;
22717   dummy += (unsigned)x;
22718 }
22719 #endif
22720
22721 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
22722 /*
22723 ** Return true if the floating point value is Not a Number (NaN).
22724 **
22725 ** Use the math library isnan() function if compiled with SQLCIPHER_HAVE_ISNAN.
22726 ** Otherwise, we have our own implementation that works on most systems.
22727 */
22728 SQLCIPHER_PRIVATE int sqlcipher3IsNaN(double x){
22729   int rc;   /* The value return */
22730 #if !defined(SQLCIPHER_HAVE_ISNAN)
22731   /*
22732   ** Systems that support the isnan() library function should probably
22733   ** make use of it by compiling with -DSQLCIPHER_HAVE_ISNAN.  But we have
22734   ** found that many systems do not have a working isnan() function so
22735   ** this implementation is provided as an alternative.
22736   **
22737   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
22738   ** On the other hand, the use of -ffast-math comes with the following
22739   ** warning:
22740   **
22741   **      This option [-ffast-math] should never be turned on by any
22742   **      -O option since it can result in incorrect output for programs
22743   **      which depend on an exact implementation of IEEE or ISO 
22744   **      rules/specifications for math functions.
22745   **
22746   ** Under MSVC, this NaN test may fail if compiled with a floating-
22747   ** point precision mode other than /fp:precise.  From the MSDN 
22748   ** documentation:
22749   **
22750   **      The compiler [with /fp:precise] will properly handle comparisons 
22751   **      involving NaN. For example, x != x evaluates to true if x is NaN 
22752   **      ...
22753   */
22754 #ifdef __FAST_MATH__
22755 # error SQLite will not work correctly with the -ffast-math option of GCC.
22756 #endif
22757   volatile double y = x;
22758   volatile double z = y;
22759   rc = (y!=z);
22760 #else  /* if defined(SQLCIPHER_HAVE_ISNAN) */
22761   rc = isnan(x);
22762 #endif /* SQLCIPHER_HAVE_ISNAN */
22763   testcase( rc );
22764   return rc;
22765 }
22766 #endif /* SQLCIPHER_OMIT_FLOATING_POINT */
22767
22768 /*
22769 ** Compute a string length that is limited to what can be stored in
22770 ** lower 30 bits of a 32-bit signed integer.
22771 **
22772 ** The value returned will never be negative.  Nor will it ever be greater
22773 ** than the actual length of the string.  For very long strings (greater
22774 ** than 1GiB) the value returned might be less than the true string length.
22775 */
22776 SQLCIPHER_PRIVATE int sqlcipher3Strlen30(const char *z){
22777   const char *z2 = z;
22778   if( z==0 ) return 0;
22779   while( *z2 ){ z2++; }
22780   return 0x3fffffff & (int)(z2 - z);
22781 }
22782
22783 /*
22784 ** Set the most recent error code and error string for the sqlcipher
22785 ** handle "db". The error code is set to "err_code".
22786 **
22787 ** If it is not NULL, string zFormat specifies the format of the
22788 ** error string in the style of the printf functions: The following
22789 ** format characters are allowed:
22790 **
22791 **      %s      Insert a string
22792 **      %z      A string that should be freed after use
22793 **      %d      Insert an integer
22794 **      %T      Insert a token
22795 **      %S      Insert the first element of a SrcList
22796 **
22797 ** zFormat and any string tokens that follow it are assumed to be
22798 ** encoded in UTF-8.
22799 **
22800 ** To clear the most recent error for sqlcipher handle "db", sqlcipher3Error
22801 ** should be called with err_code set to SQLCIPHER_OK and zFormat set
22802 ** to NULL.
22803 */
22804 SQLCIPHER_PRIVATE void sqlcipher3Error(sqlcipher3 *db, int err_code, const char *zFormat, ...){
22805   if( db && (db->pErr || (db->pErr = sqlcipher3ValueNew(db))!=0) ){
22806     db->errCode = err_code;
22807     if( zFormat ){
22808       char *z;
22809       va_list ap;
22810       va_start(ap, zFormat);
22811       z = sqlcipher3VMPrintf(db, zFormat, ap);
22812       va_end(ap);
22813       sqlcipher3ValueSetStr(db->pErr, -1, z, SQLCIPHER_UTF8, SQLCIPHER_DYNAMIC);
22814     }else{
22815       sqlcipher3ValueSetStr(db->pErr, 0, 0, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
22816     }
22817   }
22818 }
22819
22820 /*
22821 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
22822 ** The following formatting characters are allowed:
22823 **
22824 **      %s      Insert a string
22825 **      %z      A string that should be freed after use
22826 **      %d      Insert an integer
22827 **      %T      Insert a token
22828 **      %S      Insert the first element of a SrcList
22829 **
22830 ** This function should be used to report any error that occurs whilst
22831 ** compiling an SQL statement (i.e. within sqlcipher3_prepare()). The
22832 ** last thing the sqlcipher3_prepare() function does is copy the error
22833 ** stored by this function into the database handle using sqlcipher3Error().
22834 ** Function sqlcipher3Error() should be used during statement execution
22835 ** (sqlcipher3_step() etc.).
22836 */
22837 SQLCIPHER_PRIVATE void sqlcipher3ErrorMsg(Parse *pParse, const char *zFormat, ...){
22838   char *zMsg;
22839   va_list ap;
22840   sqlcipher3 *db = pParse->db;
22841   va_start(ap, zFormat);
22842   zMsg = sqlcipher3VMPrintf(db, zFormat, ap);
22843   va_end(ap);
22844   if( db->suppressErr ){
22845     sqlcipher3DbFree(db, zMsg);
22846   }else{
22847     pParse->nErr++;
22848     sqlcipher3DbFree(db, pParse->zErrMsg);
22849     pParse->zErrMsg = zMsg;
22850     pParse->rc = SQLCIPHER_ERROR;
22851   }
22852 }
22853
22854 /*
22855 ** Convert an SQL-style quoted string into a normal string by removing
22856 ** the quote characters.  The conversion is done in-place.  If the
22857 ** input does not begin with a quote character, then this routine
22858 ** is a no-op.
22859 **
22860 ** The input string must be zero-terminated.  A new zero-terminator
22861 ** is added to the dequoted string.
22862 **
22863 ** The return value is -1 if no dequoting occurs or the length of the
22864 ** dequoted string, exclusive of the zero terminator, if dequoting does
22865 ** occur.
22866 **
22867 ** 2002-Feb-14: This routine is extended to remove MS-Access style
22868 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
22869 ** "a-b-c".
22870 */
22871 SQLCIPHER_PRIVATE int sqlcipher3Dequote(char *z){
22872   char quote;
22873   int i, j;
22874   if( z==0 ) return -1;
22875   quote = z[0];
22876   switch( quote ){
22877     case '\'':  break;
22878     case '"':   break;
22879     case '`':   break;                /* For MySQL compatibility */
22880     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
22881     default:    return -1;
22882   }
22883   for(i=1, j=0; ALWAYS(z[i]); i++){
22884     if( z[i]==quote ){
22885       if( z[i+1]==quote ){
22886         z[j++] = quote;
22887         i++;
22888       }else{
22889         break;
22890       }
22891     }else{
22892       z[j++] = z[i];
22893     }
22894   }
22895   z[j] = 0;
22896   return j;
22897 }
22898
22899 /* Convenient short-hand */
22900 #define UpperToLower sqlcipher3UpperToLower
22901
22902 /*
22903 ** Some systems have stricmp().  Others have strcasecmp().  Because
22904 ** there is no consistency, we will define our own.
22905 **
22906 ** IMPLEMENTATION-OF: R-20522-24639 The sqlcipher3_strnicmp() API allows
22907 ** applications and extensions to compare the contents of two buffers
22908 ** containing UTF-8 strings in a case-independent fashion, using the same
22909 ** definition of case independence that SQLite uses internally when
22910 ** comparing identifiers.
22911 */
22912 SQLCIPHER_PRIVATE int sqlcipher3StrICmp(const char *zLeft, const char *zRight){
22913   register unsigned char *a, *b;
22914   a = (unsigned char *)zLeft;
22915   b = (unsigned char *)zRight;
22916   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
22917   return UpperToLower[*a] - UpperToLower[*b];
22918 }
22919 SQLCIPHER_API int sqlcipher3_strnicmp(const char *zLeft, const char *zRight, int N){
22920   register unsigned char *a, *b;
22921   a = (unsigned char *)zLeft;
22922   b = (unsigned char *)zRight;
22923   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
22924   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
22925 }
22926
22927 /*
22928 ** The string z[] is an text representation of a real number.
22929 ** Convert this string to a double and write it into *pResult.
22930 **
22931 ** The string z[] is length bytes in length (bytes, not characters) and
22932 ** uses the encoding enc.  The string is not necessarily zero-terminated.
22933 **
22934 ** Return TRUE if the result is a valid real number (or integer) and FALSE
22935 ** if the string is empty or contains extraneous text.  Valid numbers
22936 ** are in one of these formats:
22937 **
22938 **    [+-]digits[E[+-]digits]
22939 **    [+-]digits.[digits][E[+-]digits]
22940 **    [+-].digits[E[+-]digits]
22941 **
22942 ** Leading and trailing whitespace is ignored for the purpose of determining
22943 ** validity.
22944 **
22945 ** If some prefix of the input string is a valid number, this routine
22946 ** returns FALSE but it still converts the prefix and writes the result
22947 ** into *pResult.
22948 */
22949 SQLCIPHER_PRIVATE int sqlcipher3AtoF(const char *z, double *pResult, int length, u8 enc){
22950 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
22951   int incr = (enc==SQLCIPHER_UTF8?1:2);
22952   const char *zEnd = z + length;
22953   /* sign * significand * (10 ^ (esign * exponent)) */
22954   int sign = 1;    /* sign of significand */
22955   i64 s = 0;       /* significand */
22956   int d = 0;       /* adjust exponent for shifting decimal point */
22957   int esign = 1;   /* sign of exponent */
22958   int e = 0;       /* exponent */
22959   int eValid = 1;  /* True exponent is either not used or is well-formed */
22960   double result;
22961   int nDigits = 0;
22962
22963   *pResult = 0.0;   /* Default return value, in case of an error */
22964
22965   if( enc==SQLCIPHER_UTF16BE ) z++;
22966
22967   /* skip leading spaces */
22968   while( z<zEnd && sqlcipher3Isspace(*z) ) z+=incr;
22969   if( z>=zEnd ) return 0;
22970
22971   /* get sign of significand */
22972   if( *z=='-' ){
22973     sign = -1;
22974     z+=incr;
22975   }else if( *z=='+' ){
22976     z+=incr;
22977   }
22978
22979   /* skip leading zeroes */
22980   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
22981
22982   /* copy max significant digits to significand */
22983   while( z<zEnd && sqlcipher3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
22984     s = s*10 + (*z - '0');
22985     z+=incr, nDigits++;
22986   }
22987
22988   /* skip non-significant significand digits
22989   ** (increase exponent by d to shift decimal left) */
22990   while( z<zEnd && sqlcipher3Isdigit(*z) ) z+=incr, nDigits++, d++;
22991   if( z>=zEnd ) goto do_atof_calc;
22992
22993   /* if decimal point is present */
22994   if( *z=='.' ){
22995     z+=incr;
22996     /* copy digits from after decimal to significand
22997     ** (decrease exponent by d to shift decimal right) */
22998     while( z<zEnd && sqlcipher3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
22999       s = s*10 + (*z - '0');
23000       z+=incr, nDigits++, d--;
23001     }
23002     /* skip non-significant digits */
23003     while( z<zEnd && sqlcipher3Isdigit(*z) ) z+=incr, nDigits++;
23004   }
23005   if( z>=zEnd ) goto do_atof_calc;
23006
23007   /* if exponent is present */
23008   if( *z=='e' || *z=='E' ){
23009     z+=incr;
23010     eValid = 0;
23011     if( z>=zEnd ) goto do_atof_calc;
23012     /* get sign of exponent */
23013     if( *z=='-' ){
23014       esign = -1;
23015       z+=incr;
23016     }else if( *z=='+' ){
23017       z+=incr;
23018     }
23019     /* copy digits to exponent */
23020     while( z<zEnd && sqlcipher3Isdigit(*z) ){
23021       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23022       z+=incr;
23023       eValid = 1;
23024     }
23025   }
23026
23027   /* skip trailing spaces */
23028   if( nDigits && eValid ){
23029     while( z<zEnd && sqlcipher3Isspace(*z) ) z+=incr;
23030   }
23031
23032 do_atof_calc:
23033   /* adjust exponent by d, and update sign */
23034   e = (e*esign) + d;
23035   if( e<0 ) {
23036     esign = -1;
23037     e *= -1;
23038   } else {
23039     esign = 1;
23040   }
23041
23042   /* if 0 significand */
23043   if( !s ) {
23044     /* In the IEEE 754 standard, zero is signed.
23045     ** Add the sign if we've seen at least one digit */
23046     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23047   } else {
23048     /* attempt to reduce exponent */
23049     if( esign>0 ){
23050       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23051     }else{
23052       while( !(s%10) && e>0 ) e--,s/=10;
23053     }
23054
23055     /* adjust the sign of significand */
23056     s = sign<0 ? -s : s;
23057
23058     /* if exponent, scale significand as appropriate
23059     ** and store in result. */
23060     if( e ){
23061       double scale = 1.0;
23062       /* attempt to handle extremely small/large numbers better */
23063       if( e>307 && e<342 ){
23064         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23065         if( esign<0 ){
23066           result = s / scale;
23067           result /= 1.0e+308;
23068         }else{
23069           result = s * scale;
23070           result *= 1.0e+308;
23071         }
23072       }else if( e>=342 ){
23073         if( esign<0 ){
23074           result = 0.0*s;
23075         }else{
23076           result = 1e308*1e308*s;  /* Infinity */
23077         }
23078       }else{
23079         /* 1.0e+22 is the largest power of 10 than can be 
23080         ** represented exactly. */
23081         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23082         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23083         if( esign<0 ){
23084           result = s / scale;
23085         }else{
23086           result = s * scale;
23087         }
23088       }
23089     } else {
23090       result = (double)s;
23091     }
23092   }
23093
23094   /* store the result */
23095   *pResult = result;
23096
23097   /* return true if number and no extra non-whitespace chracters after */
23098   return z>=zEnd && nDigits>0 && eValid;
23099 #else
23100   return !sqlcipher3Atoi64(z, pResult, length, enc);
23101 #endif /* SQLCIPHER_OMIT_FLOATING_POINT */
23102 }
23103
23104 /*
23105 ** Compare the 19-character string zNum against the text representation
23106 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
23107 ** if zNum is less than, equal to, or greater than the string.
23108 ** Note that zNum must contain exactly 19 characters.
23109 **
23110 ** Unlike memcmp() this routine is guaranteed to return the difference
23111 ** in the values of the last digit if the only difference is in the
23112 ** last digit.  So, for example,
23113 **
23114 **      compare2pow63("9223372036854775800", 1)
23115 **
23116 ** will return -8.
23117 */
23118 static int compare2pow63(const char *zNum, int incr){
23119   int c = 0;
23120   int i;
23121                     /* 012345678901234567 */
23122   const char *pow63 = "922337203685477580";
23123   for(i=0; c==0 && i<18; i++){
23124     c = (zNum[i*incr]-pow63[i])*10;
23125   }
23126   if( c==0 ){
23127     c = zNum[18*incr] - '8';
23128     testcase( c==(-1) );
23129     testcase( c==0 );
23130     testcase( c==(+1) );
23131   }
23132   return c;
23133 }
23134
23135
23136 /*
23137 ** Convert zNum to a 64-bit signed integer.
23138 **
23139 ** If the zNum value is representable as a 64-bit twos-complement 
23140 ** integer, then write that value into *pNum and return 0.
23141 **
23142 ** If zNum is exactly 9223372036854665808, return 2.  This special
23143 ** case is broken out because while 9223372036854665808 cannot be a 
23144 ** signed 64-bit integer, its negative -9223372036854665808 can be.
23145 **
23146 ** If zNum is too big for a 64-bit integer and is not
23147 ** 9223372036854665808 then return 1.
23148 **
23149 ** length is the number of bytes in the string (bytes, not characters).
23150 ** The string is not necessarily zero-terminated.  The encoding is
23151 ** given by enc.
23152 */
23153 SQLCIPHER_PRIVATE int sqlcipher3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23154   int incr = (enc==SQLCIPHER_UTF8?1:2);
23155   u64 u = 0;
23156   int neg = 0; /* assume positive */
23157   int i;
23158   int c = 0;
23159   const char *zStart;
23160   const char *zEnd = zNum + length;
23161   if( enc==SQLCIPHER_UTF16BE ) zNum++;
23162   while( zNum<zEnd && sqlcipher3Isspace(*zNum) ) zNum+=incr;
23163   if( zNum<zEnd ){
23164     if( *zNum=='-' ){
23165       neg = 1;
23166       zNum+=incr;
23167     }else if( *zNum=='+' ){
23168       zNum+=incr;
23169     }
23170   }
23171   zStart = zNum;
23172   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23173   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23174     u = u*10 + c - '0';
23175   }
23176   if( u>LARGEST_INT64 ){
23177     *pNum = SMALLEST_INT64;
23178   }else if( neg ){
23179     *pNum = -(i64)u;
23180   }else{
23181     *pNum = (i64)u;
23182   }
23183   testcase( i==18 );
23184   testcase( i==19 );
23185   testcase( i==20 );
23186   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
23187     /* zNum is empty or contains non-numeric text or is longer
23188     ** than 19 digits (thus guaranteeing that it is too large) */
23189     return 1;
23190   }else if( i<19*incr ){
23191     /* Less than 19 digits, so we know that it fits in 64 bits */
23192     assert( u<=LARGEST_INT64 );
23193     return 0;
23194   }else{
23195     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
23196     c = compare2pow63(zNum, incr);
23197     if( c<0 ){
23198       /* zNum is less than 9223372036854775808 so it fits */
23199       assert( u<=LARGEST_INT64 );
23200       return 0;
23201     }else if( c>0 ){
23202       /* zNum is greater than 9223372036854775808 so it overflows */
23203       return 1;
23204     }else{
23205       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
23206       ** special case 2 overflow if positive */
23207       assert( u-1==LARGEST_INT64 );
23208       assert( (*pNum)==SMALLEST_INT64 );
23209       return neg ? 0 : 2;
23210     }
23211   }
23212 }
23213
23214 /*
23215 ** If zNum represents an integer that will fit in 32-bits, then set
23216 ** *pValue to that integer and return true.  Otherwise return false.
23217 **
23218 ** Any non-numeric characters that following zNum are ignored.
23219 ** This is different from sqlcipher3Atoi64() which requires the
23220 ** input number to be zero-terminated.
23221 */
23222 SQLCIPHER_PRIVATE int sqlcipher3GetInt32(const char *zNum, int *pValue){
23223   sqlcipher_int64 v = 0;
23224   int i, c;
23225   int neg = 0;
23226   if( zNum[0]=='-' ){
23227     neg = 1;
23228     zNum++;
23229   }else if( zNum[0]=='+' ){
23230     zNum++;
23231   }
23232   while( zNum[0]=='0' ) zNum++;
23233   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
23234     v = v*10 + c;
23235   }
23236
23237   /* The longest decimal representation of a 32 bit integer is 10 digits:
23238   **
23239   **             1234567890
23240   **     2^31 -> 2147483648
23241   */
23242   testcase( i==10 );
23243   if( i>10 ){
23244     return 0;
23245   }
23246   testcase( v-neg==2147483647 );
23247   if( v-neg>2147483647 ){
23248     return 0;
23249   }
23250   if( neg ){
23251     v = -v;
23252   }
23253   *pValue = (int)v;
23254   return 1;
23255 }
23256
23257 /*
23258 ** Return a 32-bit integer value extracted from a string.  If the
23259 ** string is not an integer, just return 0.
23260 */
23261 SQLCIPHER_PRIVATE int sqlcipher3Atoi(const char *z){
23262   int x = 0;
23263   if( z ) sqlcipher3GetInt32(z, &x);
23264   return x;
23265 }
23266
23267 /*
23268 ** The variable-length integer encoding is as follows:
23269 **
23270 ** KEY:
23271 **         A = 0xxxxxxx    7 bits of data and one flag bit
23272 **         B = 1xxxxxxx    7 bits of data and one flag bit
23273 **         C = xxxxxxxx    8 bits of data
23274 **
23275 **  7 bits - A
23276 ** 14 bits - BA
23277 ** 21 bits - BBA
23278 ** 28 bits - BBBA
23279 ** 35 bits - BBBBA
23280 ** 42 bits - BBBBBA
23281 ** 49 bits - BBBBBBA
23282 ** 56 bits - BBBBBBBA
23283 ** 64 bits - BBBBBBBBC
23284 */
23285
23286 /*
23287 ** Write a 64-bit variable-length integer to memory starting at p[0].
23288 ** The length of data write will be between 1 and 9 bytes.  The number
23289 ** of bytes written is returned.
23290 **
23291 ** A variable-length integer consists of the lower 7 bits of each byte
23292 ** for all bytes that have the 8th bit set and one byte with the 8th
23293 ** bit clear.  Except, if we get to the 9th byte, it stores the full
23294 ** 8 bits and is the last byte.
23295 */
23296 SQLCIPHER_PRIVATE int sqlcipher3PutVarint(unsigned char *p, u64 v){
23297   int i, j, n;
23298   u8 buf[10];
23299   if( v & (((u64)0xff000000)<<32) ){
23300     p[8] = (u8)v;
23301     v >>= 8;
23302     for(i=7; i>=0; i--){
23303       p[i] = (u8)((v & 0x7f) | 0x80);
23304       v >>= 7;
23305     }
23306     return 9;
23307   }    
23308   n = 0;
23309   do{
23310     buf[n++] = (u8)((v & 0x7f) | 0x80);
23311     v >>= 7;
23312   }while( v!=0 );
23313   buf[0] &= 0x7f;
23314   assert( n<=9 );
23315   for(i=0, j=n-1; j>=0; j--, i++){
23316     p[i] = buf[j];
23317   }
23318   return n;
23319 }
23320
23321 /*
23322 ** This routine is a faster version of sqlcipher3PutVarint() that only
23323 ** works for 32-bit positive integers and which is optimized for
23324 ** the common case of small integers.  A MACRO version, putVarint32,
23325 ** is provided which inlines the single-byte case.  All code should use
23326 ** the MACRO version as this function assumes the single-byte case has
23327 ** already been handled.
23328 */
23329 SQLCIPHER_PRIVATE int sqlcipher3PutVarint32(unsigned char *p, u32 v){
23330 #ifndef putVarint32
23331   if( (v & ~0x7f)==0 ){
23332     p[0] = v;
23333     return 1;
23334   }
23335 #endif
23336   if( (v & ~0x3fff)==0 ){
23337     p[0] = (u8)((v>>7) | 0x80);
23338     p[1] = (u8)(v & 0x7f);
23339     return 2;
23340   }
23341   return sqlcipher3PutVarint(p, v);
23342 }
23343
23344 /*
23345 ** Bitmasks used by sqlcipher3GetVarint().  These precomputed constants
23346 ** are defined here rather than simply putting the constant expressions
23347 ** inline in order to work around bugs in the RVT compiler.
23348 **
23349 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
23350 **
23351 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
23352 */
23353 #define SLOT_2_0     0x001fc07f
23354 #define SLOT_4_2_0   0xf01fc07f
23355
23356
23357 /*
23358 ** Read a 64-bit variable-length integer from memory starting at p[0].
23359 ** Return the number of bytes read.  The value is stored in *v.
23360 */
23361 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint(const unsigned char *p, u64 *v){
23362   u32 a,b,s;
23363
23364   a = *p;
23365   /* a: p0 (unmasked) */
23366   if (!(a&0x80))
23367   {
23368     *v = a;
23369     return 1;
23370   }
23371
23372   p++;
23373   b = *p;
23374   /* b: p1 (unmasked) */
23375   if (!(b&0x80))
23376   {
23377     a &= 0x7f;
23378     a = a<<7;
23379     a |= b;
23380     *v = a;
23381     return 2;
23382   }
23383
23384   /* Verify that constants are precomputed correctly */
23385   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
23386   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
23387
23388   p++;
23389   a = a<<14;
23390   a |= *p;
23391   /* a: p0<<14 | p2 (unmasked) */
23392   if (!(a&0x80))
23393   {
23394     a &= SLOT_2_0;
23395     b &= 0x7f;
23396     b = b<<7;
23397     a |= b;
23398     *v = a;
23399     return 3;
23400   }
23401
23402   /* CSE1 from below */
23403   a &= SLOT_2_0;
23404   p++;
23405   b = b<<14;
23406   b |= *p;
23407   /* b: p1<<14 | p3 (unmasked) */
23408   if (!(b&0x80))
23409   {
23410     b &= SLOT_2_0;
23411     /* moved CSE1 up */
23412     /* a &= (0x7f<<14)|(0x7f); */
23413     a = a<<7;
23414     a |= b;
23415     *v = a;
23416     return 4;
23417   }
23418
23419   /* a: p0<<14 | p2 (masked) */
23420   /* b: p1<<14 | p3 (unmasked) */
23421   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23422   /* moved CSE1 up */
23423   /* a &= (0x7f<<14)|(0x7f); */
23424   b &= SLOT_2_0;
23425   s = a;
23426   /* s: p0<<14 | p2 (masked) */
23427
23428   p++;
23429   a = a<<14;
23430   a |= *p;
23431   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23432   if (!(a&0x80))
23433   {
23434     /* we can skip these cause they were (effectively) done above in calc'ing s */
23435     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23436     /* b &= (0x7f<<14)|(0x7f); */
23437     b = b<<7;
23438     a |= b;
23439     s = s>>18;
23440     *v = ((u64)s)<<32 | a;
23441     return 5;
23442   }
23443
23444   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23445   s = s<<7;
23446   s |= b;
23447   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23448
23449   p++;
23450   b = b<<14;
23451   b |= *p;
23452   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
23453   if (!(b&0x80))
23454   {
23455     /* we can skip this cause it was (effectively) done above in calc'ing s */
23456     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23457     a &= SLOT_2_0;
23458     a = a<<7;
23459     a |= b;
23460     s = s>>18;
23461     *v = ((u64)s)<<32 | a;
23462     return 6;
23463   }
23464
23465   p++;
23466   a = a<<14;
23467   a |= *p;
23468   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
23469   if (!(a&0x80))
23470   {
23471     a &= SLOT_4_2_0;
23472     b &= SLOT_2_0;
23473     b = b<<7;
23474     a |= b;
23475     s = s>>11;
23476     *v = ((u64)s)<<32 | a;
23477     return 7;
23478   }
23479
23480   /* CSE2 from below */
23481   a &= SLOT_2_0;
23482   p++;
23483   b = b<<14;
23484   b |= *p;
23485   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
23486   if (!(b&0x80))
23487   {
23488     b &= SLOT_4_2_0;
23489     /* moved CSE2 up */
23490     /* a &= (0x7f<<14)|(0x7f); */
23491     a = a<<7;
23492     a |= b;
23493     s = s>>4;
23494     *v = ((u64)s)<<32 | a;
23495     return 8;
23496   }
23497
23498   p++;
23499   a = a<<15;
23500   a |= *p;
23501   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
23502
23503   /* moved CSE2 up */
23504   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
23505   b &= SLOT_2_0;
23506   b = b<<8;
23507   a |= b;
23508
23509   s = s<<4;
23510   b = p[-4];
23511   b &= 0x7f;
23512   b = b>>3;
23513   s |= b;
23514
23515   *v = ((u64)s)<<32 | a;
23516
23517   return 9;
23518 }
23519
23520 /*
23521 ** Read a 32-bit variable-length integer from memory starting at p[0].
23522 ** Return the number of bytes read.  The value is stored in *v.
23523 **
23524 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
23525 ** integer, then set *v to 0xffffffff.
23526 **
23527 ** A MACRO version, getVarint32, is provided which inlines the 
23528 ** single-byte case.  All code should use the MACRO version as 
23529 ** this function assumes the single-byte case has already been handled.
23530 */
23531 SQLCIPHER_PRIVATE u8 sqlcipher3GetVarint32(const unsigned char *p, u32 *v){
23532   u32 a,b;
23533
23534   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
23535   ** by the getVarin32() macro */
23536   a = *p;
23537   /* a: p0 (unmasked) */
23538 #ifndef getVarint32
23539   if (!(a&0x80))
23540   {
23541     /* Values between 0 and 127 */
23542     *v = a;
23543     return 1;
23544   }
23545 #endif
23546
23547   /* The 2-byte case */
23548   p++;
23549   b = *p;
23550   /* b: p1 (unmasked) */
23551   if (!(b&0x80))
23552   {
23553     /* Values between 128 and 16383 */
23554     a &= 0x7f;
23555     a = a<<7;
23556     *v = a | b;
23557     return 2;
23558   }
23559
23560   /* The 3-byte case */
23561   p++;
23562   a = a<<14;
23563   a |= *p;
23564   /* a: p0<<14 | p2 (unmasked) */
23565   if (!(a&0x80))
23566   {
23567     /* Values between 16384 and 2097151 */
23568     a &= (0x7f<<14)|(0x7f);
23569     b &= 0x7f;
23570     b = b<<7;
23571     *v = a | b;
23572     return 3;
23573   }
23574
23575   /* A 32-bit varint is used to store size information in btrees.
23576   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
23577   ** A 3-byte varint is sufficient, for example, to record the size
23578   ** of a 1048569-byte BLOB or string.
23579   **
23580   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
23581   ** rare larger cases can be handled by the slower 64-bit varint
23582   ** routine.
23583   */
23584 #if 1
23585   {
23586     u64 v64;
23587     u8 n;
23588
23589     p -= 2;
23590     n = sqlcipher3GetVarint(p, &v64);
23591     assert( n>3 && n<=9 );
23592     if( (v64 & SQLCIPHER_MAX_U32)!=v64 ){
23593       *v = 0xffffffff;
23594     }else{
23595       *v = (u32)v64;
23596     }
23597     return n;
23598   }
23599
23600 #else
23601   /* For following code (kept for historical record only) shows an
23602   ** unrolling for the 3- and 4-byte varint cases.  This code is
23603   ** slightly faster, but it is also larger and much harder to test.
23604   */
23605   p++;
23606   b = b<<14;
23607   b |= *p;
23608   /* b: p1<<14 | p3 (unmasked) */
23609   if (!(b&0x80))
23610   {
23611     /* Values between 2097152 and 268435455 */
23612     b &= (0x7f<<14)|(0x7f);
23613     a &= (0x7f<<14)|(0x7f);
23614     a = a<<7;
23615     *v = a | b;
23616     return 4;
23617   }
23618
23619   p++;
23620   a = a<<14;
23621   a |= *p;
23622   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23623   if (!(a&0x80))
23624   {
23625     /* Values  between 268435456 and 34359738367 */
23626     a &= SLOT_4_2_0;
23627     b &= SLOT_4_2_0;
23628     b = b<<7;
23629     *v = a | b;
23630     return 5;
23631   }
23632
23633   /* We can only reach this point when reading a corrupt database
23634   ** file.  In that case we are not in any hurry.  Use the (relatively
23635   ** slow) general-purpose sqlcipher3GetVarint() routine to extract the
23636   ** value. */
23637   {
23638     u64 v64;
23639     u8 n;
23640
23641     p -= 4;
23642     n = sqlcipher3GetVarint(p, &v64);
23643     assert( n>5 && n<=9 );
23644     *v = (u32)v64;
23645     return n;
23646   }
23647 #endif
23648 }
23649
23650 /*
23651 ** Return the number of bytes that will be needed to store the given
23652 ** 64-bit integer.
23653 */
23654 SQLCIPHER_PRIVATE int sqlcipher3VarintLen(u64 v){
23655   int i = 0;
23656   do{
23657     i++;
23658     v >>= 7;
23659   }while( v!=0 && ALWAYS(i<9) );
23660   return i;
23661 }
23662
23663
23664 /*
23665 ** Read or write a four-byte big-endian integer value.
23666 */
23667 SQLCIPHER_PRIVATE u32 sqlcipher3Get4byte(const u8 *p){
23668   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
23669 }
23670 SQLCIPHER_PRIVATE void sqlcipher3Put4byte(unsigned char *p, u32 v){
23671   p[0] = (u8)(v>>24);
23672   p[1] = (u8)(v>>16);
23673   p[2] = (u8)(v>>8);
23674   p[3] = (u8)v;
23675 }
23676
23677
23678
23679 /*
23680 ** Translate a single byte of Hex into an integer.
23681 ** This routine only works if h really is a valid hexadecimal
23682 ** character:  0..9a..fA..F
23683 */
23684 SQLCIPHER_PRIVATE u8 sqlcipher3HexToInt(int h){
23685   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
23686 #ifdef SQLCIPHER_ASCII
23687   h += 9*(1&(h>>6));
23688 #endif
23689 #ifdef SQLCIPHER_EBCDIC
23690   h += 9*(1&~(h>>4));
23691 #endif
23692   return (u8)(h & 0xf);
23693 }
23694
23695 #if !defined(SQLCIPHER_OMIT_BLOB_LITERAL) || defined(SQLCIPHER_HAS_CODEC)
23696 /*
23697 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
23698 ** value.  Return a pointer to its binary value.  Space to hold the
23699 ** binary value has been obtained from malloc and must be freed by
23700 ** the calling routine.
23701 */
23702 SQLCIPHER_PRIVATE void *sqlcipher3HexToBlob(sqlcipher3 *db, const char *z, int n){
23703   char *zBlob;
23704   int i;
23705
23706   zBlob = (char *)sqlcipher3DbMallocRaw(db, n/2 + 1);
23707   n--;
23708   if( zBlob ){
23709     for(i=0; i<n; i+=2){
23710       zBlob[i/2] = (sqlcipher3HexToInt(z[i])<<4) | sqlcipher3HexToInt(z[i+1]);
23711     }
23712     zBlob[i/2] = 0;
23713   }
23714   return zBlob;
23715 }
23716 #endif /* !SQLCIPHER_OMIT_BLOB_LITERAL || SQLCIPHER_HAS_CODEC */
23717
23718 /*
23719 ** Log an error that is an API call on a connection pointer that should
23720 ** not have been used.  The "type" of connection pointer is given as the
23721 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
23722 */
23723 static void logBadConnection(const char *zType){
23724   sqlcipher3_log(SQLCIPHER_MISUSE, 
23725      "API call with %s database connection pointer",
23726      zType
23727   );
23728 }
23729
23730 /*
23731 ** Check to make sure we have a valid db pointer.  This test is not
23732 ** foolproof but it does provide some measure of protection against
23733 ** misuse of the interface such as passing in db pointers that are
23734 ** NULL or which have been previously closed.  If this routine returns
23735 ** 1 it means that the db pointer is valid and 0 if it should not be
23736 ** dereferenced for any reason.  The calling function should invoke
23737 ** SQLCIPHER_MISUSE immediately.
23738 **
23739 ** sqlcipher3SafetyCheckOk() requires that the db pointer be valid for
23740 ** use.  sqlcipher3SafetyCheckSickOrOk() allows a db pointer that failed to
23741 ** open properly and is not fit for general use but which can be
23742 ** used as an argument to sqlcipher3_errmsg() or sqlcipher3_close().
23743 */
23744 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckOk(sqlcipher3 *db){
23745   u32 magic;
23746   if( db==0 ){
23747     logBadConnection("NULL");
23748     return 0;
23749   }
23750   magic = db->magic;
23751   if( magic!=SQLCIPHER_MAGIC_OPEN ){
23752     if( sqlcipher3SafetyCheckSickOrOk(db) ){
23753       testcase( sqlcipher3GlobalConfig.xLog!=0 );
23754       logBadConnection("unopened");
23755     }
23756     return 0;
23757   }else{
23758     return 1;
23759   }
23760 }
23761 SQLCIPHER_PRIVATE int sqlcipher3SafetyCheckSickOrOk(sqlcipher3 *db){
23762   u32 magic;
23763   magic = db->magic;
23764   if( magic!=SQLCIPHER_MAGIC_SICK &&
23765       magic!=SQLCIPHER_MAGIC_OPEN &&
23766       magic!=SQLCIPHER_MAGIC_BUSY ){
23767     testcase( sqlcipher3GlobalConfig.xLog!=0 );
23768     logBadConnection("invalid");
23769     return 0;
23770   }else{
23771     return 1;
23772   }
23773 }
23774
23775 /*
23776 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
23777 ** the other 64-bit signed integer at *pA and store the result in *pA.
23778 ** Return 0 on success.  Or if the operation would have resulted in an
23779 ** overflow, leave *pA unchanged and return 1.
23780 */
23781 SQLCIPHER_PRIVATE int sqlcipher3AddInt64(i64 *pA, i64 iB){
23782   i64 iA = *pA;
23783   testcase( iA==0 ); testcase( iA==1 );
23784   testcase( iB==-1 ); testcase( iB==0 );
23785   if( iB>=0 ){
23786     testcase( iA>0 && LARGEST_INT64 - iA == iB );
23787     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
23788     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
23789     *pA += iB;
23790   }else{
23791     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
23792     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
23793     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
23794     *pA += iB;
23795   }
23796   return 0; 
23797 }
23798 SQLCIPHER_PRIVATE int sqlcipher3SubInt64(i64 *pA, i64 iB){
23799   testcase( iB==SMALLEST_INT64+1 );
23800   if( iB==SMALLEST_INT64 ){
23801     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
23802     if( (*pA)>=0 ) return 1;
23803     *pA -= iB;
23804     return 0;
23805   }else{
23806     return sqlcipher3AddInt64(pA, -iB);
23807   }
23808 }
23809 #define TWOPOWER32 (((i64)1)<<32)
23810 #define TWOPOWER31 (((i64)1)<<31)
23811 SQLCIPHER_PRIVATE int sqlcipher3MulInt64(i64 *pA, i64 iB){
23812   i64 iA = *pA;
23813   i64 iA1, iA0, iB1, iB0, r;
23814
23815   iA1 = iA/TWOPOWER32;
23816   iA0 = iA % TWOPOWER32;
23817   iB1 = iB/TWOPOWER32;
23818   iB0 = iB % TWOPOWER32;
23819   if( iA1*iB1 != 0 ) return 1;
23820   assert( iA1*iB0==0 || iA0*iB1==0 );
23821   r = iA1*iB0 + iA0*iB1;
23822   testcase( r==(-TWOPOWER31)-1 );
23823   testcase( r==(-TWOPOWER31) );
23824   testcase( r==TWOPOWER31 );
23825   testcase( r==TWOPOWER31-1 );
23826   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
23827   r *= TWOPOWER32;
23828   if( sqlcipher3AddInt64(&r, iA0*iB0) ) return 1;
23829   *pA = r;
23830   return 0;
23831 }
23832
23833 /*
23834 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
23835 ** if the integer has a value of -2147483648, return +2147483647
23836 */
23837 SQLCIPHER_PRIVATE int sqlcipher3AbsInt32(int x){
23838   if( x>=0 ) return x;
23839   if( x==(int)0x80000000 ) return 0x7fffffff;
23840   return -x;
23841 }
23842
23843 #ifdef SQLCIPHER_ENABLE_8_3_NAMES
23844 /*
23845 ** If SQLCIPHER_ENABLE_8_3_NAMES is set at compile-time and if the database
23846 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
23847 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
23848 ** three characters, then shorten the suffix on z[] to be the last three
23849 ** characters of the original suffix.
23850 **
23851 ** If SQLCIPHER_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
23852 ** do the suffix shortening regardless of URI parameter.
23853 **
23854 ** Examples:
23855 **
23856 **     test.db-journal    =>   test.nal
23857 **     test.db-wal        =>   test.wal
23858 **     test.db-shm        =>   test.shm
23859 */
23860 SQLCIPHER_PRIVATE void sqlcipher3FileSuffix3(const char *zBaseFilename, char *z){
23861 #if SQLCIPHER_ENABLE_8_3_NAMES<2
23862   const char *zOk;
23863   zOk = sqlcipher3_uri_parameter(zBaseFilename, "8_3_names");
23864   if( zOk && sqlcipher3GetBoolean(zOk) )
23865 #endif
23866   {
23867     int i, sz;
23868     sz = sqlcipher3Strlen30(z);
23869     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
23870     if( z[i]=='.' && ALWAYS(sz>i+4) ) memcpy(&z[i+1], &z[sz-3], 4);
23871   }
23872 }
23873 #endif
23874
23875 /************** End of util.c ************************************************/
23876 /************** Begin file hash.c ********************************************/
23877 /*
23878 ** 2001 September 22
23879 **
23880 ** The author disclaims copyright to this source code.  In place of
23881 ** a legal notice, here is a blessing:
23882 **
23883 **    May you do good and not evil.
23884 **    May you find forgiveness for yourself and forgive others.
23885 **    May you share freely, never taking more than you give.
23886 **
23887 *************************************************************************
23888 ** This is the implementation of generic hash-tables
23889 ** used in SQLite.
23890 */
23891 /* #include <assert.h> */
23892
23893 /* Turn bulk memory into a hash table object by initializing the
23894 ** fields of the Hash structure.
23895 **
23896 ** "pNew" is a pointer to the hash table that is to be initialized.
23897 */
23898 SQLCIPHER_PRIVATE void sqlcipher3HashInit(Hash *pNew){
23899   assert( pNew!=0 );
23900   pNew->first = 0;
23901   pNew->count = 0;
23902   pNew->htsize = 0;
23903   pNew->ht = 0;
23904 }
23905
23906 /* Remove all entries from a hash table.  Reclaim all memory.
23907 ** Call this routine to delete a hash table or to reset a hash table
23908 ** to the empty state.
23909 */
23910 SQLCIPHER_PRIVATE void sqlcipher3HashClear(Hash *pH){
23911   HashElem *elem;         /* For looping over all elements of the table */
23912
23913   assert( pH!=0 );
23914   elem = pH->first;
23915   pH->first = 0;
23916   sqlcipher3_free(pH->ht);
23917   pH->ht = 0;
23918   pH->htsize = 0;
23919   while( elem ){
23920     HashElem *next_elem = elem->next;
23921     sqlcipher3_free(elem);
23922     elem = next_elem;
23923   }
23924   pH->count = 0;
23925 }
23926
23927 /*
23928 ** The hashing function.
23929 */
23930 static unsigned int strHash(const char *z, int nKey){
23931   int h = 0;
23932   assert( nKey>=0 );
23933   while( nKey > 0  ){
23934     h = (h<<3) ^ h ^ sqlcipher3UpperToLower[(unsigned char)*z++];
23935     nKey--;
23936   }
23937   return h;
23938 }
23939
23940
23941 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
23942 ** insert pNew into the pEntry hash bucket.
23943 */
23944 static void insertElement(
23945   Hash *pH,              /* The complete hash table */
23946   struct _ht *pEntry,    /* The entry into which pNew is inserted */
23947   HashElem *pNew         /* The element to be inserted */
23948 ){
23949   HashElem *pHead;       /* First element already in pEntry */
23950   if( pEntry ){
23951     pHead = pEntry->count ? pEntry->chain : 0;
23952     pEntry->count++;
23953     pEntry->chain = pNew;
23954   }else{
23955     pHead = 0;
23956   }
23957   if( pHead ){
23958     pNew->next = pHead;
23959     pNew->prev = pHead->prev;
23960     if( pHead->prev ){ pHead->prev->next = pNew; }
23961     else             { pH->first = pNew; }
23962     pHead->prev = pNew;
23963   }else{
23964     pNew->next = pH->first;
23965     if( pH->first ){ pH->first->prev = pNew; }
23966     pNew->prev = 0;
23967     pH->first = pNew;
23968   }
23969 }
23970
23971
23972 /* Resize the hash table so that it cantains "new_size" buckets.
23973 **
23974 ** The hash table might fail to resize if sqlcipher3_malloc() fails or
23975 ** if the new size is the same as the prior size.
23976 ** Return TRUE if the resize occurs and false if not.
23977 */
23978 static int rehash(Hash *pH, unsigned int new_size){
23979   struct _ht *new_ht;            /* The new hash table */
23980   HashElem *elem, *next_elem;    /* For looping over existing elements */
23981
23982 #if SQLCIPHER_MALLOC_SOFT_LIMIT>0
23983   if( new_size*sizeof(struct _ht)>SQLCIPHER_MALLOC_SOFT_LIMIT ){
23984     new_size = SQLCIPHER_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
23985   }
23986   if( new_size==pH->htsize ) return 0;
23987 #endif
23988
23989   /* The inability to allocates space for a larger hash table is
23990   ** a performance hit but it is not a fatal error.  So mark the
23991   ** allocation as a benign.
23992   */
23993   sqlcipher3BeginBenignMalloc();
23994   new_ht = (struct _ht *)sqlcipher3Malloc( new_size*sizeof(struct _ht) );
23995   sqlcipher3EndBenignMalloc();
23996
23997   if( new_ht==0 ) return 0;
23998   sqlcipher3_free(pH->ht);
23999   pH->ht = new_ht;
24000   pH->htsize = new_size = sqlcipher3MallocSize(new_ht)/sizeof(struct _ht);
24001   memset(new_ht, 0, new_size*sizeof(struct _ht));
24002   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24003     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
24004     next_elem = elem->next;
24005     insertElement(pH, &new_ht[h], elem);
24006   }
24007   return 1;
24008 }
24009
24010 /* This function (for internal use only) locates an element in an
24011 ** hash table that matches the given key.  The hash for this key has
24012 ** already been computed and is passed as the 4th parameter.
24013 */
24014 static HashElem *findElementGivenHash(
24015   const Hash *pH,     /* The pH to be searched */
24016   const char *pKey,   /* The key we are searching for */
24017   int nKey,           /* Bytes in key (not counting zero terminator) */
24018   unsigned int h      /* The hash for this key. */
24019 ){
24020   HashElem *elem;                /* Used to loop thru the element list */
24021   int count;                     /* Number of elements left to test */
24022
24023   if( pH->ht ){
24024     struct _ht *pEntry = &pH->ht[h];
24025     elem = pEntry->chain;
24026     count = pEntry->count;
24027   }else{
24028     elem = pH->first;
24029     count = pH->count;
24030   }
24031   while( count-- && ALWAYS(elem) ){
24032     if( elem->nKey==nKey && sqlcipher3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
24033       return elem;
24034     }
24035     elem = elem->next;
24036   }
24037   return 0;
24038 }
24039
24040 /* Remove a single entry from the hash table given a pointer to that
24041 ** element and a hash on the element's key.
24042 */
24043 static void removeElementGivenHash(
24044   Hash *pH,         /* The pH containing "elem" */
24045   HashElem* elem,   /* The element to be removed from the pH */
24046   unsigned int h    /* Hash value for the element */
24047 ){
24048   struct _ht *pEntry;
24049   if( elem->prev ){
24050     elem->prev->next = elem->next; 
24051   }else{
24052     pH->first = elem->next;
24053   }
24054   if( elem->next ){
24055     elem->next->prev = elem->prev;
24056   }
24057   if( pH->ht ){
24058     pEntry = &pH->ht[h];
24059     if( pEntry->chain==elem ){
24060       pEntry->chain = elem->next;
24061     }
24062     pEntry->count--;
24063     assert( pEntry->count>=0 );
24064   }
24065   sqlcipher3_free( elem );
24066   pH->count--;
24067   if( pH->count<=0 ){
24068     assert( pH->first==0 );
24069     assert( pH->count==0 );
24070     sqlcipher3HashClear(pH);
24071   }
24072 }
24073
24074 /* Attempt to locate an element of the hash table pH with a key
24075 ** that matches pKey,nKey.  Return the data for this element if it is
24076 ** found, or NULL if there is no match.
24077 */
24078 SQLCIPHER_PRIVATE void *sqlcipher3HashFind(const Hash *pH, const char *pKey, int nKey){
24079   HashElem *elem;    /* The element that matches key */
24080   unsigned int h;    /* A hash on key */
24081
24082   assert( pH!=0 );
24083   assert( pKey!=0 );
24084   assert( nKey>=0 );
24085   if( pH->ht ){
24086     h = strHash(pKey, nKey) % pH->htsize;
24087   }else{
24088     h = 0;
24089   }
24090   elem = findElementGivenHash(pH, pKey, nKey, h);
24091   return elem ? elem->data : 0;
24092 }
24093
24094 /* Insert an element into the hash table pH.  The key is pKey,nKey
24095 ** and the data is "data".
24096 **
24097 ** If no element exists with a matching key, then a new
24098 ** element is created and NULL is returned.
24099 **
24100 ** If another element already exists with the same key, then the
24101 ** new data replaces the old data and the old data is returned.
24102 ** The key is not copied in this instance.  If a malloc fails, then
24103 ** the new data is returned and the hash table is unchanged.
24104 **
24105 ** If the "data" parameter to this function is NULL, then the
24106 ** element corresponding to "key" is removed from the hash table.
24107 */
24108 SQLCIPHER_PRIVATE void *sqlcipher3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
24109   unsigned int h;       /* the hash of the key modulo hash table size */
24110   HashElem *elem;       /* Used to loop thru the element list */
24111   HashElem *new_elem;   /* New element added to the pH */
24112
24113   assert( pH!=0 );
24114   assert( pKey!=0 );
24115   assert( nKey>=0 );
24116   if( pH->htsize ){
24117     h = strHash(pKey, nKey) % pH->htsize;
24118   }else{
24119     h = 0;
24120   }
24121   elem = findElementGivenHash(pH,pKey,nKey,h);
24122   if( elem ){
24123     void *old_data = elem->data;
24124     if( data==0 ){
24125       removeElementGivenHash(pH,elem,h);
24126     }else{
24127       elem->data = data;
24128       elem->pKey = pKey;
24129       assert(nKey==elem->nKey);
24130     }
24131     return old_data;
24132   }
24133   if( data==0 ) return 0;
24134   new_elem = (HashElem*)sqlcipher3Malloc( sizeof(HashElem) );
24135   if( new_elem==0 ) return data;
24136   new_elem->pKey = pKey;
24137   new_elem->nKey = nKey;
24138   new_elem->data = data;
24139   pH->count++;
24140   if( pH->count>=10 && pH->count > 2*pH->htsize ){
24141     if( rehash(pH, pH->count*2) ){
24142       assert( pH->htsize>0 );
24143       h = strHash(pKey, nKey) % pH->htsize;
24144     }
24145   }
24146   if( pH->ht ){
24147     insertElement(pH, &pH->ht[h], new_elem);
24148   }else{
24149     insertElement(pH, 0, new_elem);
24150   }
24151   return 0;
24152 }
24153
24154 /************** End of hash.c ************************************************/
24155 /************** Begin file opcodes.c *****************************************/
24156 /* Automatically generated.  Do not edit */
24157 /* See the mkopcodec.awk script for details. */
24158 #if !defined(SQLCIPHER_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLCIPHER_DEBUG)
24159 SQLCIPHER_PRIVATE const char *sqlcipher3OpcodeName(int i){
24160  static const char *const azName[] = { "?",
24161      /*   1 */ "Goto",
24162      /*   2 */ "Gosub",
24163      /*   3 */ "Return",
24164      /*   4 */ "Yield",
24165      /*   5 */ "HaltIfNull",
24166      /*   6 */ "Halt",
24167      /*   7 */ "Integer",
24168      /*   8 */ "Int64",
24169      /*   9 */ "String",
24170      /*  10 */ "Null",
24171      /*  11 */ "Blob",
24172      /*  12 */ "Variable",
24173      /*  13 */ "Move",
24174      /*  14 */ "Copy",
24175      /*  15 */ "SCopy",
24176      /*  16 */ "ResultRow",
24177      /*  17 */ "CollSeq",
24178      /*  18 */ "Function",
24179      /*  19 */ "Not",
24180      /*  20 */ "AddImm",
24181      /*  21 */ "MustBeInt",
24182      /*  22 */ "RealAffinity",
24183      /*  23 */ "Permutation",
24184      /*  24 */ "Compare",
24185      /*  25 */ "Jump",
24186      /*  26 */ "Once",
24187      /*  27 */ "If",
24188      /*  28 */ "IfNot",
24189      /*  29 */ "Column",
24190      /*  30 */ "Affinity",
24191      /*  31 */ "MakeRecord",
24192      /*  32 */ "Count",
24193      /*  33 */ "Savepoint",
24194      /*  34 */ "AutoCommit",
24195      /*  35 */ "Transaction",
24196      /*  36 */ "ReadCookie",
24197      /*  37 */ "SetCookie",
24198      /*  38 */ "VerifyCookie",
24199      /*  39 */ "OpenRead",
24200      /*  40 */ "OpenWrite",
24201      /*  41 */ "OpenAutoindex",
24202      /*  42 */ "OpenEphemeral",
24203      /*  43 */ "SorterOpen",
24204      /*  44 */ "OpenPseudo",
24205      /*  45 */ "Close",
24206      /*  46 */ "SeekLt",
24207      /*  47 */ "SeekLe",
24208      /*  48 */ "SeekGe",
24209      /*  49 */ "SeekGt",
24210      /*  50 */ "Seek",
24211      /*  51 */ "NotFound",
24212      /*  52 */ "Found",
24213      /*  53 */ "IsUnique",
24214      /*  54 */ "NotExists",
24215      /*  55 */ "Sequence",
24216      /*  56 */ "NewRowid",
24217      /*  57 */ "Insert",
24218      /*  58 */ "InsertInt",
24219      /*  59 */ "Delete",
24220      /*  60 */ "ResetCount",
24221      /*  61 */ "SorterCompare",
24222      /*  62 */ "SorterData",
24223      /*  63 */ "RowKey",
24224      /*  64 */ "RowData",
24225      /*  65 */ "Rowid",
24226      /*  66 */ "NullRow",
24227      /*  67 */ "Last",
24228      /*  68 */ "Or",
24229      /*  69 */ "And",
24230      /*  70 */ "SorterSort",
24231      /*  71 */ "Sort",
24232      /*  72 */ "Rewind",
24233      /*  73 */ "IsNull",
24234      /*  74 */ "NotNull",
24235      /*  75 */ "Ne",
24236      /*  76 */ "Eq",
24237      /*  77 */ "Gt",
24238      /*  78 */ "Le",
24239      /*  79 */ "Lt",
24240      /*  80 */ "Ge",
24241      /*  81 */ "SorterNext",
24242      /*  82 */ "BitAnd",
24243      /*  83 */ "BitOr",
24244      /*  84 */ "ShiftLeft",
24245      /*  85 */ "ShiftRight",
24246      /*  86 */ "Add",
24247      /*  87 */ "Subtract",
24248      /*  88 */ "Multiply",
24249      /*  89 */ "Divide",
24250      /*  90 */ "Remainder",
24251      /*  91 */ "Concat",
24252      /*  92 */ "Prev",
24253      /*  93 */ "BitNot",
24254      /*  94 */ "String8",
24255      /*  95 */ "Next",
24256      /*  96 */ "SorterInsert",
24257      /*  97 */ "IdxInsert",
24258      /*  98 */ "IdxDelete",
24259      /*  99 */ "IdxRowid",
24260      /* 100 */ "IdxLT",
24261      /* 101 */ "IdxGE",
24262      /* 102 */ "Destroy",
24263      /* 103 */ "Clear",
24264      /* 104 */ "CreateIndex",
24265      /* 105 */ "CreateTable",
24266      /* 106 */ "ParseSchema",
24267      /* 107 */ "LoadAnalysis",
24268      /* 108 */ "DropTable",
24269      /* 109 */ "DropIndex",
24270      /* 110 */ "DropTrigger",
24271      /* 111 */ "IntegrityCk",
24272      /* 112 */ "RowSetAdd",
24273      /* 113 */ "RowSetRead",
24274      /* 114 */ "RowSetTest",
24275      /* 115 */ "Program",
24276      /* 116 */ "Param",
24277      /* 117 */ "FkCounter",
24278      /* 118 */ "FkIfZero",
24279      /* 119 */ "MemMax",
24280      /* 120 */ "IfPos",
24281      /* 121 */ "IfNeg",
24282      /* 122 */ "IfZero",
24283      /* 123 */ "AggStep",
24284      /* 124 */ "AggFinal",
24285      /* 125 */ "Checkpoint",
24286      /* 126 */ "JournalMode",
24287      /* 127 */ "Vacuum",
24288      /* 128 */ "IncrVacuum",
24289      /* 129 */ "Expire",
24290      /* 130 */ "Real",
24291      /* 131 */ "TableLock",
24292      /* 132 */ "VBegin",
24293      /* 133 */ "VCreate",
24294      /* 134 */ "VDestroy",
24295      /* 135 */ "VOpen",
24296      /* 136 */ "VFilter",
24297      /* 137 */ "VColumn",
24298      /* 138 */ "VNext",
24299      /* 139 */ "VRename",
24300      /* 140 */ "VUpdate",
24301      /* 141 */ "ToText",
24302      /* 142 */ "ToBlob",
24303      /* 143 */ "ToNumeric",
24304      /* 144 */ "ToInt",
24305      /* 145 */ "ToReal",
24306      /* 146 */ "Pagecount",
24307      /* 147 */ "MaxPgcnt",
24308      /* 148 */ "Trace",
24309      /* 149 */ "Noop",
24310      /* 150 */ "Explain",
24311   };
24312   return azName[i];
24313 }
24314 #endif
24315
24316 /************** End of opcodes.c *********************************************/
24317 /************** Begin file os_os2.c ******************************************/
24318 /*
24319 ** 2006 Feb 14
24320 **
24321 ** The author disclaims copyright to this source code.  In place of
24322 ** a legal notice, here is a blessing:
24323 **
24324 **    May you do good and not evil.
24325 **    May you find forgiveness for yourself and forgive others.
24326 **    May you share freely, never taking more than you give.
24327 **
24328 ******************************************************************************
24329 **
24330 ** This file contains code that is specific to OS/2.
24331 */
24332
24333
24334 #if SQLCIPHER_OS_OS2
24335
24336 /*
24337 ** A Note About Memory Allocation:
24338 **
24339 ** This driver uses malloc()/free() directly rather than going through
24340 ** the SQLite-wrappers sqlcipher3_malloc()/sqlcipher3_free().  Those wrappers
24341 ** are designed for use on embedded systems where memory is scarce and
24342 ** malloc failures happen frequently.  OS/2 does not typically run on
24343 ** embedded systems, and when it does the developers normally have bigger
24344 ** problems to worry about than running out of memory.  So there is not
24345 ** a compelling need to use the wrappers.
24346 **
24347 ** But there is a good reason to not use the wrappers.  If we use the
24348 ** wrappers then we will get simulated malloc() failures within this
24349 ** driver.  And that causes all kinds of problems for our tests.  We
24350 ** could enhance SQLite to deal with simulated malloc failures within
24351 ** the OS driver, but the code to deal with those failure would not
24352 ** be exercised on Linux (which does not need to malloc() in the driver)
24353 ** and so we would have difficulty writing coverage tests for that
24354 ** code.  Better to leave the code out, we think.
24355 **
24356 ** The point of this discussion is as follows:  When creating a new
24357 ** OS layer for an embedded system, if you use this file as an example,
24358 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
24359 ** desktops but not so well in embedded systems.
24360 */
24361
24362 /*
24363 ** Macros used to determine whether or not to use threads.
24364 */
24365 #if defined(SQLCIPHER_THREADSAFE) && SQLCIPHER_THREADSAFE
24366 # define SQLCIPHER_OS2_THREADS 1
24367 #endif
24368
24369 /*
24370 ** Include code that is common to all os_*.c files
24371 */
24372 /************** Include os_common.h in the middle of os_os2.c ****************/
24373 /************** Begin file os_common.h ***************************************/
24374 /*
24375 ** 2004 May 22
24376 **
24377 ** The author disclaims copyright to this source code.  In place of
24378 ** a legal notice, here is a blessing:
24379 **
24380 **    May you do good and not evil.
24381 **    May you find forgiveness for yourself and forgive others.
24382 **    May you share freely, never taking more than you give.
24383 **
24384 ******************************************************************************
24385 **
24386 ** This file contains macros and a little bit of code that is common to
24387 ** all of the platform-specific files (os_*.c) and is #included into those
24388 ** files.
24389 **
24390 ** This file should be #included by the os_*.c files only.  It is not a
24391 ** general purpose header file.
24392 */
24393 #ifndef _OS_COMMON_H_
24394 #define _OS_COMMON_H_
24395
24396 /*
24397 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24398 ** macro to SQLCIPHER_DEBUG and some older makefiles have not yet made the
24399 ** switch.  The following code should catch this problem at compile-time.
24400 */
24401 #ifdef MEMORY_DEBUG
24402 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLCIPHER_DEBUG instead."
24403 #endif
24404
24405 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
24406 # ifndef SQLCIPHER_DEBUG_OS_TRACE
24407 #   define SQLCIPHER_DEBUG_OS_TRACE 0
24408 # endif
24409   int sqlcipher3OSTrace = SQLCIPHER_DEBUG_OS_TRACE;
24410 # define OSTRACE(X)          if( sqlcipher3OSTrace ) sqlcipher3DebugPrintf X
24411 #else
24412 # define OSTRACE(X)
24413 #endif
24414
24415 /*
24416 ** Macros for performance tracing.  Normally turned off.  Only works
24417 ** on i486 hardware.
24418 */
24419 #ifdef SQLCIPHER_PERFORMANCE_TRACE
24420
24421 /* 
24422 ** hwtime.h contains inline assembler code for implementing 
24423 ** high-performance timing routines.
24424 */
24425 /************** Include hwtime.h in the middle of os_common.h ****************/
24426 /************** Begin file hwtime.h ******************************************/
24427 /*
24428 ** 2008 May 27
24429 **
24430 ** The author disclaims copyright to this source code.  In place of
24431 ** a legal notice, here is a blessing:
24432 **
24433 **    May you do good and not evil.
24434 **    May you find forgiveness for yourself and forgive others.
24435 **    May you share freely, never taking more than you give.
24436 **
24437 ******************************************************************************
24438 **
24439 ** This file contains inline asm code for retrieving "high-performance"
24440 ** counters for x86 class CPUs.
24441 */
24442 #ifndef _HWTIME_H_
24443 #define _HWTIME_H_
24444
24445 /*
24446 ** The following routine only works on pentium-class (or newer) processors.
24447 ** It uses the RDTSC opcode to read the cycle count value out of the
24448 ** processor and returns that value.  This can be used for high-res
24449 ** profiling.
24450 */
24451 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24452       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24453
24454   #if defined(__GNUC__)
24455
24456   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
24457      unsigned int lo, hi;
24458      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24459      return (sqlcipher_uint64)hi << 32 | lo;
24460   }
24461
24462   #elif defined(_MSC_VER)
24463
24464   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
24465      __asm {
24466         rdtsc
24467         ret       ; return value at EDX:EAX
24468      }
24469   }
24470
24471   #endif
24472
24473 #elif (defined(__GNUC__) && defined(__x86_64__))
24474
24475   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
24476       unsigned long val;
24477       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24478       return val;
24479   }
24480  
24481 #elif (defined(__GNUC__) && defined(__ppc__))
24482
24483   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
24484       unsigned long long retval;
24485       unsigned long junk;
24486       __asm__ __volatile__ ("\n\
24487           1:      mftbu   %1\n\
24488                   mftb    %L0\n\
24489                   mftbu   %0\n\
24490                   cmpw    %0,%1\n\
24491                   bne     1b"
24492                   : "=r" (retval), "=r" (junk));
24493       return retval;
24494   }
24495
24496 #else
24497
24498   #error Need implementation of sqlcipher3Hwtime() for your platform.
24499
24500   /*
24501   ** To compile without implementing sqlcipher3Hwtime() for your platform,
24502   ** you can remove the above #error and use the following
24503   ** stub function.  You will lose timing support for many
24504   ** of the debugging and testing utilities, but it should at
24505   ** least compile and run.
24506   */
24507 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
24508
24509 #endif
24510
24511 #endif /* !defined(_HWTIME_H_) */
24512
24513 /************** End of hwtime.h **********************************************/
24514 /************** Continuing where we left off in os_common.h ******************/
24515
24516 static sqlcipher_uint64 g_start;
24517 static sqlcipher_uint64 g_elapsed;
24518 #define TIMER_START       g_start=sqlcipher3Hwtime()
24519 #define TIMER_END         g_elapsed=sqlcipher3Hwtime()-g_start
24520 #define TIMER_ELAPSED     g_elapsed
24521 #else
24522 #define TIMER_START
24523 #define TIMER_END
24524 #define TIMER_ELAPSED     ((sqlcipher_uint64)0)
24525 #endif
24526
24527 /*
24528 ** If we compile with the SQLCIPHER_TEST macro set, then the following block
24529 ** of code will give us the ability to simulate a disk I/O error.  This
24530 ** is used for testing the I/O recovery logic.
24531 */
24532 #ifdef SQLCIPHER_TEST
24533 SQLCIPHER_API int sqlcipher3_io_error_hit = 0;            /* Total number of I/O Errors */
24534 SQLCIPHER_API int sqlcipher3_io_error_hardhit = 0;        /* Number of non-benign errors */
24535 SQLCIPHER_API int sqlcipher3_io_error_pending = 0;        /* Count down to first I/O error */
24536 SQLCIPHER_API int sqlcipher3_io_error_persist = 0;        /* True if I/O errors persist */
24537 SQLCIPHER_API int sqlcipher3_io_error_benign = 0;         /* True if errors are benign */
24538 SQLCIPHER_API int sqlcipher3_diskfull_pending = 0;
24539 SQLCIPHER_API int sqlcipher3_diskfull = 0;
24540 #define SimulateIOErrorBenign(X) sqlcipher3_io_error_benign=(X)
24541 #define SimulateIOError(CODE)  \
24542   if( (sqlcipher3_io_error_persist && sqlcipher3_io_error_hit) \
24543        || sqlcipher3_io_error_pending-- == 1 )  \
24544               { local_ioerr(); CODE; }
24545 static void local_ioerr(){
24546   IOTRACE(("IOERR\n"));
24547   sqlcipher3_io_error_hit++;
24548   if( !sqlcipher3_io_error_benign ) sqlcipher3_io_error_hardhit++;
24549 }
24550 #define SimulateDiskfullError(CODE) \
24551    if( sqlcipher3_diskfull_pending ){ \
24552      if( sqlcipher3_diskfull_pending == 1 ){ \
24553        local_ioerr(); \
24554        sqlcipher3_diskfull = 1; \
24555        sqlcipher3_io_error_hit = 1; \
24556        CODE; \
24557      }else{ \
24558        sqlcipher3_diskfull_pending--; \
24559      } \
24560    }
24561 #else
24562 #define SimulateIOErrorBenign(X)
24563 #define SimulateIOError(A)
24564 #define SimulateDiskfullError(A)
24565 #endif
24566
24567 /*
24568 ** When testing, keep a count of the number of open files.
24569 */
24570 #ifdef SQLCIPHER_TEST
24571 SQLCIPHER_API int sqlcipher3_open_file_count = 0;
24572 #define OpenCounter(X)  sqlcipher3_open_file_count+=(X)
24573 #else
24574 #define OpenCounter(X)
24575 #endif
24576
24577 #endif /* !defined(_OS_COMMON_H_) */
24578
24579 /************** End of os_common.h *******************************************/
24580 /************** Continuing where we left off in os_os2.c *********************/
24581
24582 /* Forward references */
24583 typedef struct os2File os2File;         /* The file structure */
24584 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
24585 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
24586
24587 /*
24588 ** The os2File structure is subclass of sqlcipher3_file specific for the OS/2
24589 ** protability layer.
24590 */
24591 struct os2File {
24592   const sqlcipher3_io_methods *pMethod;  /* Always the first entry */
24593   HFILE h;                  /* Handle for accessing the file */
24594   int flags;                /* Flags provided to os2Open() */
24595   int locktype;             /* Type of lock currently held on this file */
24596   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
24597   char *zFullPathCp;        /* Full path name of this file */
24598   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
24599 };
24600
24601 #define LOCK_TIMEOUT 10L /* the default locking timeout */
24602
24603 /*
24604 ** Missing from some versions of the OS/2 toolkit -
24605 ** used to allocate from high memory if possible
24606 */
24607 #ifndef OBJ_ANY
24608 # define OBJ_ANY 0x00000400
24609 #endif
24610
24611 /*****************************************************************************
24612 ** The next group of routines implement the I/O methods specified
24613 ** by the sqlcipher3_io_methods object.
24614 ******************************************************************************/
24615
24616 /*
24617 ** Close a file.
24618 */
24619 static int os2Close( sqlcipher3_file *id ){
24620   APIRET rc;
24621   os2File *pFile = (os2File*)id;
24622
24623   assert( id!=0 );
24624   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
24625
24626   rc = DosClose( pFile->h );
24627
24628   if( pFile->flags & SQLCIPHER_OPEN_DELETEONCLOSE )
24629     DosForceDelete( (PSZ)pFile->zFullPathCp );
24630
24631   free( pFile->zFullPathCp );
24632   pFile->zFullPathCp = NULL;
24633   pFile->locktype = NO_LOCK;
24634   pFile->h = (HFILE)-1;
24635   pFile->flags = 0;
24636
24637   OpenCounter( -1 );
24638   return rc == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR;
24639 }
24640
24641 /*
24642 ** Read data from a file into a buffer.  Return SQLCIPHER_OK if all
24643 ** bytes were read successfully and SQLCIPHER_IOERR if anything goes
24644 ** wrong.
24645 */
24646 static int os2Read(
24647   sqlcipher3_file *id,               /* File to read from */
24648   void *pBuf,                     /* Write content into this buffer */
24649   int amt,                        /* Number of bytes to read */
24650   sqlcipher3_int64 offset            /* Begin reading at this offset */
24651 ){
24652   ULONG fileLocation = 0L;
24653   ULONG got;
24654   os2File *pFile = (os2File*)id;
24655   assert( id!=0 );
24656   SimulateIOError( return SQLCIPHER_IOERR_READ );
24657   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
24658   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
24659     return SQLCIPHER_IOERR;
24660   }
24661   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
24662     return SQLCIPHER_IOERR_READ;
24663   }
24664   if( got == (ULONG)amt )
24665     return SQLCIPHER_OK;
24666   else {
24667     /* Unread portions of the input buffer must be zero-filled */
24668     memset(&((char*)pBuf)[got], 0, amt-got);
24669     return SQLCIPHER_IOERR_SHORT_READ;
24670   }
24671 }
24672
24673 /*
24674 ** Write data from a buffer into a file.  Return SQLCIPHER_OK on success
24675 ** or some other error code on failure.
24676 */
24677 static int os2Write(
24678   sqlcipher3_file *id,               /* File to write into */
24679   const void *pBuf,               /* The bytes to be written */
24680   int amt,                        /* Number of bytes to write */
24681   sqlcipher3_int64 offset            /* Offset into the file to begin writing at */
24682 ){
24683   ULONG fileLocation = 0L;
24684   APIRET rc = NO_ERROR;
24685   ULONG wrote;
24686   os2File *pFile = (os2File*)id;
24687   assert( id!=0 );
24688   SimulateIOError( return SQLCIPHER_IOERR_WRITE );
24689   SimulateDiskfullError( return SQLCIPHER_FULL );
24690   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
24691   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
24692     return SQLCIPHER_IOERR;
24693   }
24694   assert( amt>0 );
24695   while( amt > 0 &&
24696          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
24697          wrote > 0
24698   ){
24699     amt -= wrote;
24700     pBuf = &((char*)pBuf)[wrote];
24701   }
24702
24703   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLCIPHER_FULL : SQLCIPHER_OK;
24704 }
24705
24706 /*
24707 ** Truncate an open file to a specified size
24708 */
24709 static int os2Truncate( sqlcipher3_file *id, i64 nByte ){
24710   APIRET rc;
24711   os2File *pFile = (os2File*)id;
24712   assert( id!=0 );
24713   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
24714   SimulateIOError( return SQLCIPHER_IOERR_TRUNCATE );
24715
24716   /* If the user has configured a chunk-size for this file, truncate the
24717   ** file so that it consists of an integer number of chunks (i.e. the
24718   ** actual file size after the operation may be larger than the requested
24719   ** size).
24720   */
24721   if( pFile->szChunk ){
24722     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
24723   }
24724   
24725   rc = DosSetFileSize( pFile->h, nByte );
24726   return rc == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR_TRUNCATE;
24727 }
24728
24729 #ifdef SQLCIPHER_TEST
24730 /*
24731 ** Count the number of fullsyncs and normal syncs.  This is used to test
24732 ** that syncs and fullsyncs are occuring at the right times.
24733 */
24734 SQLCIPHER_API int sqlcipher3_sync_count = 0;
24735 SQLCIPHER_API int sqlcipher3_fullsync_count = 0;
24736 #endif
24737
24738 /*
24739 ** Make sure all writes to a particular file are committed to disk.
24740 */
24741 static int os2Sync( sqlcipher3_file *id, int flags ){
24742   os2File *pFile = (os2File*)id;
24743   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
24744 #ifdef SQLCIPHER_TEST
24745   if( flags & SQLCIPHER_SYNC_FULL){
24746     sqlcipher3_fullsync_count++;
24747   }
24748   sqlcipher3_sync_count++;
24749 #endif
24750   /* If we compiled with the SQLCIPHER_NO_SYNC flag, then syncing is a
24751   ** no-op
24752   */
24753 #ifdef SQLCIPHER_NO_SYNC
24754   UNUSED_PARAMETER(pFile);
24755   return SQLCIPHER_OK;
24756 #else
24757   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR;
24758 #endif
24759 }
24760
24761 /*
24762 ** Determine the current size of a file in bytes
24763 */
24764 static int os2FileSize( sqlcipher3_file *id, sqlcipher3_int64 *pSize ){
24765   APIRET rc = NO_ERROR;
24766   FILESTATUS3 fsts3FileInfo;
24767   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
24768   assert( id!=0 );
24769   SimulateIOError( return SQLCIPHER_IOERR_FSTAT );
24770   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
24771   if( rc == NO_ERROR ){
24772     *pSize = fsts3FileInfo.cbFile;
24773     return SQLCIPHER_OK;
24774   }else{
24775     return SQLCIPHER_IOERR_FSTAT;
24776   }
24777 }
24778
24779 /*
24780 ** Acquire a reader lock.
24781 */
24782 static int getReadLock( os2File *pFile ){
24783   FILELOCK  LockArea,
24784             UnlockArea;
24785   APIRET res;
24786   memset(&LockArea, 0, sizeof(LockArea));
24787   memset(&UnlockArea, 0, sizeof(UnlockArea));
24788   LockArea.lOffset = SHARED_FIRST;
24789   LockArea.lRange = SHARED_SIZE;
24790   UnlockArea.lOffset = 0L;
24791   UnlockArea.lRange = 0L;
24792   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
24793   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
24794   return res;
24795 }
24796
24797 /*
24798 ** Undo a readlock
24799 */
24800 static int unlockReadLock( os2File *id ){
24801   FILELOCK  LockArea,
24802             UnlockArea;
24803   APIRET res;
24804   memset(&LockArea, 0, sizeof(LockArea));
24805   memset(&UnlockArea, 0, sizeof(UnlockArea));
24806   LockArea.lOffset = 0L;
24807   LockArea.lRange = 0L;
24808   UnlockArea.lOffset = SHARED_FIRST;
24809   UnlockArea.lRange = SHARED_SIZE;
24810   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
24811   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
24812   return res;
24813 }
24814
24815 /*
24816 ** Lock the file with the lock specified by parameter locktype - one
24817 ** of the following:
24818 **
24819 **     (1) SHARED_LOCK
24820 **     (2) RESERVED_LOCK
24821 **     (3) PENDING_LOCK
24822 **     (4) EXCLUSIVE_LOCK
24823 **
24824 ** Sometimes when requesting one lock state, additional lock states
24825 ** are inserted in between.  The locking might fail on one of the later
24826 ** transitions leaving the lock state different from what it started but
24827 ** still short of its goal.  The following chart shows the allowed
24828 ** transitions and the inserted intermediate states:
24829 **
24830 **    UNLOCKED -> SHARED
24831 **    SHARED -> RESERVED
24832 **    SHARED -> (PENDING) -> EXCLUSIVE
24833 **    RESERVED -> (PENDING) -> EXCLUSIVE
24834 **    PENDING -> EXCLUSIVE
24835 **
24836 ** This routine will only increase a lock.  The os2Unlock() routine
24837 ** erases all locks at once and returns us immediately to locking level 0.
24838 ** It is not possible to lower the locking level one step at a time.  You
24839 ** must go straight to locking level 0.
24840 */
24841 static int os2Lock( sqlcipher3_file *id, int locktype ){
24842   int rc = SQLCIPHER_OK;       /* Return code from subroutines */
24843   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
24844   int newLocktype;       /* Set pFile->locktype to this value before exiting */
24845   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
24846   FILELOCK  LockArea,
24847             UnlockArea;
24848   os2File *pFile = (os2File*)id;
24849   memset(&LockArea, 0, sizeof(LockArea));
24850   memset(&UnlockArea, 0, sizeof(UnlockArea));
24851   assert( pFile!=0 );
24852   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
24853
24854   /* If there is already a lock of this type or more restrictive on the
24855   ** os2File, do nothing. Don't use the end_lock: exit path, as
24856   ** sqlcipher3_mutex_enter() hasn't been called yet.
24857   */
24858   if( pFile->locktype>=locktype ){
24859     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
24860     return SQLCIPHER_OK;
24861   }
24862
24863   /* Make sure the locking sequence is correct
24864   */
24865   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24866   assert( locktype!=PENDING_LOCK );
24867   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24868
24869   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
24870   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
24871   ** the PENDING_LOCK byte is temporary.
24872   */
24873   newLocktype = pFile->locktype;
24874   if( pFile->locktype==NO_LOCK
24875       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
24876   ){
24877     LockArea.lOffset = PENDING_BYTE;
24878     LockArea.lRange = 1L;
24879     UnlockArea.lOffset = 0L;
24880     UnlockArea.lRange = 0L;
24881
24882     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
24883     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
24884     if( res == NO_ERROR ){
24885       gotPendingLock = 1;
24886       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
24887     }
24888   }
24889
24890   /* Acquire a shared lock
24891   */
24892   if( locktype==SHARED_LOCK && res == NO_ERROR ){
24893     assert( pFile->locktype==NO_LOCK );
24894     res = getReadLock(pFile);
24895     if( res == NO_ERROR ){
24896       newLocktype = SHARED_LOCK;
24897     }
24898     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
24899   }
24900
24901   /* Acquire a RESERVED lock
24902   */
24903   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
24904     assert( pFile->locktype==SHARED_LOCK );
24905     LockArea.lOffset = RESERVED_BYTE;
24906     LockArea.lRange = 1L;
24907     UnlockArea.lOffset = 0L;
24908     UnlockArea.lRange = 0L;
24909     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24910     if( res == NO_ERROR ){
24911       newLocktype = RESERVED_LOCK;
24912     }
24913     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
24914   }
24915
24916   /* Acquire a PENDING lock
24917   */
24918   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
24919     newLocktype = PENDING_LOCK;
24920     gotPendingLock = 0;
24921     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
24922                pFile->h ));
24923   }
24924
24925   /* Acquire an EXCLUSIVE lock
24926   */
24927   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
24928     assert( pFile->locktype>=SHARED_LOCK );
24929     res = unlockReadLock(pFile);
24930     OSTRACE(( "unreadlock = %d\n", res ));
24931     LockArea.lOffset = SHARED_FIRST;
24932     LockArea.lRange = SHARED_SIZE;
24933     UnlockArea.lOffset = 0L;
24934     UnlockArea.lRange = 0L;
24935     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24936     if( res == NO_ERROR ){
24937       newLocktype = EXCLUSIVE_LOCK;
24938     }else{
24939       OSTRACE(( "OS/2 error-code = %d\n", res ));
24940       getReadLock(pFile);
24941     }
24942     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
24943   }
24944
24945   /* If we are holding a PENDING lock that ought to be released, then
24946   ** release it now.
24947   */
24948   if( gotPendingLock && locktype==SHARED_LOCK ){
24949     int r;
24950     LockArea.lOffset = 0L;
24951     LockArea.lRange = 0L;
24952     UnlockArea.lOffset = PENDING_BYTE;
24953     UnlockArea.lRange = 1L;
24954     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24955     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
24956   }
24957
24958   /* Update the state of the lock has held in the file descriptor then
24959   ** return the appropriate result code.
24960   */
24961   if( res == NO_ERROR ){
24962     rc = SQLCIPHER_OK;
24963   }else{
24964     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
24965               locktype, newLocktype ));
24966     rc = SQLCIPHER_BUSY;
24967   }
24968   pFile->locktype = newLocktype;
24969   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
24970   return rc;
24971 }
24972
24973 /*
24974 ** This routine checks if there is a RESERVED lock held on the specified
24975 ** file by this or any other process. If such a lock is held, return
24976 ** non-zero, otherwise zero.
24977 */
24978 static int os2CheckReservedLock( sqlcipher3_file *id, int *pOut ){
24979   int r = 0;
24980   os2File *pFile = (os2File*)id;
24981   assert( pFile!=0 );
24982   if( pFile->locktype>=RESERVED_LOCK ){
24983     r = 1;
24984     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
24985   }else{
24986     FILELOCK  LockArea,
24987               UnlockArea;
24988     APIRET rc = NO_ERROR;
24989     memset(&LockArea, 0, sizeof(LockArea));
24990     memset(&UnlockArea, 0, sizeof(UnlockArea));
24991     LockArea.lOffset = RESERVED_BYTE;
24992     LockArea.lRange = 1L;
24993     UnlockArea.lOffset = 0L;
24994     UnlockArea.lRange = 0L;
24995     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
24996     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
24997     if( rc == NO_ERROR ){
24998       APIRET rcu = NO_ERROR; /* return code for unlocking */
24999       LockArea.lOffset = 0L;
25000       LockArea.lRange = 0L;
25001       UnlockArea.lOffset = RESERVED_BYTE;
25002       UnlockArea.lRange = 1L;
25003       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25004       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
25005     }
25006     r = !(rc == NO_ERROR);
25007     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
25008   }
25009   *pOut = r;
25010   return SQLCIPHER_OK;
25011 }
25012
25013 /*
25014 ** Lower the locking level on file descriptor id to locktype.  locktype
25015 ** must be either NO_LOCK or SHARED_LOCK.
25016 **
25017 ** If the locking level of the file descriptor is already at or below
25018 ** the requested locking level, this routine is a no-op.
25019 **
25020 ** It is not possible for this routine to fail if the second argument
25021 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
25022 ** might return SQLCIPHER_IOERR;
25023 */
25024 static int os2Unlock( sqlcipher3_file *id, int locktype ){
25025   int type;
25026   os2File *pFile = (os2File*)id;
25027   APIRET rc = SQLCIPHER_OK;
25028   APIRET res = NO_ERROR;
25029   FILELOCK  LockArea,
25030             UnlockArea;
25031   memset(&LockArea, 0, sizeof(LockArea));
25032   memset(&UnlockArea, 0, sizeof(UnlockArea));
25033   assert( pFile!=0 );
25034   assert( locktype<=SHARED_LOCK );
25035   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
25036   type = pFile->locktype;
25037   if( type>=EXCLUSIVE_LOCK ){
25038     LockArea.lOffset = 0L;
25039     LockArea.lRange = 0L;
25040     UnlockArea.lOffset = SHARED_FIRST;
25041     UnlockArea.lRange = SHARED_SIZE;
25042     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25043     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
25044     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
25045       /* This should never happen.  We should always be able to
25046       ** reacquire the read lock */
25047       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
25048       rc = SQLCIPHER_IOERR_UNLOCK;
25049     }
25050   }
25051   if( type>=RESERVED_LOCK ){
25052     LockArea.lOffset = 0L;
25053     LockArea.lRange = 0L;
25054     UnlockArea.lOffset = RESERVED_BYTE;
25055     UnlockArea.lRange = 1L;
25056     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25057     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
25058   }
25059   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
25060     res = unlockReadLock(pFile);
25061     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
25062               pFile->h, type, locktype, res ));
25063   }
25064   if( type>=PENDING_LOCK ){
25065     LockArea.lOffset = 0L;
25066     LockArea.lRange = 0L;
25067     UnlockArea.lOffset = PENDING_BYTE;
25068     UnlockArea.lRange = 1L;
25069     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
25070     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
25071   }
25072   pFile->locktype = locktype;
25073   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
25074   return rc;
25075 }
25076
25077 /*
25078 ** Control and query of the open file handle.
25079 */
25080 static int os2FileControl(sqlcipher3_file *id, int op, void *pArg){
25081   switch( op ){
25082     case SQLCIPHER_FCNTL_LOCKSTATE: {
25083       *(int*)pArg = ((os2File*)id)->locktype;
25084       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
25085                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
25086       return SQLCIPHER_OK;
25087     }
25088     case SQLCIPHER_FCNTL_CHUNK_SIZE: {
25089       ((os2File*)id)->szChunk = *(int*)pArg;
25090       return SQLCIPHER_OK;
25091     }
25092     case SQLCIPHER_FCNTL_SIZE_HINT: {
25093       sqlcipher3_int64 sz = *(sqlcipher3_int64*)pArg;
25094       SimulateIOErrorBenign(1);
25095       os2Truncate(id, sz);
25096       SimulateIOErrorBenign(0);
25097       return SQLCIPHER_OK;
25098     }
25099     case SQLCIPHER_FCNTL_SYNC_OMITTED: {
25100       return SQLCIPHER_OK;
25101     }
25102   }
25103   return SQLCIPHER_NOTFOUND;
25104 }
25105
25106 /*
25107 ** Return the sector size in bytes of the underlying block device for
25108 ** the specified file. This is almost always 512 bytes, but may be
25109 ** larger for some devices.
25110 **
25111 ** SQLite code assumes this function cannot fail. It also assumes that
25112 ** if two files are created in the same file-system directory (i.e.
25113 ** a database and its journal file) that the sector size will be the
25114 ** same for both.
25115 */
25116 static int os2SectorSize(sqlcipher3_file *id){
25117   UNUSED_PARAMETER(id);
25118   return SQLCIPHER_DEFAULT_SECTOR_SIZE;
25119 }
25120
25121 /*
25122 ** Return a vector of device characteristics.
25123 */
25124 static int os2DeviceCharacteristics(sqlcipher3_file *id){
25125   UNUSED_PARAMETER(id);
25126   return SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN;
25127 }
25128
25129
25130 /*
25131 ** Character set conversion objects used by conversion routines.
25132 */
25133 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
25134 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
25135
25136 /*
25137 ** Helper function to initialize the conversion objects from and to UTF-8.
25138 */
25139 static void initUconvObjects( void ){
25140   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
25141     ucUtf8 = NULL;
25142   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
25143     uclCp = NULL;
25144 }
25145
25146 /*
25147 ** Helper function to free the conversion objects from and to UTF-8.
25148 */
25149 static void freeUconvObjects( void ){
25150   if ( ucUtf8 )
25151     UniFreeUconvObject( ucUtf8 );
25152   if ( uclCp )
25153     UniFreeUconvObject( uclCp );
25154   ucUtf8 = NULL;
25155   uclCp = NULL;
25156 }
25157
25158 /*
25159 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
25160 ** The two-step process: first convert the incoming UTF-8 string
25161 ** into UCS-2 and then from UCS-2 to the current codepage.
25162 ** The returned char pointer has to be freed.
25163 */
25164 static char *convertUtf8PathToCp( const char *in ){
25165   UniChar tempPath[CCHMAXPATH];
25166   char *out = (char *)calloc( CCHMAXPATH, 1 );
25167
25168   if( !out )
25169     return NULL;
25170
25171   if( !ucUtf8 || !uclCp )
25172     initUconvObjects();
25173
25174   /* determine string for the conversion of UTF-8 which is CP1208 */
25175   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
25176     return out; /* if conversion fails, return the empty string */
25177
25178   /* conversion for current codepage which can be used for paths */
25179   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
25180
25181   return out;
25182 }
25183
25184 /*
25185 ** Helper function to convert filenames from local codepage to UTF-8.
25186 ** The two-step process: first convert the incoming codepage-specific
25187 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
25188 ** The returned char pointer has to be freed.
25189 **
25190 ** This function is non-static to be able to use this in shell.c and
25191 ** similar applications that take command line arguments.
25192 */
25193 char *convertCpPathToUtf8( const char *in ){
25194   UniChar tempPath[CCHMAXPATH];
25195   char *out = (char *)calloc( CCHMAXPATH, 1 );
25196
25197   if( !out )
25198     return NULL;
25199
25200   if( !ucUtf8 || !uclCp )
25201     initUconvObjects();
25202
25203   /* conversion for current codepage which can be used for paths */
25204   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
25205     return out; /* if conversion fails, return the empty string */
25206
25207   /* determine string for the conversion of UTF-8 which is CP1208 */
25208   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
25209
25210   return out;
25211 }
25212
25213
25214 #ifndef SQLCIPHER_OMIT_WAL
25215
25216 /*
25217 ** Use main database file for interprocess locking. If un-defined
25218 ** a separate file is created for this purpose. The file will be
25219 ** used only to set file locks. There will be no data written to it.
25220 */
25221 #define SQLCIPHER_OS2_NO_WAL_LOCK_FILE     
25222
25223 #if 0
25224 static void _ERR_TRACE( const char *fmt, ... ) {
25225   va_list  ap;
25226   va_start(ap, fmt);
25227   vfprintf(stderr, fmt, ap);
25228   fflush(stderr);
25229 }
25230 #define ERR_TRACE(rc, msg)        \
25231         if( (rc) != SQLCIPHER_OK ) _ERR_TRACE msg;
25232 #else
25233 #define ERR_TRACE(rc, msg)
25234 #endif
25235
25236 /*
25237 ** Helper functions to obtain and relinquish the global mutex. The
25238 ** global mutex is used to protect os2ShmNodeList.
25239 **
25240 ** Function os2ShmMutexHeld() is used to assert() that the global mutex 
25241 ** is held when required. This function is only used as part of assert() 
25242 ** statements. e.g.
25243 **
25244 **   os2ShmEnterMutex()
25245 **     assert( os2ShmMutexHeld() );
25246 **   os2ShmLeaveMutex()
25247 */
25248 static void os2ShmEnterMutex(void){
25249   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
25250 }
25251 static void os2ShmLeaveMutex(void){
25252   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
25253 }
25254 #ifdef SQLCIPHER_DEBUG
25255 static int os2ShmMutexHeld(void) {
25256   return sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
25257 }
25258 int GetCurrentProcessId(void) {
25259   PPIB pib;
25260   DosGetInfoBlocks(NULL, &pib);
25261   return (int)pib->pib_ulpid;
25262 }
25263 #endif
25264
25265 /*
25266 ** Object used to represent a the shared memory area for a single log file.
25267 ** When multiple threads all reference the same log-summary, each thread has
25268 ** its own os2File object, but they all point to a single instance of this 
25269 ** object.  In other words, each log-summary is opened only once per process.
25270 **
25271 ** os2ShmMutexHeld() must be true when creating or destroying
25272 ** this object or while reading or writing the following fields:
25273 **
25274 **      nRef
25275 **      pNext 
25276 **
25277 ** The following fields are read-only after the object is created:
25278 ** 
25279 **      szRegion
25280 **      hLockFile
25281 **      shmBaseName
25282 **
25283 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
25284 ** os2ShmMutexHeld() is true when reading or writing any other field
25285 ** in this structure.
25286 **
25287 */
25288 struct os2ShmNode {
25289   sqlcipher3_mutex *mutex;      /* Mutex to access this object */
25290   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
25291
25292   int szRegion;              /* Size of shared-memory regions */
25293
25294   int nRegion;               /* Size of array apRegion */
25295   void **apRegion;           /* Array of pointers to shared-memory regions */
25296
25297   int nRef;                  /* Number of os2ShmLink objects pointing to this */
25298   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
25299
25300   HFILE hLockFile;           /* File used for inter-process memory locking */
25301   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
25302 };
25303
25304
25305 /*
25306 ** Structure used internally by this VFS to record the state of an
25307 ** open shared memory connection.
25308 **
25309 ** The following fields are initialized when this object is created and
25310 ** are read-only thereafter:
25311 **
25312 **    os2Shm.pShmNode
25313 **    os2Shm.id
25314 **
25315 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
25316 ** while accessing any read/write fields.
25317 */
25318 struct os2ShmLink {
25319   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
25320   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
25321   u32 sharedMask;            /* Mask of shared locks held */
25322   u32 exclMask;              /* Mask of exclusive locks held */
25323 #ifdef SQLCIPHER_DEBUG
25324   u8 id;                     /* Id of this connection with its os2ShmNode */
25325 #endif
25326 };
25327
25328
25329 /*
25330 ** A global list of all os2ShmNode objects.
25331 **
25332 ** The os2ShmMutexHeld() must be true while reading or writing this list.
25333 */
25334 static os2ShmNode *os2ShmNodeList = NULL;
25335
25336 /*
25337 ** Constants used for locking
25338 */
25339 #ifdef  SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25340 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
25341 #else
25342 #define OS2_SHM_BASE   ((22+SQLCIPHER_SHM_NLOCK)*4)        /* first lock byte */
25343 #endif
25344
25345 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLCIPHER_SHM_NLOCK)  /* deadman switch */
25346
25347 /*
25348 ** Apply advisory locks for all n bytes beginning at ofst.
25349 */
25350 #define _SHM_UNLCK  1   /* no lock */
25351 #define _SHM_RDLCK  2   /* shared lock, no wait */
25352 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
25353 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
25354 static int os2ShmSystemLock(
25355   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
25356   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
25357   int ofst,             /* Offset to first byte to be locked/unlocked */
25358   int nByte             /* Number of bytes to lock or unlock */
25359 ){
25360   APIRET rc;
25361   FILELOCK area;
25362   ULONG mode, timeout;
25363
25364   /* Access to the os2ShmNode object is serialized by the caller */
25365   assert( sqlcipher3_mutex_held(pNode->mutex) || pNode->nRef==0 );
25366
25367   mode = 1;     /* shared lock */
25368   timeout = 0;  /* no wait */
25369   area.lOffset = ofst;
25370   area.lRange = nByte;
25371
25372   switch( lockType ) {
25373     case _SHM_WRLCK_WAIT:
25374       timeout = (ULONG)-1;      /* wait forever */
25375     case _SHM_WRLCK:
25376       mode = 0;                 /* exclusive lock */
25377     case _SHM_RDLCK:
25378       rc = DosSetFileLocks(pNode->hLockFile, 
25379                            NULL, &area, timeout, mode);
25380       break;
25381     /* case _SHM_UNLCK: */
25382     default:
25383       rc = DosSetFileLocks(pNode->hLockFile, 
25384                            &area, NULL, 0, 0);
25385       break;
25386   }
25387                           
25388   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
25389            pNode->hLockFile,
25390            rc==SQLCIPHER_OK ? "ok" : "failed",
25391            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
25392            rc));
25393
25394   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
25395
25396   return ( rc == 0 ) ?  SQLCIPHER_OK : SQLCIPHER_BUSY;
25397 }
25398
25399 /*
25400 ** Find an os2ShmNode in global list or allocate a new one, if not found.
25401 **
25402 ** This is not a VFS shared-memory method; it is a utility function called
25403 ** by VFS shared-memory methods.
25404 */
25405 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
25406   os2ShmLink *pLink;
25407   os2ShmNode *pNode;
25408   int cbShmName, rc = SQLCIPHER_OK;
25409   char shmName[CCHMAXPATH + 30];
25410 #ifndef SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25411   ULONG action;
25412 #endif
25413   
25414   /* We need some additional space at the end to append the region number */
25415   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
25416   if( cbShmName >= CCHMAXPATH-8 )
25417     return SQLCIPHER_IOERR_SHMOPEN; 
25418
25419   /* Replace colon in file name to form a valid shared memory name */
25420   shmName[10+1] = '!';
25421
25422   /* Allocate link object (we free it later in case of failure) */
25423   pLink = sqlcipher3_malloc( sizeof(*pLink) );
25424   if( !pLink )
25425     return SQLCIPHER_NOMEM;
25426
25427   /* Access node list */
25428   os2ShmEnterMutex();
25429
25430   /* Find node by it's shared memory base name */
25431   for( pNode = os2ShmNodeList; 
25432        pNode && stricmp(shmName, pNode->shmBaseName) != 0; 
25433        pNode = pNode->pNext )   ;
25434
25435   /* Not found: allocate a new node */
25436   if( !pNode ) {
25437     pNode = sqlcipher3_malloc( sizeof(*pNode) + cbShmName );
25438     if( pNode ) {
25439       memset(pNode, 0, sizeof(*pNode) );
25440       pNode->szRegion = szRegion;
25441       pNode->hLockFile = (HFILE)-1;      
25442       strcpy(pNode->shmBaseName, shmName);
25443
25444 #ifdef SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25445       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
25446 #else
25447       sprintf(shmName, "%s-lck", fd->zFullPathCp);
25448       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL, 
25449                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
25450                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE | 
25451                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
25452                   NULL) != 0 ) {
25453 #endif
25454         sqlcipher3_free(pNode);  
25455         rc = SQLCIPHER_IOERR;
25456       } else {
25457         pNode->mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_FAST);
25458         if( !pNode->mutex ) {
25459           sqlcipher3_free(pNode);  
25460           rc = SQLCIPHER_NOMEM;
25461         }
25462       }   
25463     } else {
25464       rc = SQLCIPHER_NOMEM;
25465     }
25466     
25467     if( rc == SQLCIPHER_OK ) {
25468       pNode->pNext = os2ShmNodeList;
25469       os2ShmNodeList = pNode;
25470     } else {
25471       pNode = NULL;
25472     }
25473   } else if( pNode->szRegion != szRegion ) {
25474     rc = SQLCIPHER_IOERR_SHMSIZE;
25475     pNode = NULL;
25476   }
25477
25478   if( pNode ) {
25479     sqlcipher3_mutex_enter(pNode->mutex);
25480
25481     memset(pLink, 0, sizeof(*pLink));
25482
25483     pLink->pShmNode = pNode;
25484     pLink->pNext = pNode->pFirst;
25485     pNode->pFirst = pLink;
25486     pNode->nRef++;
25487
25488     fd->pShmLink = pLink;
25489
25490     sqlcipher3_mutex_leave(pNode->mutex);
25491     
25492   } else {
25493     /* Error occured. Free our link object. */
25494     sqlcipher3_free(pLink);  
25495   }
25496
25497   os2ShmLeaveMutex();
25498
25499   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))  
25500   
25501   return rc;
25502 }
25503
25504 /*
25505 ** Purge the os2ShmNodeList list of all entries with nRef==0.
25506 **
25507 ** This is not a VFS shared-memory method; it is a utility function called
25508 ** by VFS shared-memory methods.
25509 */
25510 static void os2PurgeShmNodes( int deleteFlag ) {
25511   os2ShmNode *pNode;
25512   os2ShmNode **ppNode;
25513
25514   os2ShmEnterMutex();
25515   
25516   ppNode = &os2ShmNodeList;
25517
25518   while( *ppNode ) {
25519     pNode = *ppNode;
25520
25521     if( pNode->nRef == 0 ) {
25522       *ppNode = pNode->pNext;   
25523      
25524       if( pNode->apRegion ) {
25525         /* Prevent other processes from resizing the shared memory */
25526         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
25527
25528         while( pNode->nRegion-- ) {
25529 #ifdef SQLCIPHER_DEBUG
25530           int rc = 
25531 #endif          
25532           DosFreeMem(pNode->apRegion[pNode->nRegion]);
25533
25534           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
25535                   (int)GetCurrentProcessId(), pNode->nRegion,
25536                   rc == 0 ? "ok" : "failed"));
25537         }
25538
25539         /* Allow other processes to resize the shared memory */
25540         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
25541
25542         sqlcipher3_free(pNode->apRegion);
25543       }  
25544
25545       DosClose(pNode->hLockFile);
25546       
25547 #ifndef SQLCIPHER_OS2_NO_WAL_LOCK_FILE
25548       if( deleteFlag ) {
25549          char fileName[CCHMAXPATH];
25550          /* Skip "\\SHAREMEM\\" */
25551          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
25552          /* restore colon */
25553          fileName[1] = ':';
25554          
25555          DosForceDelete(fileName); 
25556       }
25557 #endif
25558
25559       sqlcipher3_mutex_free(pNode->mutex);
25560
25561       sqlcipher3_free(pNode);
25562       
25563     } else {
25564       ppNode = &pNode->pNext;
25565     }
25566   } 
25567
25568   os2ShmLeaveMutex();
25569 }
25570
25571 /*
25572 ** This function is called to obtain a pointer to region iRegion of the
25573 ** shared-memory associated with the database file id. Shared-memory regions
25574 ** are numbered starting from zero. Each shared-memory region is szRegion
25575 ** bytes in size.
25576 **
25577 ** If an error occurs, an error code is returned and *pp is set to NULL.
25578 **
25579 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
25580 ** region has not been allocated (by any client, including one running in a
25581 ** separate process), then *pp is set to NULL and SQLCIPHER_OK returned. If
25582 ** bExtend is non-zero and the requested shared-memory region has not yet
25583 ** been allocated, it is allocated by this function.
25584 **
25585 ** If the shared-memory region has already been allocated or is allocated by
25586 ** this call as described above, then it is mapped into this processes
25587 ** address space (if it is not already), *pp is set to point to the mapped
25588 ** memory and SQLCIPHER_OK returned.
25589 */
25590 static int os2ShmMap(
25591   sqlcipher3_file *id,               /* Handle open on database file */
25592   int iRegion,                    /* Region to retrieve */
25593   int szRegion,                   /* Size of regions */
25594   int bExtend,                    /* True to extend block if necessary */
25595   void volatile **pp              /* OUT: Mapped memory */
25596 ){
25597   PVOID pvTemp;
25598   void **apRegion;
25599   os2ShmNode *pNode;
25600   int n, rc = SQLCIPHER_OK;
25601   char shmName[CCHMAXPATH];
25602   os2File *pFile = (os2File*)id;
25603   
25604   *pp = NULL;
25605
25606   if( !pFile->pShmLink )
25607     rc = os2OpenSharedMemory( pFile, szRegion );
25608   
25609   if( rc == SQLCIPHER_OK ) {
25610     pNode = pFile->pShmLink->pShmNode ;
25611     
25612     sqlcipher3_mutex_enter(pNode->mutex);
25613     
25614     assert( szRegion==pNode->szRegion );
25615
25616     /* Unmapped region ? */
25617     if( iRegion >= pNode->nRegion ) {
25618       /* Prevent other processes from resizing the shared memory */
25619       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
25620
25621       apRegion = sqlcipher3_realloc(
25622         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
25623
25624       if( apRegion ) {
25625         pNode->apRegion = apRegion;
25626
25627         while( pNode->nRegion <= iRegion ) {
25628           sprintf(shmName, "%s-%u", 
25629                   pNode->shmBaseName, pNode->nRegion);
25630
25631           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName, 
25632                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
25633             if( !bExtend )
25634               break;
25635
25636             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
25637                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR && 
25638                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
25639                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) { 
25640               rc = SQLCIPHER_NOMEM;
25641               break;
25642             }
25643           }
25644
25645           apRegion[pNode->nRegion++] = pvTemp;
25646         }
25647
25648         /* zero out remaining entries */ 
25649         for( n = pNode->nRegion; n <= iRegion; n++ )
25650           pNode->apRegion[n] = NULL;
25651
25652         /* Return this region (maybe zero) */
25653         *pp = pNode->apRegion[iRegion];
25654       } else {
25655         rc = SQLCIPHER_NOMEM;
25656       }
25657
25658       /* Allow other processes to resize the shared memory */
25659       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
25660       
25661     } else {
25662       /* Region has been mapped previously */
25663       *pp = pNode->apRegion[iRegion];
25664     }
25665
25666     sqlcipher3_mutex_leave(pNode->mutex);
25667   } 
25668
25669   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n", 
25670                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
25671           
25672   return rc;
25673 }
25674
25675 /*
25676 ** Close a connection to shared-memory.  Delete the underlying
25677 ** storage if deleteFlag is true.
25678 **
25679 ** If there is no shared memory associated with the connection then this
25680 ** routine is a harmless no-op.
25681 */
25682 static int os2ShmUnmap(
25683   sqlcipher3_file *id,               /* The underlying database file */
25684   int deleteFlag                  /* Delete shared-memory if true */
25685 ){
25686   os2File *pFile = (os2File*)id;
25687   os2ShmLink *pLink = pFile->pShmLink;
25688   
25689   if( pLink ) {
25690     int nRef = -1;
25691     os2ShmLink **ppLink;
25692     os2ShmNode *pNode = pLink->pShmNode;
25693
25694     sqlcipher3_mutex_enter(pNode->mutex);
25695     
25696     for( ppLink = &pNode->pFirst;
25697          *ppLink && *ppLink != pLink;
25698          ppLink = &(*ppLink)->pNext )   ;
25699          
25700     assert(*ppLink);
25701
25702     if( *ppLink ) {
25703       *ppLink = pLink->pNext;
25704       nRef = --pNode->nRef;
25705     } else {
25706       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n", 
25707                     pNode->shmBaseName))
25708     }
25709     
25710     pFile->pShmLink = NULL;
25711     sqlcipher3_free(pLink);
25712
25713     sqlcipher3_mutex_leave(pNode->mutex);
25714     
25715     if( nRef == 0 )
25716       os2PurgeShmNodes( deleteFlag );
25717   }
25718
25719   return SQLCIPHER_OK;
25720 }
25721
25722 /*
25723 ** Change the lock state for a shared-memory segment.
25724 **
25725 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
25726 ** different here than in posix.  In xShmLock(), one can go from unlocked
25727 ** to shared and back or from unlocked to exclusive and back.  But one may
25728 ** not go from shared to exclusive or from exclusive to shared.
25729 */
25730 static int os2ShmLock(
25731   sqlcipher3_file *id,          /* Database file holding the shared memory */
25732   int ofst,                  /* First lock to acquire or release */
25733   int n,                     /* Number of locks to acquire or release */
25734   int flags                  /* What to do with the lock */
25735 ){
25736   u32 mask;                             /* Mask of locks to take or release */
25737   int rc = SQLCIPHER_OK;                   /* Result code */
25738   os2File *pFile = (os2File*)id;
25739   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
25740   os2ShmLink *pX;                       /* For looping over all siblings */
25741   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
25742   
25743   assert( ofst>=0 && ofst+n<=SQLCIPHER_SHM_NLOCK );
25744   assert( n>=1 );
25745   assert( flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED)
25746        || flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE)
25747        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED)
25748        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE) );
25749   assert( n==1 || (flags & SQLCIPHER_SHM_EXCLUSIVE)!=0 );
25750
25751   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
25752   assert( n>1 || mask==(1<<ofst) );
25753
25754
25755   sqlcipher3_mutex_enter(pShmNode->mutex);
25756
25757   if( flags & SQLCIPHER_SHM_UNLOCK ){
25758     u32 allMask = 0; /* Mask of locks held by siblings */
25759
25760     /* See if any siblings hold this same lock */
25761     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25762       if( pX==p ) continue;
25763       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
25764       allMask |= pX->sharedMask;
25765     }
25766
25767     /* Unlock the system-level locks */
25768     if( (mask & allMask)==0 ){
25769       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
25770     }else{
25771       rc = SQLCIPHER_OK;
25772     }
25773
25774     /* Undo the local locks */
25775     if( rc==SQLCIPHER_OK ){
25776       p->exclMask &= ~mask;
25777       p->sharedMask &= ~mask;
25778     } 
25779   }else if( flags & SQLCIPHER_SHM_SHARED ){
25780     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
25781
25782     /* Find out which shared locks are already held by sibling connections.
25783     ** If any sibling already holds an exclusive lock, go ahead and return
25784     ** SQLCIPHER_BUSY.
25785     */
25786     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25787       if( (pX->exclMask & mask)!=0 ){
25788         rc = SQLCIPHER_BUSY;
25789         break;
25790       }
25791       allShared |= pX->sharedMask;
25792     }
25793
25794     /* Get shared locks at the system level, if necessary */
25795     if( rc==SQLCIPHER_OK ){
25796       if( (allShared & mask)==0 ){
25797         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
25798       }else{
25799         rc = SQLCIPHER_OK;
25800       }
25801     }
25802
25803     /* Get the local shared locks */
25804     if( rc==SQLCIPHER_OK ){
25805       p->sharedMask |= mask;
25806     }
25807   }else{
25808     /* Make sure no sibling connections hold locks that will block this
25809     ** lock.  If any do, return SQLCIPHER_BUSY right away.
25810     */
25811     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
25812       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
25813         rc = SQLCIPHER_BUSY;
25814         break;
25815       }
25816     }
25817   
25818     /* Get the exclusive locks at the system level.  Then if successful
25819     ** also mark the local connection as being locked.
25820     */
25821     if( rc==SQLCIPHER_OK ){
25822       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
25823       if( rc==SQLCIPHER_OK ){
25824         assert( (p->sharedMask & mask)==0 );
25825         p->exclMask |= mask;
25826       }
25827     }
25828   }
25829
25830   sqlcipher3_mutex_leave(pShmNode->mutex);
25831   
25832   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
25833            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
25834            rc ? "failed" : "ok"));
25835
25836   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n", 
25837                  ofst, n, flags, rc))
25838                   
25839   return rc; 
25840 }
25841
25842 /*
25843 ** Implement a memory barrier or memory fence on shared memory.
25844 **
25845 ** All loads and stores begun before the barrier must complete before
25846 ** any load or store begun after the barrier.
25847 */
25848 static void os2ShmBarrier(
25849   sqlcipher3_file *id                /* Database file holding the shared memory */
25850 ){
25851   UNUSED_PARAMETER(id);
25852   os2ShmEnterMutex();
25853   os2ShmLeaveMutex();
25854 }
25855
25856 #else
25857 # define os2ShmMap     0
25858 # define os2ShmLock    0
25859 # define os2ShmBarrier 0
25860 # define os2ShmUnmap   0
25861 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
25862
25863
25864 /*
25865 ** This vector defines all the methods that can operate on an
25866 ** sqlcipher3_file for os2.
25867 */
25868 static const sqlcipher3_io_methods os2IoMethod = {
25869   2,                              /* iVersion */
25870   os2Close,                       /* xClose */
25871   os2Read,                        /* xRead */
25872   os2Write,                       /* xWrite */
25873   os2Truncate,                    /* xTruncate */
25874   os2Sync,                        /* xSync */
25875   os2FileSize,                    /* xFileSize */
25876   os2Lock,                        /* xLock */
25877   os2Unlock,                      /* xUnlock */
25878   os2CheckReservedLock,           /* xCheckReservedLock */
25879   os2FileControl,                 /* xFileControl */
25880   os2SectorSize,                  /* xSectorSize */
25881   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
25882   os2ShmMap,                      /* xShmMap */
25883   os2ShmLock,                     /* xShmLock */
25884   os2ShmBarrier,                  /* xShmBarrier */
25885   os2ShmUnmap                     /* xShmUnmap */
25886 };
25887
25888
25889 /***************************************************************************
25890 ** Here ends the I/O methods that form the sqlcipher3_io_methods object.
25891 **
25892 ** The next block of code implements the VFS methods.
25893 ****************************************************************************/
25894
25895 /*
25896 ** Create a temporary file name in zBuf.  zBuf must be big enough to
25897 ** hold at pVfs->mxPathname characters.
25898 */
25899 static int getTempname(int nBuf, char *zBuf ){
25900   static const char zChars[] =
25901     "abcdefghijklmnopqrstuvwxyz"
25902     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25903     "0123456789";
25904   int i, j;
25905   PSZ zTempPathCp;      
25906   char zTempPath[CCHMAXPATH];
25907   ULONG ulDriveNum, ulDriveMap;
25908   
25909   /* It's odd to simulate an io-error here, but really this is just
25910   ** using the io-error infrastructure to test that SQLite handles this
25911   ** function failing. 
25912   */
25913   SimulateIOError( return SQLCIPHER_IOERR );
25914
25915   if( sqlcipher3_temp_directory ) {
25916     sqlcipher3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlcipher3_temp_directory);
25917   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
25918              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
25919              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
25920     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
25921     sqlcipher3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
25922     free( zTempPathUTF );
25923   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
25924     zTempPath[0] = (char)('A' + ulDriveNum - 1);
25925     zTempPath[1] = ':'; 
25926     zTempPath[2] = '\0'; 
25927   } else {
25928     zTempPath[0] = '\0'; 
25929   }
25930   
25931   /* Strip off a trailing slashes or backslashes, otherwise we would get *
25932    * multiple (back)slashes which causes DosOpen() to fail.              *
25933    * Trailing spaces are not allowed, either.                            */
25934   j = sqlcipher3Strlen30(zTempPath);
25935   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' || 
25936                     zTempPath[j-1] == ' ' ) ){
25937     j--;
25938   }
25939   zTempPath[j] = '\0';
25940   
25941   /* We use 20 bytes to randomize the name */
25942   sqlcipher3_snprintf(nBuf-22, zBuf,
25943                    "%s\\"SQLCIPHER_TEMP_FILE_PREFIX, zTempPath);
25944   j = sqlcipher3Strlen30(zBuf);
25945   sqlcipher3_randomness( 20, &zBuf[j] );
25946   for( i = 0; i < 20; i++, j++ ){
25947     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25948   }
25949   zBuf[j] = 0;
25950
25951   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
25952   return SQLCIPHER_OK;
25953 }
25954
25955
25956 /*
25957 ** Turn a relative pathname into a full pathname.  Write the full
25958 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
25959 ** bytes in size.
25960 */
25961 static int os2FullPathname(
25962   sqlcipher3_vfs *pVfs,          /* Pointer to vfs object */
25963   const char *zRelative,      /* Possibly relative input path */
25964   int nFull,                  /* Size of output buffer in bytes */
25965   char *zFull                 /* Output buffer */
25966 ){
25967   char *zRelativeCp = convertUtf8PathToCp( zRelative );
25968   char zFullCp[CCHMAXPATH] = "\0";
25969   char *zFullUTF;
25970   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME, 
25971                                 zFullCp, CCHMAXPATH );
25972   free( zRelativeCp );
25973   zFullUTF = convertCpPathToUtf8( zFullCp );
25974   sqlcipher3_snprintf( nFull, zFull, zFullUTF );
25975   free( zFullUTF );
25976   return rc == NO_ERROR ? SQLCIPHER_OK : SQLCIPHER_IOERR;
25977 }
25978
25979
25980 /*
25981 ** Open a file.
25982 */
25983 static int os2Open(
25984   sqlcipher3_vfs *pVfs,            /* Not used */
25985   const char *zName,            /* Name of the file (UTF-8) */
25986   sqlcipher3_file *id,             /* Write the SQLite file handle here */
25987   int flags,                    /* Open mode flags */
25988   int *pOutFlags                /* Status return flags */
25989 ){
25990   HFILE h;
25991   ULONG ulOpenFlags = 0;
25992   ULONG ulOpenMode = 0;
25993   ULONG ulAction = 0;
25994   ULONG rc;
25995   os2File *pFile = (os2File*)id;
25996   const char *zUtf8Name = zName;
25997   char *zNameCp;
25998   char  zTmpname[CCHMAXPATH];
25999
26000   int isExclusive  = (flags & SQLCIPHER_OPEN_EXCLUSIVE);
26001   int isCreate     = (flags & SQLCIPHER_OPEN_CREATE);
26002   int isReadWrite  = (flags & SQLCIPHER_OPEN_READWRITE);
26003 #ifndef NDEBUG
26004   int isDelete     = (flags & SQLCIPHER_OPEN_DELETEONCLOSE);
26005   int isReadonly   = (flags & SQLCIPHER_OPEN_READONLY);
26006   int eType        = (flags & 0xFFFFFF00);
26007   int isOpenJournal = (isCreate && (
26008         eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
26009      || eType==SQLCIPHER_OPEN_MAIN_JOURNAL 
26010      || eType==SQLCIPHER_OPEN_WAL
26011   ));
26012 #endif
26013
26014   UNUSED_PARAMETER(pVfs);
26015   assert( id!=0 );
26016
26017   /* Check the following statements are true: 
26018   **
26019   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
26020   **   (b) if CREATE is set, then READWRITE must also be set, and
26021   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
26022   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
26023   */
26024   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
26025   assert(isCreate==0 || isReadWrite);
26026   assert(isExclusive==0 || isCreate);
26027   assert(isDelete==0 || isCreate);
26028
26029   /* The main DB, main journal, WAL file and master journal are never 
26030   ** automatically deleted. Nor are they ever temporary files.  */
26031   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_DB );
26032   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_JOURNAL );
26033   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MASTER_JOURNAL );
26034   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_WAL );
26035
26036   /* Assert that the upper layer has set one of the "file-type" flags. */
26037   assert( eType==SQLCIPHER_OPEN_MAIN_DB      || eType==SQLCIPHER_OPEN_TEMP_DB 
26038        || eType==SQLCIPHER_OPEN_MAIN_JOURNAL || eType==SQLCIPHER_OPEN_TEMP_JOURNAL 
26039        || eType==SQLCIPHER_OPEN_SUBJOURNAL   || eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
26040        || eType==SQLCIPHER_OPEN_TRANSIENT_DB || eType==SQLCIPHER_OPEN_WAL
26041   );
26042
26043   memset( pFile, 0, sizeof(*pFile) );
26044   pFile->h = (HFILE)-1;
26045
26046   /* If the second argument to this function is NULL, generate a 
26047   ** temporary file name to use 
26048   */
26049   if( !zUtf8Name ){
26050     assert(isDelete && !isOpenJournal);
26051     rc = getTempname(CCHMAXPATH, zTmpname);
26052     if( rc!=SQLCIPHER_OK ){
26053       return rc;
26054     }
26055     zUtf8Name = zTmpname;
26056   }
26057
26058   if( isReadWrite ){
26059     ulOpenMode |= OPEN_ACCESS_READWRITE;
26060   }else{
26061     ulOpenMode |= OPEN_ACCESS_READONLY;
26062   }
26063
26064   /* Open in random access mode for possibly better speed.  Allow full
26065   ** sharing because file locks will provide exclusive access when needed.
26066   ** The handle should not be inherited by child processes and we don't 
26067   ** want popups from the critical error handler.
26068   */
26069   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE | 
26070                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
26071
26072   /* SQLCIPHER_OPEN_EXCLUSIVE is used to make sure that a new file is 
26073   ** created. SQLite doesn't use it to indicate "exclusive access" 
26074   ** as it is usually understood.
26075   */
26076   if( isExclusive ){
26077     /* Creates a new file, only if it does not already exist. */
26078     /* If the file exists, it fails. */
26079     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
26080   }else if( isCreate ){
26081     /* Open existing file, or create if it doesn't exist */
26082     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
26083   }else{
26084     /* Opens a file, only if it exists. */
26085     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
26086   }
26087
26088   zNameCp = convertUtf8PathToCp( zUtf8Name );
26089   rc = DosOpen( (PSZ)zNameCp,
26090                 &h,
26091                 &ulAction,
26092                 0L,
26093                 FILE_NORMAL,
26094                 ulOpenFlags,
26095                 ulOpenMode,
26096                 (PEAOP2)NULL );
26097   free( zNameCp );
26098
26099   if( rc != NO_ERROR ){
26100     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
26101               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
26102
26103     if( isReadWrite ){
26104       return os2Open( pVfs, zName, id,
26105                       ((flags|SQLCIPHER_OPEN_READONLY)&~(SQLCIPHER_OPEN_CREATE|SQLCIPHER_OPEN_READWRITE)),
26106                       pOutFlags );
26107     }else{
26108       return SQLCIPHER_CANTOPEN;
26109     }
26110   }
26111
26112   if( pOutFlags ){
26113     *pOutFlags = isReadWrite ? SQLCIPHER_OPEN_READWRITE : SQLCIPHER_OPEN_READONLY;
26114   }
26115
26116   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
26117   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
26118   pFile->pMethod = &os2IoMethod;
26119   pFile->flags = flags;
26120   pFile->h = h;
26121
26122   OpenCounter(+1);
26123   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
26124   return SQLCIPHER_OK;
26125 }
26126
26127 /*
26128 ** Delete the named file.
26129 */
26130 static int os2Delete(
26131   sqlcipher3_vfs *pVfs,                     /* Not used on os2 */
26132   const char *zFilename,                 /* Name of file to delete */
26133   int syncDir                            /* Not used on os2 */
26134 ){
26135   APIRET rc;
26136   char *zFilenameCp;
26137   SimulateIOError( return SQLCIPHER_IOERR_DELETE );
26138   zFilenameCp = convertUtf8PathToCp( zFilename );
26139   rc = DosDelete( (PSZ)zFilenameCp );
26140   free( zFilenameCp );
26141   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
26142   return (rc == NO_ERROR ||
26143           rc == ERROR_FILE_NOT_FOUND ||
26144           rc == ERROR_PATH_NOT_FOUND ) ? SQLCIPHER_OK : SQLCIPHER_IOERR_DELETE;
26145 }
26146
26147 /*
26148 ** Check the existance and status of a file.
26149 */
26150 static int os2Access(
26151   sqlcipher3_vfs *pVfs,        /* Not used on os2 */
26152   const char *zFilename,    /* Name of file to check */
26153   int flags,                /* Type of test to make on this file */
26154   int *pOut                 /* Write results here */
26155 ){
26156   APIRET rc;
26157   FILESTATUS3 fsts3ConfigInfo;
26158   char *zFilenameCp;
26159
26160   UNUSED_PARAMETER(pVfs);
26161   SimulateIOError( return SQLCIPHER_IOERR_ACCESS; );
26162   
26163   zFilenameCp = convertUtf8PathToCp( zFilename );
26164   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
26165                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
26166   free( zFilenameCp );
26167   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
26168             fsts3ConfigInfo.attrFile, flags, rc ));
26169
26170   switch( flags ){
26171     case SQLCIPHER_ACCESS_EXISTS:
26172       /* For an SQLCIPHER_ACCESS_EXISTS query, treat a zero-length file
26173       ** as if it does not exist.
26174       */
26175       if( fsts3ConfigInfo.cbFile == 0 ) 
26176         rc = ERROR_FILE_NOT_FOUND;
26177       break;
26178     case SQLCIPHER_ACCESS_READ:
26179       break;
26180     case SQLCIPHER_ACCESS_READWRITE:
26181       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
26182         rc = ERROR_ACCESS_DENIED;
26183       break;
26184     default:
26185       rc = ERROR_FILE_NOT_FOUND;
26186       assert( !"Invalid flags argument" );
26187   }
26188
26189   *pOut = (rc == NO_ERROR);
26190   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
26191
26192   return SQLCIPHER_OK;
26193 }
26194
26195
26196 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
26197 /*
26198 ** Interfaces for opening a shared library, finding entry points
26199 ** within the shared library, and closing the shared library.
26200 */
26201 /*
26202 ** Interfaces for opening a shared library, finding entry points
26203 ** within the shared library, and closing the shared library.
26204 */
26205 static void *os2DlOpen(sqlcipher3_vfs *pVfs, const char *zFilename){
26206   HMODULE hmod;
26207   APIRET rc;
26208   char *zFilenameCp = convertUtf8PathToCp(zFilename);
26209   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
26210   free(zFilenameCp);
26211   return rc != NO_ERROR ? 0 : (void*)hmod;
26212 }
26213 /*
26214 ** A no-op since the error code is returned on the DosLoadModule call.
26215 ** os2Dlopen returns zero if DosLoadModule is not successful.
26216 */
26217 static void os2DlError(sqlcipher3_vfs *pVfs, int nBuf, char *zBufOut){
26218 /* no-op */
26219 }
26220 static void (*os2DlSym(sqlcipher3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
26221   PFN pfn;
26222   APIRET rc;
26223   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
26224   if( rc != NO_ERROR ){
26225     /* if the symbol itself was not found, search again for the same
26226      * symbol with an extra underscore, that might be needed depending
26227      * on the calling convention */
26228     char _zSymbol[256] = "_";
26229     strncat(_zSymbol, zSymbol, 254);
26230     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
26231   }
26232   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
26233 }
26234 static void os2DlClose(sqlcipher3_vfs *pVfs, void *pHandle){
26235   DosFreeModule((HMODULE)pHandle);
26236 }
26237 #else /* if SQLCIPHER_OMIT_LOAD_EXTENSION is defined: */
26238   #define os2DlOpen 0
26239   #define os2DlError 0
26240   #define os2DlSym 0
26241   #define os2DlClose 0
26242 #endif
26243
26244
26245 /*
26246 ** Write up to nBuf bytes of randomness into zBuf.
26247 */
26248 static int os2Randomness(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf ){
26249   int n = 0;
26250 #if defined(SQLCIPHER_TEST)
26251   n = nBuf;
26252   memset(zBuf, 0, nBuf);
26253 #else
26254   int i;                           
26255   PPIB ppib;
26256   PTIB ptib;
26257   DATETIME dt; 
26258   static unsigned c = 0;
26259   /* Ordered by variation probability */
26260   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
26261                             QSV_MAXPRMEM, QSV_MAXSHMEM,
26262                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
26263
26264   /* 8 bytes; timezone and weekday don't increase the randomness much */
26265   if( (int)sizeof(dt)-3 <= nBuf - n ){
26266     c += 0x0100;
26267     DosGetDateTime(&dt);
26268     dt.year = (USHORT)((dt.year - 1900) | c);
26269     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
26270     n += sizeof(dt)-3;
26271   }
26272
26273   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
26274   if( (int)sizeof(ULONG) <= nBuf - n ){
26275     DosGetInfoBlocks(&ptib, &ppib);
26276     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
26277                                  ptib->tib_ptib2->tib2_ultid);
26278     n += sizeof(ULONG);
26279   }
26280
26281   /* Up to 6 * 4 bytes; variables depend on the system state */
26282   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
26283     DosQuerySysInfo(svIdx[i], svIdx[i], 
26284                     (PULONG)&zBuf[n], sizeof(ULONG));
26285     n += sizeof(ULONG);
26286   } 
26287 #endif
26288
26289   return n;
26290 }
26291
26292 /*
26293 ** Sleep for a little while.  Return the amount of time slept.
26294 ** The argument is the number of microseconds we want to sleep.
26295 ** The return value is the number of microseconds of sleep actually
26296 ** requested from the underlying operating system, a number which
26297 ** might be greater than or equal to the argument, but not less
26298 ** than the argument.
26299 */
26300 static int os2Sleep( sqlcipher3_vfs *pVfs, int microsec ){
26301   DosSleep( (microsec/1000) );
26302   return microsec;
26303 }
26304
26305 /*
26306 ** The following variable, if set to a non-zero value, becomes the result
26307 ** returned from sqlcipher3OsCurrentTime().  This is used for testing.
26308 */
26309 #ifdef SQLCIPHER_TEST
26310 SQLCIPHER_API int sqlcipher3_current_time = 0;
26311 #endif
26312
26313 /*
26314 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
26315 ** the current time and date as a Julian Day number times 86_400_000.  In
26316 ** other words, write into *piNow the number of milliseconds since the Julian
26317 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
26318 ** proleptic Gregorian calendar.
26319 **
26320 ** On success, return 0.  Return 1 if the time and date cannot be found.
26321 */
26322 static int os2CurrentTimeInt64(sqlcipher3_vfs *pVfs, sqlcipher3_int64 *piNow){
26323 #ifdef SQLCIPHER_TEST
26324   static const sqlcipher3_int64 unixEpoch = 24405875*(sqlcipher3_int64)8640000;
26325 #endif
26326   int year, month, datepart, timepart;
26327  
26328   DATETIME dt;
26329   DosGetDateTime( &dt );
26330
26331   year = dt.year;
26332   month = dt.month;
26333
26334   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
26335   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
26336   ** Calculate the Julian days
26337   */
26338   datepart = (int)dt.day - 32076 +
26339     1461*(year + 4800 + (month - 14)/12)/4 +
26340     367*(month - 2 - (month - 14)/12*12)/12 -
26341     3*((year + 4900 + (month - 14)/12)/100)/4;
26342
26343   /* Time in milliseconds, hours to noon added */
26344   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
26345     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
26346
26347   *piNow = (sqlcipher3_int64)datepart*86400*1000 + timepart;
26348    
26349 #ifdef SQLCIPHER_TEST
26350   if( sqlcipher3_current_time ){
26351     *piNow = 1000*(sqlcipher3_int64)sqlcipher3_current_time + unixEpoch;
26352   }
26353 #endif
26354
26355   UNUSED_PARAMETER(pVfs);
26356   return 0;
26357 }
26358
26359 /*
26360 ** Find the current time (in Universal Coordinated Time).  Write the
26361 ** current time and date as a Julian Day number into *prNow and
26362 ** return 0.  Return 1 if the time and date cannot be found.
26363 */
26364 static int os2CurrentTime( sqlcipher3_vfs *pVfs, double *prNow ){
26365   int rc;
26366   sqlcipher3_int64 i;
26367   rc = os2CurrentTimeInt64(pVfs, &i);
26368   if( !rc ){
26369     *prNow = i/86400000.0;
26370   }
26371   return rc;
26372 }
26373
26374 /*
26375 ** The idea is that this function works like a combination of
26376 ** GetLastError() and FormatMessage() on windows (or errno and
26377 ** strerror_r() on unix). After an error is returned by an OS
26378 ** function, SQLite calls this function with zBuf pointing to
26379 ** a buffer of nBuf bytes. The OS layer should populate the
26380 ** buffer with a nul-terminated UTF-8 encoded error message
26381 ** describing the last IO error to have occurred within the calling
26382 ** thread.
26383 **
26384 ** If the error message is too large for the supplied buffer,
26385 ** it should be truncated. The return value of xGetLastError
26386 ** is zero if the error message fits in the buffer, or non-zero
26387 ** otherwise (if the message was truncated). If non-zero is returned,
26388 ** then it is not necessary to include the nul-terminator character
26389 ** in the output buffer.
26390 **
26391 ** Not supplying an error message will have no adverse effect
26392 ** on SQLite. It is fine to have an implementation that never
26393 ** returns an error message:
26394 **
26395 **   int xGetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
26396 **     assert(zBuf[0]=='\0');
26397 **     return 0;
26398 **   }
26399 **
26400 ** However if an error message is supplied, it will be incorporated
26401 ** by sqlcipher into the error message available to the user using
26402 ** sqlcipher3_errmsg(), possibly making IO errors easier to debug.
26403 */
26404 static int os2GetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
26405   assert(zBuf[0]=='\0');
26406   return 0;
26407 }
26408
26409 /*
26410 ** Initialize and deinitialize the operating system interface.
26411 */
26412 SQLCIPHER_API int sqlcipher3_os_init(void){
26413   static sqlcipher3_vfs os2Vfs = {
26414     3,                 /* iVersion */
26415     sizeof(os2File),   /* szOsFile */
26416     CCHMAXPATH,        /* mxPathname */
26417     0,                 /* pNext */
26418     "os2",             /* zName */
26419     0,                 /* pAppData */
26420
26421     os2Open,           /* xOpen */
26422     os2Delete,         /* xDelete */
26423     os2Access,         /* xAccess */
26424     os2FullPathname,   /* xFullPathname */
26425     os2DlOpen,         /* xDlOpen */
26426     os2DlError,        /* xDlError */
26427     os2DlSym,          /* xDlSym */
26428     os2DlClose,        /* xDlClose */
26429     os2Randomness,     /* xRandomness */
26430     os2Sleep,          /* xSleep */
26431     os2CurrentTime,    /* xCurrentTime */
26432     os2GetLastError,   /* xGetLastError */
26433     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
26434     0,                 /* xSetSystemCall */
26435     0,                 /* xGetSystemCall */
26436     0                  /* xNextSystemCall */
26437   };
26438   sqlcipher3_vfs_register(&os2Vfs, 1);
26439   initUconvObjects();
26440 /*  sqlcipher3OSTrace = 1; */
26441   return SQLCIPHER_OK;
26442 }
26443 SQLCIPHER_API int sqlcipher3_os_end(void){
26444   freeUconvObjects();
26445   return SQLCIPHER_OK;
26446 }
26447
26448 #endif /* SQLCIPHER_OS_OS2 */
26449
26450 /************** End of os_os2.c **********************************************/
26451 /************** Begin file os_unix.c *****************************************/
26452 /*
26453 ** 2004 May 22
26454 **
26455 ** The author disclaims copyright to this source code.  In place of
26456 ** a legal notice, here is a blessing:
26457 **
26458 **    May you do good and not evil.
26459 **    May you find forgiveness for yourself and forgive others.
26460 **    May you share freely, never taking more than you give.
26461 **
26462 ******************************************************************************
26463 **
26464 ** This file contains the VFS implementation for unix-like operating systems
26465 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
26466 **
26467 ** There are actually several different VFS implementations in this file.
26468 ** The differences are in the way that file locking is done.  The default
26469 ** implementation uses Posix Advisory Locks.  Alternative implementations
26470 ** use flock(), dot-files, various proprietary locking schemas, or simply
26471 ** skip locking all together.
26472 **
26473 ** This source file is organized into divisions where the logic for various
26474 ** subfunctions is contained within the appropriate division.  PLEASE
26475 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
26476 ** in the correct division and should be clearly labeled.
26477 **
26478 ** The layout of divisions is as follows:
26479 **
26480 **   *  General-purpose declarations and utility functions.
26481 **   *  Unique file ID logic used by VxWorks.
26482 **   *  Various locking primitive implementations (all except proxy locking):
26483 **      + for Posix Advisory Locks
26484 **      + for no-op locks
26485 **      + for dot-file locks
26486 **      + for flock() locking
26487 **      + for named semaphore locks (VxWorks only)
26488 **      + for AFP filesystem locks (MacOSX only)
26489 **   *  sqlcipher3_file methods not associated with locking.
26490 **   *  Definitions of sqlcipher3_io_methods objects for all locking
26491 **      methods plus "finder" functions for each locking method.
26492 **   *  sqlcipher3_vfs method implementations.
26493 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
26494 **   *  Definitions of sqlcipher3_vfs objects for all locking methods
26495 **      plus implementations of sqlcipher3_os_init() and sqlcipher3_os_end().
26496 */
26497 #if SQLCIPHER_OS_UNIX              /* This file is used on unix only */
26498
26499 /*
26500 ** There are various methods for file locking used for concurrency
26501 ** control:
26502 **
26503 **   1. POSIX locking (the default),
26504 **   2. No locking,
26505 **   3. Dot-file locking,
26506 **   4. flock() locking,
26507 **   5. AFP locking (OSX only),
26508 **   6. Named POSIX semaphores (VXWorks only),
26509 **   7. proxy locking. (OSX only)
26510 **
26511 ** Styles 4, 5, and 7 are only available of SQLCIPHER_ENABLE_LOCKING_STYLE
26512 ** is defined to 1.  The SQLCIPHER_ENABLE_LOCKING_STYLE also enables automatic
26513 ** selection of the appropriate locking style based on the filesystem
26514 ** where the database is located.  
26515 */
26516 #if !defined(SQLCIPHER_ENABLE_LOCKING_STYLE)
26517 #  if defined(__APPLE__)
26518 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 1
26519 #  else
26520 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 0
26521 #  endif
26522 #endif
26523
26524 /*
26525 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
26526 ** vxworks, or 0 otherwise.
26527 */
26528 #ifndef OS_VXWORKS
26529 #  if defined(__RTP__) || defined(_WRS_KERNEL)
26530 #    define OS_VXWORKS 1
26531 #  else
26532 #    define OS_VXWORKS 0
26533 #  endif
26534 #endif
26535
26536 /*
26537 ** These #defines should enable >2GB file support on Posix if the
26538 ** underlying operating system supports it.  If the OS lacks
26539 ** large file support, these should be no-ops.
26540 **
26541 ** Large file support can be disabled using the -DSQLCIPHER_DISABLE_LFS switch
26542 ** on the compiler command line.  This is necessary if you are compiling
26543 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
26544 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
26545 ** without this option, LFS is enable.  But LFS does not exist in the kernel
26546 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
26547 ** portability you should omit LFS.
26548 **
26549 ** The previous paragraph was written in 2005.  (This paragraph is written
26550 ** on 2008-11-28.) These days, all Linux kernels support large files, so
26551 ** you should probably leave LFS enabled.  But some embedded platforms might
26552 ** lack LFS in which case the SQLCIPHER_DISABLE_LFS macro might still be useful.
26553 */
26554 #ifndef SQLCIPHER_DISABLE_LFS
26555 # define _LARGE_FILE       1
26556 # ifndef _FILE_OFFSET_BITS
26557 #   define _FILE_OFFSET_BITS 64
26558 # endif
26559 # define _LARGEFILE_SOURCE 1
26560 #endif
26561
26562 /*
26563 ** standard include files.
26564 */
26565 #include <sys/types.h>
26566 #include <sys/stat.h>
26567 #include <fcntl.h>
26568 #include <unistd.h>
26569 /* #include <time.h> */
26570 #include <sys/time.h>
26571 #include <errno.h>
26572 #ifndef SQLCIPHER_OMIT_WAL
26573 /* #include <sys/mman.h> */
26574 #endif
26575
26576 #if SQLCIPHER_ENABLE_LOCKING_STYLE
26577 # include <sys/ioctl.h>
26578 # if OS_VXWORKS
26579 #  include <semaphore.h>
26580 #  include <limits.h>
26581 # else
26582 #  include <sys/file.h>
26583 #  include <sys/param.h>
26584 # endif
26585 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE */
26586
26587 #if defined(__APPLE__) || (SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
26588 # include <sys/mount.h>
26589 #endif
26590
26591 #ifdef HAVE_UTIME
26592 # include <utime.h>
26593 #endif
26594
26595 /*
26596 ** Allowed values of unixFile.fsFlags
26597 */
26598 #define SQLCIPHER_FSFLAGS_IS_MSDOS     0x1
26599
26600 /*
26601 ** If we are to be thread-safe, include the pthreads header and define
26602 ** the SQLCIPHER_UNIX_THREADS macro.
26603 */
26604 #if SQLCIPHER_THREADSAFE
26605 /* # include <pthread.h> */
26606 # define SQLCIPHER_UNIX_THREADS 1
26607 #endif
26608
26609 /*
26610 ** Default permissions when creating a new file
26611 */
26612 #ifndef SQLCIPHER_DEFAULT_FILE_PERMISSIONS
26613 # define SQLCIPHER_DEFAULT_FILE_PERMISSIONS 0644
26614 #endif
26615
26616 /*
26617  ** Default permissions when creating auto proxy dir
26618  */
26619 #ifndef SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS
26620 # define SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS 0755
26621 #endif
26622
26623 /*
26624 ** Maximum supported path-length.
26625 */
26626 #define MAX_PATHNAME 512
26627
26628 /*
26629 ** Only set the lastErrno if the error code is a real error and not 
26630 ** a normal expected return code of SQLCIPHER_BUSY or SQLCIPHER_OK
26631 */
26632 #define IS_LOCK_ERROR(x)  ((x != SQLCIPHER_OK) && (x != SQLCIPHER_BUSY))
26633
26634 /* Forward references */
26635 typedef struct unixShm unixShm;               /* Connection shared memory */
26636 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
26637 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
26638 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
26639
26640 /*
26641 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
26642 ** cannot be closed immediately. In these cases, instances of the following
26643 ** structure are used to store the file descriptor while waiting for an
26644 ** opportunity to either close or reuse it.
26645 */
26646 struct UnixUnusedFd {
26647   int fd;                   /* File descriptor to close */
26648   int flags;                /* Flags this file descriptor was opened with */
26649   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
26650 };
26651
26652 /*
26653 ** The unixFile structure is subclass of sqlcipher3_file specific to the unix
26654 ** VFS implementations.
26655 */
26656 typedef struct unixFile unixFile;
26657 struct unixFile {
26658   sqlcipher3_io_methods const *pMethod;  /* Always the first entry */
26659   unixInodeInfo *pInode;              /* Info about locks on this inode */
26660   int h;                              /* The file descriptor */
26661   unsigned char eFileLock;            /* The type of lock held on this fd */
26662   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
26663   int lastErrno;                      /* The unix errno from last I/O error */
26664   void *lockingContext;               /* Locking style specific state */
26665   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
26666   const char *zPath;                  /* Name of the file */
26667   unixShm *pShm;                      /* Shared memory segment information */
26668   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
26669 #if SQLCIPHER_ENABLE_LOCKING_STYLE
26670   int openFlags;                      /* The flags specified at open() */
26671 #endif
26672 #if SQLCIPHER_ENABLE_LOCKING_STYLE || defined(__APPLE__)
26673   unsigned fsFlags;                   /* cached details from statfs() */
26674 #endif
26675 #if OS_VXWORKS
26676   int isDelete;                       /* Delete on close if true */
26677   struct vxworksFileId *pId;          /* Unique file ID */
26678 #endif
26679 #ifndef NDEBUG
26680   /* The next group of variables are used to track whether or not the
26681   ** transaction counter in bytes 24-27 of database files are updated
26682   ** whenever any part of the database changes.  An assertion fault will
26683   ** occur if a file is updated without also updating the transaction
26684   ** counter.  This test is made to avoid new problems similar to the
26685   ** one described by ticket #3584. 
26686   */
26687   unsigned char transCntrChng;   /* True if the transaction counter changed */
26688   unsigned char dbUpdate;        /* True if any part of database file changed */
26689   unsigned char inNormalWrite;   /* True if in a normal write operation */
26690 #endif
26691 #ifdef SQLCIPHER_TEST
26692   /* In test mode, increase the size of this structure a bit so that 
26693   ** it is larger than the struct CrashFile defined in test6.c.
26694   */
26695   char aPadding[32];
26696 #endif
26697 };
26698
26699 /*
26700 ** Allowed values for the unixFile.ctrlFlags bitmask:
26701 */
26702 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
26703 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
26704 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
26705 #ifndef SQLCIPHER_DISABLE_DIRSYNC
26706 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
26707 #else
26708 # define UNIXFILE_DIRSYNC    0x00
26709 #endif
26710
26711 /*
26712 ** Include code that is common to all os_*.c files
26713 */
26714 /************** Include os_common.h in the middle of os_unix.c ***************/
26715 /************** Begin file os_common.h ***************************************/
26716 /*
26717 ** 2004 May 22
26718 **
26719 ** The author disclaims copyright to this source code.  In place of
26720 ** a legal notice, here is a blessing:
26721 **
26722 **    May you do good and not evil.
26723 **    May you find forgiveness for yourself and forgive others.
26724 **    May you share freely, never taking more than you give.
26725 **
26726 ******************************************************************************
26727 **
26728 ** This file contains macros and a little bit of code that is common to
26729 ** all of the platform-specific files (os_*.c) and is #included into those
26730 ** files.
26731 **
26732 ** This file should be #included by the os_*.c files only.  It is not a
26733 ** general purpose header file.
26734 */
26735 #ifndef _OS_COMMON_H_
26736 #define _OS_COMMON_H_
26737
26738 /*
26739 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
26740 ** macro to SQLCIPHER_DEBUG and some older makefiles have not yet made the
26741 ** switch.  The following code should catch this problem at compile-time.
26742 */
26743 #ifdef MEMORY_DEBUG
26744 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLCIPHER_DEBUG instead."
26745 #endif
26746
26747 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
26748 # ifndef SQLCIPHER_DEBUG_OS_TRACE
26749 #   define SQLCIPHER_DEBUG_OS_TRACE 0
26750 # endif
26751   int sqlcipher3OSTrace = SQLCIPHER_DEBUG_OS_TRACE;
26752 # define OSTRACE(X)          if( sqlcipher3OSTrace ) sqlcipher3DebugPrintf X
26753 #else
26754 # define OSTRACE(X)
26755 #endif
26756
26757 /*
26758 ** Macros for performance tracing.  Normally turned off.  Only works
26759 ** on i486 hardware.
26760 */
26761 #ifdef SQLCIPHER_PERFORMANCE_TRACE
26762
26763 /* 
26764 ** hwtime.h contains inline assembler code for implementing 
26765 ** high-performance timing routines.
26766 */
26767 /************** Include hwtime.h in the middle of os_common.h ****************/
26768 /************** Begin file hwtime.h ******************************************/
26769 /*
26770 ** 2008 May 27
26771 **
26772 ** The author disclaims copyright to this source code.  In place of
26773 ** a legal notice, here is a blessing:
26774 **
26775 **    May you do good and not evil.
26776 **    May you find forgiveness for yourself and forgive others.
26777 **    May you share freely, never taking more than you give.
26778 **
26779 ******************************************************************************
26780 **
26781 ** This file contains inline asm code for retrieving "high-performance"
26782 ** counters for x86 class CPUs.
26783 */
26784 #ifndef _HWTIME_H_
26785 #define _HWTIME_H_
26786
26787 /*
26788 ** The following routine only works on pentium-class (or newer) processors.
26789 ** It uses the RDTSC opcode to read the cycle count value out of the
26790 ** processor and returns that value.  This can be used for high-res
26791 ** profiling.
26792 */
26793 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
26794       (defined(i386) || defined(__i386__) || defined(_M_IX86))
26795
26796   #if defined(__GNUC__)
26797
26798   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
26799      unsigned int lo, hi;
26800      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
26801      return (sqlcipher_uint64)hi << 32 | lo;
26802   }
26803
26804   #elif defined(_MSC_VER)
26805
26806   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
26807      __asm {
26808         rdtsc
26809         ret       ; return value at EDX:EAX
26810      }
26811   }
26812
26813   #endif
26814
26815 #elif (defined(__GNUC__) && defined(__x86_64__))
26816
26817   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
26818       unsigned long val;
26819       __asm__ __volatile__ ("rdtsc" : "=A" (val));
26820       return val;
26821   }
26822  
26823 #elif (defined(__GNUC__) && defined(__ppc__))
26824
26825   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
26826       unsigned long long retval;
26827       unsigned long junk;
26828       __asm__ __volatile__ ("\n\
26829           1:      mftbu   %1\n\
26830                   mftb    %L0\n\
26831                   mftbu   %0\n\
26832                   cmpw    %0,%1\n\
26833                   bne     1b"
26834                   : "=r" (retval), "=r" (junk));
26835       return retval;
26836   }
26837
26838 #else
26839
26840   #error Need implementation of sqlcipher3Hwtime() for your platform.
26841
26842   /*
26843   ** To compile without implementing sqlcipher3Hwtime() for your platform,
26844   ** you can remove the above #error and use the following
26845   ** stub function.  You will lose timing support for many
26846   ** of the debugging and testing utilities, but it should at
26847   ** least compile and run.
26848   */
26849 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
26850
26851 #endif
26852
26853 #endif /* !defined(_HWTIME_H_) */
26854
26855 /************** End of hwtime.h **********************************************/
26856 /************** Continuing where we left off in os_common.h ******************/
26857
26858 static sqlcipher_uint64 g_start;
26859 static sqlcipher_uint64 g_elapsed;
26860 #define TIMER_START       g_start=sqlcipher3Hwtime()
26861 #define TIMER_END         g_elapsed=sqlcipher3Hwtime()-g_start
26862 #define TIMER_ELAPSED     g_elapsed
26863 #else
26864 #define TIMER_START
26865 #define TIMER_END
26866 #define TIMER_ELAPSED     ((sqlcipher_uint64)0)
26867 #endif
26868
26869 /*
26870 ** If we compile with the SQLCIPHER_TEST macro set, then the following block
26871 ** of code will give us the ability to simulate a disk I/O error.  This
26872 ** is used for testing the I/O recovery logic.
26873 */
26874 #ifdef SQLCIPHER_TEST
26875 SQLCIPHER_API int sqlcipher3_io_error_hit = 0;            /* Total number of I/O Errors */
26876 SQLCIPHER_API int sqlcipher3_io_error_hardhit = 0;        /* Number of non-benign errors */
26877 SQLCIPHER_API int sqlcipher3_io_error_pending = 0;        /* Count down to first I/O error */
26878 SQLCIPHER_API int sqlcipher3_io_error_persist = 0;        /* True if I/O errors persist */
26879 SQLCIPHER_API int sqlcipher3_io_error_benign = 0;         /* True if errors are benign */
26880 SQLCIPHER_API int sqlcipher3_diskfull_pending = 0;
26881 SQLCIPHER_API int sqlcipher3_diskfull = 0;
26882 #define SimulateIOErrorBenign(X) sqlcipher3_io_error_benign=(X)
26883 #define SimulateIOError(CODE)  \
26884   if( (sqlcipher3_io_error_persist && sqlcipher3_io_error_hit) \
26885        || sqlcipher3_io_error_pending-- == 1 )  \
26886               { local_ioerr(); CODE; }
26887 static void local_ioerr(){
26888   IOTRACE(("IOERR\n"));
26889   sqlcipher3_io_error_hit++;
26890   if( !sqlcipher3_io_error_benign ) sqlcipher3_io_error_hardhit++;
26891 }
26892 #define SimulateDiskfullError(CODE) \
26893    if( sqlcipher3_diskfull_pending ){ \
26894      if( sqlcipher3_diskfull_pending == 1 ){ \
26895        local_ioerr(); \
26896        sqlcipher3_diskfull = 1; \
26897        sqlcipher3_io_error_hit = 1; \
26898        CODE; \
26899      }else{ \
26900        sqlcipher3_diskfull_pending--; \
26901      } \
26902    }
26903 #else
26904 #define SimulateIOErrorBenign(X)
26905 #define SimulateIOError(A)
26906 #define SimulateDiskfullError(A)
26907 #endif
26908
26909 /*
26910 ** When testing, keep a count of the number of open files.
26911 */
26912 #ifdef SQLCIPHER_TEST
26913 SQLCIPHER_API int sqlcipher3_open_file_count = 0;
26914 #define OpenCounter(X)  sqlcipher3_open_file_count+=(X)
26915 #else
26916 #define OpenCounter(X)
26917 #endif
26918
26919 #endif /* !defined(_OS_COMMON_H_) */
26920
26921 /************** End of os_common.h *******************************************/
26922 /************** Continuing where we left off in os_unix.c ********************/
26923
26924 /*
26925 ** Define various macros that are missing from some systems.
26926 */
26927 #ifndef O_LARGEFILE
26928 # define O_LARGEFILE 0
26929 #endif
26930 #ifdef SQLCIPHER_DISABLE_LFS
26931 # undef O_LARGEFILE
26932 # define O_LARGEFILE 0
26933 #endif
26934 #ifndef O_NOFOLLOW
26935 # define O_NOFOLLOW 0
26936 #endif
26937 #ifndef O_BINARY
26938 # define O_BINARY 0
26939 #endif
26940
26941 /*
26942 ** The threadid macro resolves to the thread-id or to 0.  Used for
26943 ** testing and debugging only.
26944 */
26945 #if SQLCIPHER_THREADSAFE
26946 #define threadid pthread_self()
26947 #else
26948 #define threadid 0
26949 #endif
26950
26951 /*
26952 ** Different Unix systems declare open() in different ways.  Same use
26953 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
26954 ** The difference is important when using a pointer to the function.
26955 **
26956 ** The safest way to deal with the problem is to always use this wrapper
26957 ** which always has the same well-defined interface.
26958 */
26959 static int posixOpen(const char *zFile, int flags, int mode){
26960   return open(zFile, flags, mode);
26961 }
26962
26963 /* Forward reference */
26964 static int openDirectory(const char*, int*);
26965
26966 /*
26967 ** Many system calls are accessed through pointer-to-functions so that
26968 ** they may be overridden at runtime to facilitate fault injection during
26969 ** testing and sandboxing.  The following array holds the names and pointers
26970 ** to all overrideable system calls.
26971 */
26972 static struct unix_syscall {
26973   const char *zName;            /* Name of the sytem call */
26974   sqlcipher3_syscall_ptr pCurrent; /* Current value of the system call */
26975   sqlcipher3_syscall_ptr pDefault; /* Default value */
26976 } aSyscall[] = {
26977   { "open",         (sqlcipher3_syscall_ptr)posixOpen,  0  },
26978 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
26979
26980   { "close",        (sqlcipher3_syscall_ptr)close,      0  },
26981 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
26982
26983   { "access",       (sqlcipher3_syscall_ptr)access,     0  },
26984 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
26985
26986   { "getcwd",       (sqlcipher3_syscall_ptr)getcwd,     0  },
26987 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
26988
26989   { "stat",         (sqlcipher3_syscall_ptr)stat,       0  },
26990 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
26991
26992 /*
26993 ** The DJGPP compiler environment looks mostly like Unix, but it
26994 ** lacks the fcntl() system call.  So redefine fcntl() to be something
26995 ** that always succeeds.  This means that locking does not occur under
26996 ** DJGPP.  But it is DOS - what did you expect?
26997 */
26998 #ifdef __DJGPP__
26999   { "fstat",        0,                 0  },
27000 #define osFstat(a,b,c)    0
27001 #else     
27002   { "fstat",        (sqlcipher3_syscall_ptr)fstat,      0  },
27003 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
27004 #endif
27005
27006   { "ftruncate",    (sqlcipher3_syscall_ptr)ftruncate,  0  },
27007 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
27008
27009   { "fcntl",        (sqlcipher3_syscall_ptr)fcntl,      0  },
27010 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
27011
27012   { "read",         (sqlcipher3_syscall_ptr)read,       0  },
27013 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
27014
27015 #if defined(USE_PREAD) || SQLCIPHER_ENABLE_LOCKING_STYLE
27016   { "pread",        (sqlcipher3_syscall_ptr)pread,      0  },
27017 #else
27018   { "pread",        (sqlcipher3_syscall_ptr)0,          0  },
27019 #endif
27020 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
27021
27022 #if defined(USE_PREAD64)
27023   { "pread64",      (sqlcipher3_syscall_ptr)pread64,    0  },
27024 #else
27025   { "pread64",      (sqlcipher3_syscall_ptr)0,          0  },
27026 #endif
27027 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
27028
27029   { "write",        (sqlcipher3_syscall_ptr)write,      0  },
27030 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
27031
27032 #if defined(USE_PREAD) || SQLCIPHER_ENABLE_LOCKING_STYLE
27033   { "pwrite",       (sqlcipher3_syscall_ptr)pwrite,     0  },
27034 #else
27035   { "pwrite",       (sqlcipher3_syscall_ptr)0,          0  },
27036 #endif
27037 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
27038                     aSyscall[12].pCurrent)
27039
27040 #if defined(USE_PREAD64)
27041   { "pwrite64",     (sqlcipher3_syscall_ptr)pwrite64,   0  },
27042 #else
27043   { "pwrite64",     (sqlcipher3_syscall_ptr)0,          0  },
27044 #endif
27045 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
27046                     aSyscall[13].pCurrent)
27047
27048 #if SQLCIPHER_ENABLE_LOCKING_STYLE
27049   { "fchmod",       (sqlcipher3_syscall_ptr)fchmod,     0  },
27050 #else
27051   { "fchmod",       (sqlcipher3_syscall_ptr)0,          0  },
27052 #endif
27053 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
27054
27055 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27056   { "fallocate",    (sqlcipher3_syscall_ptr)posix_fallocate,  0 },
27057 #else
27058   { "fallocate",    (sqlcipher3_syscall_ptr)0,                0 },
27059 #endif
27060 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
27061
27062   { "unlink",       (sqlcipher3_syscall_ptr)unlink,           0 },
27063 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
27064
27065   { "openDirectory",    (sqlcipher3_syscall_ptr)openDirectory,      0 },
27066 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
27067
27068 }; /* End of the overrideable system calls */
27069
27070 /*
27071 ** This is the xSetSystemCall() method of sqlcipher3_vfs for all of the
27072 ** "unix" VFSes.  Return SQLCIPHER_OK opon successfully updating the
27073 ** system call pointer, or SQLCIPHER_NOTFOUND if there is no configurable
27074 ** system call named zName.
27075 */
27076 static int unixSetSystemCall(
27077   sqlcipher3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
27078   const char *zName,            /* Name of system call to override */
27079   sqlcipher3_syscall_ptr pNewFunc  /* Pointer to new system call value */
27080 ){
27081   unsigned int i;
27082   int rc = SQLCIPHER_NOTFOUND;
27083
27084   UNUSED_PARAMETER(pNotUsed);
27085   if( zName==0 ){
27086     /* If no zName is given, restore all system calls to their default
27087     ** settings and return NULL
27088     */
27089     rc = SQLCIPHER_OK;
27090     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27091       if( aSyscall[i].pDefault ){
27092         aSyscall[i].pCurrent = aSyscall[i].pDefault;
27093       }
27094     }
27095   }else{
27096     /* If zName is specified, operate on only the one system call
27097     ** specified.
27098     */
27099     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27100       if( strcmp(zName, aSyscall[i].zName)==0 ){
27101         if( aSyscall[i].pDefault==0 ){
27102           aSyscall[i].pDefault = aSyscall[i].pCurrent;
27103         }
27104         rc = SQLCIPHER_OK;
27105         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
27106         aSyscall[i].pCurrent = pNewFunc;
27107         break;
27108       }
27109     }
27110   }
27111   return rc;
27112 }
27113
27114 /*
27115 ** Return the value of a system call.  Return NULL if zName is not a
27116 ** recognized system call name.  NULL is also returned if the system call
27117 ** is currently undefined.
27118 */
27119 static sqlcipher3_syscall_ptr unixGetSystemCall(
27120   sqlcipher3_vfs *pNotUsed,
27121   const char *zName
27122 ){
27123   unsigned int i;
27124
27125   UNUSED_PARAMETER(pNotUsed);
27126   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27127     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
27128   }
27129   return 0;
27130 }
27131
27132 /*
27133 ** Return the name of the first system call after zName.  If zName==NULL
27134 ** then return the name of the first system call.  Return NULL if zName
27135 ** is the last system call or if zName is not the name of a valid
27136 ** system call.
27137 */
27138 static const char *unixNextSystemCall(sqlcipher3_vfs *p, const char *zName){
27139   int i = -1;
27140
27141   UNUSED_PARAMETER(p);
27142   if( zName ){
27143     for(i=0; i<ArraySize(aSyscall)-1; i++){
27144       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
27145     }
27146   }
27147   for(i++; i<ArraySize(aSyscall); i++){
27148     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
27149   }
27150   return 0;
27151 }
27152
27153 /*
27154 ** Retry open() calls that fail due to EINTR
27155 */
27156 static int robust_open(const char *z, int f, int m){
27157   int rc;
27158   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
27159   return rc;
27160 }
27161
27162 /*
27163 ** Helper functions to obtain and relinquish the global mutex. The
27164 ** global mutex is used to protect the unixInodeInfo and
27165 ** vxworksFileId objects used by this file, all of which may be 
27166 ** shared by multiple threads.
27167 **
27168 ** Function unixMutexHeld() is used to assert() that the global mutex 
27169 ** is held when required. This function is only used as part of assert() 
27170 ** statements. e.g.
27171 **
27172 **   unixEnterMutex()
27173 **     assert( unixMutexHeld() );
27174 **   unixEnterLeave()
27175 */
27176 static void unixEnterMutex(void){
27177   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
27178 }
27179 static void unixLeaveMutex(void){
27180   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
27181 }
27182 #ifdef SQLCIPHER_DEBUG
27183 static int unixMutexHeld(void) {
27184   return sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
27185 }
27186 #endif
27187
27188
27189 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
27190 /*
27191 ** Helper function for printing out trace information from debugging
27192 ** binaries. This returns the string represetation of the supplied
27193 ** integer lock-type.
27194 */
27195 static const char *azFileLock(int eFileLock){
27196   switch( eFileLock ){
27197     case NO_LOCK: return "NONE";
27198     case SHARED_LOCK: return "SHARED";
27199     case RESERVED_LOCK: return "RESERVED";
27200     case PENDING_LOCK: return "PENDING";
27201     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
27202   }
27203   return "ERROR";
27204 }
27205 #endif
27206
27207 #ifdef SQLCIPHER_LOCK_TRACE
27208 /*
27209 ** Print out information about all locking operations.
27210 **
27211 ** This routine is used for troubleshooting locks on multithreaded
27212 ** platforms.  Enable by compiling with the -DSQLCIPHER_LOCK_TRACE
27213 ** command-line option on the compiler.  This code is normally
27214 ** turned off.
27215 */
27216 static int lockTrace(int fd, int op, struct flock *p){
27217   char *zOpName, *zType;
27218   int s;
27219   int savedErrno;
27220   if( op==F_GETLK ){
27221     zOpName = "GETLK";
27222   }else if( op==F_SETLK ){
27223     zOpName = "SETLK";
27224   }else{
27225     s = osFcntl(fd, op, p);
27226     sqlcipher3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
27227     return s;
27228   }
27229   if( p->l_type==F_RDLCK ){
27230     zType = "RDLCK";
27231   }else if( p->l_type==F_WRLCK ){
27232     zType = "WRLCK";
27233   }else if( p->l_type==F_UNLCK ){
27234     zType = "UNLCK";
27235   }else{
27236     assert( 0 );
27237   }
27238   assert( p->l_whence==SEEK_SET );
27239   s = osFcntl(fd, op, p);
27240   savedErrno = errno;
27241   sqlcipher3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
27242      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
27243      (int)p->l_pid, s);
27244   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
27245     struct flock l2;
27246     l2 = *p;
27247     osFcntl(fd, F_GETLK, &l2);
27248     if( l2.l_type==F_RDLCK ){
27249       zType = "RDLCK";
27250     }else if( l2.l_type==F_WRLCK ){
27251       zType = "WRLCK";
27252     }else if( l2.l_type==F_UNLCK ){
27253       zType = "UNLCK";
27254     }else{
27255       assert( 0 );
27256     }
27257     sqlcipher3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
27258        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
27259   }
27260   errno = savedErrno;
27261   return s;
27262 }
27263 #undef osFcntl
27264 #define osFcntl lockTrace
27265 #endif /* SQLCIPHER_LOCK_TRACE */
27266
27267 /*
27268 ** Retry ftruncate() calls that fail due to EINTR
27269 */
27270 static int robust_ftruncate(int h, sqlcipher3_int64 sz){
27271   int rc;
27272   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
27273   return rc;
27274 }
27275
27276 /*
27277 ** This routine translates a standard POSIX errno code into something
27278 ** useful to the clients of the sqlcipher3 functions.  Specifically, it is
27279 ** intended to translate a variety of "try again" errors into SQLCIPHER_BUSY
27280 ** and a variety of "please close the file descriptor NOW" errors into 
27281 ** SQLCIPHER_IOERR
27282 ** 
27283 ** Errors during initialization of locks, or file system support for locks,
27284 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
27285 */
27286 static int sqlcipherErrorFromPosixError(int posixError, int sqlcipherIOErr) {
27287   switch (posixError) {
27288 #if 0
27289   /* At one point this code was not commented out. In theory, this branch
27290   ** should never be hit, as this function should only be called after
27291   ** a locking-related function (i.e. fcntl()) has returned non-zero with
27292   ** the value of errno as the first argument. Since a system call has failed,
27293   ** errno should be non-zero.
27294   **
27295   ** Despite this, if errno really is zero, we still don't want to return
27296   ** SQLCIPHER_OK. The system call failed, and *some* SQLite error should be
27297   ** propagated back to the caller. Commenting this branch out means errno==0
27298   ** will be handled by the "default:" case below.
27299   */
27300   case 0: 
27301     return SQLCIPHER_OK;
27302 #endif
27303
27304   case EAGAIN:
27305   case ETIMEDOUT:
27306   case EBUSY:
27307   case EINTR:
27308   case ENOLCK:  
27309     /* random NFS retry error, unless during file system support 
27310      * introspection, in which it actually means what it says */
27311     return SQLCIPHER_BUSY;
27312     
27313   case EACCES: 
27314     /* EACCES is like EAGAIN during locking operations, but not any other time*/
27315     if( (sqlcipherIOErr == SQLCIPHER_IOERR_LOCK) || 
27316         (sqlcipherIOErr == SQLCIPHER_IOERR_UNLOCK) || 
27317         (sqlcipherIOErr == SQLCIPHER_IOERR_RDLOCK) ||
27318         (sqlcipherIOErr == SQLCIPHER_IOERR_CHECKRESERVEDLOCK) ){
27319       return SQLCIPHER_BUSY;
27320     }
27321     /* else fall through */
27322   case EPERM: 
27323     return SQLCIPHER_PERM;
27324     
27325   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
27326   ** this module never makes such a call. And the code in SQLite itself 
27327   ** asserts that SQLCIPHER_IOERR_BLOCKED is never returned. For these reasons
27328   ** this case is also commented out. If the system does set errno to EDEADLK,
27329   ** the default SQLCIPHER_IOERR_XXX code will be returned. */
27330 #if 0
27331   case EDEADLK:
27332     return SQLCIPHER_IOERR_BLOCKED;
27333 #endif
27334     
27335 #if EOPNOTSUPP!=ENOTSUP
27336   case EOPNOTSUPP: 
27337     /* something went terribly awry, unless during file system support 
27338      * introspection, in which it actually means what it says */
27339 #endif
27340 #ifdef ENOTSUP
27341   case ENOTSUP: 
27342     /* invalid fd, unless during file system support introspection, in which 
27343      * it actually means what it says */
27344 #endif
27345   case EIO:
27346   case EBADF:
27347   case EINVAL:
27348   case ENOTCONN:
27349   case ENODEV:
27350   case ENXIO:
27351   case ENOENT:
27352 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
27353   case ESTALE:
27354 #endif
27355   case ENOSYS:
27356     /* these should force the client to close the file and reconnect */
27357     
27358   default: 
27359     return sqlcipherIOErr;
27360   }
27361 }
27362
27363
27364
27365 /******************************************************************************
27366 ****************** Begin Unique File ID Utility Used By VxWorks ***************
27367 **
27368 ** On most versions of unix, we can get a unique ID for a file by concatenating
27369 ** the device number and the inode number.  But this does not work on VxWorks.
27370 ** On VxWorks, a unique file id must be based on the canonical filename.
27371 **
27372 ** A pointer to an instance of the following structure can be used as a
27373 ** unique file ID in VxWorks.  Each instance of this structure contains
27374 ** a copy of the canonical filename.  There is also a reference count.  
27375 ** The structure is reclaimed when the number of pointers to it drops to
27376 ** zero.
27377 **
27378 ** There are never very many files open at one time and lookups are not
27379 ** a performance-critical path, so it is sufficient to put these
27380 ** structures on a linked list.
27381 */
27382 struct vxworksFileId {
27383   struct vxworksFileId *pNext;  /* Next in a list of them all */
27384   int nRef;                     /* Number of references to this one */
27385   int nName;                    /* Length of the zCanonicalName[] string */
27386   char *zCanonicalName;         /* Canonical filename */
27387 };
27388
27389 #if OS_VXWORKS
27390 /* 
27391 ** All unique filenames are held on a linked list headed by this
27392 ** variable:
27393 */
27394 static struct vxworksFileId *vxworksFileList = 0;
27395
27396 /*
27397 ** Simplify a filename into its canonical form
27398 ** by making the following changes:
27399 **
27400 **  * removing any trailing and duplicate /
27401 **  * convert /./ into just /
27402 **  * convert /A/../ where A is any simple name into just /
27403 **
27404 ** Changes are made in-place.  Return the new name length.
27405 **
27406 ** The original filename is in z[0..n-1].  Return the number of
27407 ** characters in the simplified name.
27408 */
27409 static int vxworksSimplifyName(char *z, int n){
27410   int i, j;
27411   while( n>1 && z[n-1]=='/' ){ n--; }
27412   for(i=j=0; i<n; i++){
27413     if( z[i]=='/' ){
27414       if( z[i+1]=='/' ) continue;
27415       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
27416         i += 1;
27417         continue;
27418       }
27419       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
27420         while( j>0 && z[j-1]!='/' ){ j--; }
27421         if( j>0 ){ j--; }
27422         i += 2;
27423         continue;
27424       }
27425     }
27426     z[j++] = z[i];
27427   }
27428   z[j] = 0;
27429   return j;
27430 }
27431
27432 /*
27433 ** Find a unique file ID for the given absolute pathname.  Return
27434 ** a pointer to the vxworksFileId object.  This pointer is the unique
27435 ** file ID.
27436 **
27437 ** The nRef field of the vxworksFileId object is incremented before
27438 ** the object is returned.  A new vxworksFileId object is created
27439 ** and added to the global list if necessary.
27440 **
27441 ** If a memory allocation error occurs, return NULL.
27442 */
27443 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
27444   struct vxworksFileId *pNew;         /* search key and new file ID */
27445   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
27446   int n;                              /* Length of zAbsoluteName string */
27447
27448   assert( zAbsoluteName[0]=='/' );
27449   n = (int)strlen(zAbsoluteName);
27450   pNew = sqlcipher3_malloc( sizeof(*pNew) + (n+1) );
27451   if( pNew==0 ) return 0;
27452   pNew->zCanonicalName = (char*)&pNew[1];
27453   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
27454   n = vxworksSimplifyName(pNew->zCanonicalName, n);
27455
27456   /* Search for an existing entry that matching the canonical name.
27457   ** If found, increment the reference count and return a pointer to
27458   ** the existing file ID.
27459   */
27460   unixEnterMutex();
27461   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
27462     if( pCandidate->nName==n 
27463      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
27464     ){
27465        sqlcipher3_free(pNew);
27466        pCandidate->nRef++;
27467        unixLeaveMutex();
27468        return pCandidate;
27469     }
27470   }
27471
27472   /* No match was found.  We will make a new file ID */
27473   pNew->nRef = 1;
27474   pNew->nName = n;
27475   pNew->pNext = vxworksFileList;
27476   vxworksFileList = pNew;
27477   unixLeaveMutex();
27478   return pNew;
27479 }
27480
27481 /*
27482 ** Decrement the reference count on a vxworksFileId object.  Free
27483 ** the object when the reference count reaches zero.
27484 */
27485 static void vxworksReleaseFileId(struct vxworksFileId *pId){
27486   unixEnterMutex();
27487   assert( pId->nRef>0 );
27488   pId->nRef--;
27489   if( pId->nRef==0 ){
27490     struct vxworksFileId **pp;
27491     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
27492     assert( *pp==pId );
27493     *pp = pId->pNext;
27494     sqlcipher3_free(pId);
27495   }
27496   unixLeaveMutex();
27497 }
27498 #endif /* OS_VXWORKS */
27499 /*************** End of Unique File ID Utility Used By VxWorks ****************
27500 ******************************************************************************/
27501
27502
27503 /******************************************************************************
27504 *************************** Posix Advisory Locking ****************************
27505 **
27506 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
27507 ** section 6.5.2.2 lines 483 through 490 specify that when a process
27508 ** sets or clears a lock, that operation overrides any prior locks set
27509 ** by the same process.  It does not explicitly say so, but this implies
27510 ** that it overrides locks set by the same process using a different
27511 ** file descriptor.  Consider this test case:
27512 **
27513 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
27514 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
27515 **
27516 ** Suppose ./file1 and ./file2 are really the same file (because
27517 ** one is a hard or symbolic link to the other) then if you set
27518 ** an exclusive lock on fd1, then try to get an exclusive lock
27519 ** on fd2, it works.  I would have expected the second lock to
27520 ** fail since there was already a lock on the file due to fd1.
27521 ** But not so.  Since both locks came from the same process, the
27522 ** second overrides the first, even though they were on different
27523 ** file descriptors opened on different file names.
27524 **
27525 ** This means that we cannot use POSIX locks to synchronize file access
27526 ** among competing threads of the same process.  POSIX locks will work fine
27527 ** to synchronize access for threads in separate processes, but not
27528 ** threads within the same process.
27529 **
27530 ** To work around the problem, SQLite has to manage file locks internally
27531 ** on its own.  Whenever a new database is opened, we have to find the
27532 ** specific inode of the database file (the inode is determined by the
27533 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
27534 ** and check for locks already existing on that inode.  When locks are
27535 ** created or removed, we have to look at our own internal record of the
27536 ** locks to see if another thread has previously set a lock on that same
27537 ** inode.
27538 **
27539 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
27540 ** For VxWorks, we have to use the alternative unique ID system based on
27541 ** canonical filename and implemented in the previous division.)
27542 **
27543 ** The sqlcipher3_file structure for POSIX is no longer just an integer file
27544 ** descriptor.  It is now a structure that holds the integer file
27545 ** descriptor and a pointer to a structure that describes the internal
27546 ** locks on the corresponding inode.  There is one locking structure
27547 ** per inode, so if the same inode is opened twice, both unixFile structures
27548 ** point to the same locking structure.  The locking structure keeps
27549 ** a reference count (so we will know when to delete it) and a "cnt"
27550 ** field that tells us its internal lock status.  cnt==0 means the
27551 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
27552 ** cnt>0 means there are cnt shared locks on the file.
27553 **
27554 ** Any attempt to lock or unlock a file first checks the locking
27555 ** structure.  The fcntl() system call is only invoked to set a 
27556 ** POSIX lock if the internal lock structure transitions between
27557 ** a locked and an unlocked state.
27558 **
27559 ** But wait:  there are yet more problems with POSIX advisory locks.
27560 **
27561 ** If you close a file descriptor that points to a file that has locks,
27562 ** all locks on that file that are owned by the current process are
27563 ** released.  To work around this problem, each unixInodeInfo object
27564 ** maintains a count of the number of pending locks on tha inode.
27565 ** When an attempt is made to close an unixFile, if there are
27566 ** other unixFile open on the same inode that are holding locks, the call
27567 ** to close() the file descriptor is deferred until all of the locks clear.
27568 ** The unixInodeInfo structure keeps a list of file descriptors that need to
27569 ** be closed and that list is walked (and cleared) when the last lock
27570 ** clears.
27571 **
27572 ** Yet another problem:  LinuxThreads do not play well with posix locks.
27573 **
27574 ** Many older versions of linux use the LinuxThreads library which is
27575 ** not posix compliant.  Under LinuxThreads, a lock created by thread
27576 ** A cannot be modified or overridden by a different thread B.
27577 ** Only thread A can modify the lock.  Locking behavior is correct
27578 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
27579 ** on linux - with NPTL a lock created by thread A can override locks
27580 ** in thread B.  But there is no way to know at compile-time which
27581 ** threading library is being used.  So there is no way to know at
27582 ** compile-time whether or not thread A can override locks on thread B.
27583 ** One has to do a run-time check to discover the behavior of the
27584 ** current process.
27585 **
27586 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
27587 ** was dropped beginning with version 3.7.0.  SQLite will still work with
27588 ** LinuxThreads provided that (1) there is no more than one connection 
27589 ** per database file in the same process and (2) database connections
27590 ** do not move across threads.
27591 */
27592
27593 /*
27594 ** An instance of the following structure serves as the key used
27595 ** to locate a particular unixInodeInfo object.
27596 */
27597 struct unixFileId {
27598   dev_t dev;                  /* Device number */
27599 #if OS_VXWORKS
27600   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
27601 #else
27602   ino_t ino;                  /* Inode number */
27603 #endif
27604 };
27605
27606 /*
27607 ** An instance of the following structure is allocated for each open
27608 ** inode.  Or, on LinuxThreads, there is one of these structures for
27609 ** each inode opened by each thread.
27610 **
27611 ** A single inode can have multiple file descriptors, so each unixFile
27612 ** structure contains a pointer to an instance of this object and this
27613 ** object keeps a count of the number of unixFile pointing to it.
27614 */
27615 struct unixInodeInfo {
27616   struct unixFileId fileId;       /* The lookup key */
27617   int nShared;                    /* Number of SHARED locks held */
27618   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
27619   unsigned char bProcessLock;     /* An exclusive process lock is held */
27620   int nRef;                       /* Number of pointers to this structure */
27621   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
27622   int nLock;                      /* Number of outstanding file locks */
27623   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
27624   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
27625   unixInodeInfo *pPrev;           /*    .... doubly linked */
27626 #if SQLCIPHER_ENABLE_LOCKING_STYLE
27627   unsigned long long sharedByte;  /* for AFP simulated shared lock */
27628 #endif
27629 #if OS_VXWORKS
27630   sem_t *pSem;                    /* Named POSIX semaphore */
27631   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
27632 #endif
27633 };
27634
27635 /*
27636 ** A lists of all unixInodeInfo objects.
27637 */
27638 static unixInodeInfo *inodeList = 0;
27639
27640 /*
27641 **
27642 ** This function - unixLogError_x(), is only ever called via the macro
27643 ** unixLogError().
27644 **
27645 ** It is invoked after an error occurs in an OS function and errno has been
27646 ** set. It logs a message using sqlcipher3_log() containing the current value of
27647 ** errno and, if possible, the human-readable equivalent from strerror() or
27648 ** strerror_r().
27649 **
27650 ** The first argument passed to the macro should be the error code that
27651 ** will be returned to SQLite (e.g. SQLCIPHER_IOERR_DELETE, SQLCIPHER_CANTOPEN). 
27652 ** The two subsequent arguments should be the name of the OS function that
27653 ** failed (e.g. "unlink", "open") and the the associated file-system path,
27654 ** if any.
27655 */
27656 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
27657 static int unixLogErrorAtLine(
27658   int errcode,                    /* SQLite error code */
27659   const char *zFunc,              /* Name of OS function that failed */
27660   const char *zPath,              /* File path associated with error */
27661   int iLine                       /* Source line number where error occurred */
27662 ){
27663   char *zErr;                     /* Message from strerror() or equivalent */
27664   int iErrno = errno;             /* Saved syscall error number */
27665
27666   /* If this is not a threadsafe build (SQLCIPHER_THREADSAFE==0), then use
27667   ** the strerror() function to obtain the human-readable error message
27668   ** equivalent to errno. Otherwise, use strerror_r().
27669   */ 
27670 #if SQLCIPHER_THREADSAFE && defined(HAVE_STRERROR_R)
27671   char aErr[80];
27672   memset(aErr, 0, sizeof(aErr));
27673   zErr = aErr;
27674
27675   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
27676   ** assume that the system provides the the GNU version of strerror_r() that 
27677   ** returns a pointer to a buffer containing the error message. That pointer 
27678   ** may point to aErr[], or it may point to some static storage somewhere. 
27679   ** Otherwise, assume that the system provides the POSIX version of 
27680   ** strerror_r(), which always writes an error message into aErr[].
27681   **
27682   ** If the code incorrectly assumes that it is the POSIX version that is
27683   ** available, the error message will often be an empty string. Not a
27684   ** huge problem. Incorrectly concluding that the GNU version is available 
27685   ** could lead to a segfault though.
27686   */
27687 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
27688   zErr = 
27689 # endif
27690   strerror_r(iErrno, aErr, sizeof(aErr)-1);
27691
27692 #elif SQLCIPHER_THREADSAFE
27693   /* This is a threadsafe build, but strerror_r() is not available. */
27694   zErr = "";
27695 #else
27696   /* Non-threadsafe build, use strerror(). */
27697   zErr = strerror(iErrno);
27698 #endif
27699
27700   assert( errcode!=SQLCIPHER_OK );
27701   if( zPath==0 ) zPath = "";
27702   sqlcipher3_log(errcode,
27703       "os_unix.c:%d: (%d) %s(%s) - %s",
27704       iLine, iErrno, zFunc, zPath, zErr
27705   );
27706
27707   return errcode;
27708 }
27709
27710 /*
27711 ** Close a file descriptor.
27712 **
27713 ** We assume that close() almost always works, since it is only in a
27714 ** very sick application or on a very sick platform that it might fail.
27715 ** If it does fail, simply leak the file descriptor, but do log the
27716 ** error.
27717 **
27718 ** Note that it is not safe to retry close() after EINTR since the
27719 ** file descriptor might have already been reused by another thread.
27720 ** So we don't even try to recover from an EINTR.  Just log the error
27721 ** and move on.
27722 */
27723 static void robust_close(unixFile *pFile, int h, int lineno){
27724   if( osClose(h) ){
27725     unixLogErrorAtLine(SQLCIPHER_IOERR_CLOSE, "close",
27726                        pFile ? pFile->zPath : 0, lineno);
27727   }
27728 }
27729
27730 /*
27731 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
27732 */ 
27733 static void closePendingFds(unixFile *pFile){
27734   unixInodeInfo *pInode = pFile->pInode;
27735   UnixUnusedFd *p;
27736   UnixUnusedFd *pNext;
27737   for(p=pInode->pUnused; p; p=pNext){
27738     pNext = p->pNext;
27739     robust_close(pFile, p->fd, __LINE__);
27740     sqlcipher3_free(p);
27741   }
27742   pInode->pUnused = 0;
27743 }
27744
27745 /*
27746 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
27747 **
27748 ** The mutex entered using the unixEnterMutex() function must be held
27749 ** when this function is called.
27750 */
27751 static void releaseInodeInfo(unixFile *pFile){
27752   unixInodeInfo *pInode = pFile->pInode;
27753   assert( unixMutexHeld() );
27754   if( ALWAYS(pInode) ){
27755     pInode->nRef--;
27756     if( pInode->nRef==0 ){
27757       assert( pInode->pShmNode==0 );
27758       closePendingFds(pFile);
27759       if( pInode->pPrev ){
27760         assert( pInode->pPrev->pNext==pInode );
27761         pInode->pPrev->pNext = pInode->pNext;
27762       }else{
27763         assert( inodeList==pInode );
27764         inodeList = pInode->pNext;
27765       }
27766       if( pInode->pNext ){
27767         assert( pInode->pNext->pPrev==pInode );
27768         pInode->pNext->pPrev = pInode->pPrev;
27769       }
27770       sqlcipher3_free(pInode);
27771     }
27772   }
27773 }
27774
27775 /*
27776 ** Given a file descriptor, locate the unixInodeInfo object that
27777 ** describes that file descriptor.  Create a new one if necessary.  The
27778 ** return value might be uninitialized if an error occurs.
27779 **
27780 ** The mutex entered using the unixEnterMutex() function must be held
27781 ** when this function is called.
27782 **
27783 ** Return an appropriate error code.
27784 */
27785 static int findInodeInfo(
27786   unixFile *pFile,               /* Unix file with file desc used in the key */
27787   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
27788 ){
27789   int rc;                        /* System call return code */
27790   int fd;                        /* The file descriptor for pFile */
27791   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
27792   struct stat statbuf;           /* Low-level file information */
27793   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
27794
27795   assert( unixMutexHeld() );
27796
27797   /* Get low-level information about the file that we can used to
27798   ** create a unique name for the file.
27799   */
27800   fd = pFile->h;
27801   rc = osFstat(fd, &statbuf);
27802   if( rc!=0 ){
27803     pFile->lastErrno = errno;
27804 #ifdef EOVERFLOW
27805     if( pFile->lastErrno==EOVERFLOW ) return SQLCIPHER_NOLFS;
27806 #endif
27807     return SQLCIPHER_IOERR;
27808   }
27809
27810 #ifdef __APPLE__
27811   /* On OS X on an msdos filesystem, the inode number is reported
27812   ** incorrectly for zero-size files.  See ticket #3260.  To work
27813   ** around this problem (we consider it a bug in OS X, not SQLite)
27814   ** we always increase the file size to 1 by writing a single byte
27815   ** prior to accessing the inode number.  The one byte written is
27816   ** an ASCII 'S' character which also happens to be the first byte
27817   ** in the header of every SQLite database.  In this way, if there
27818   ** is a race condition such that another thread has already populated
27819   ** the first page of the database, no damage is done.
27820   */
27821   if( statbuf.st_size==0 && (pFile->fsFlags & SQLCIPHER_FSFLAGS_IS_MSDOS)!=0 ){
27822     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
27823     if( rc!=1 ){
27824       pFile->lastErrno = errno;
27825       return SQLCIPHER_IOERR;
27826     }
27827     rc = osFstat(fd, &statbuf);
27828     if( rc!=0 ){
27829       pFile->lastErrno = errno;
27830       return SQLCIPHER_IOERR;
27831     }
27832   }
27833 #endif
27834
27835   memset(&fileId, 0, sizeof(fileId));
27836   fileId.dev = statbuf.st_dev;
27837 #if OS_VXWORKS
27838   fileId.pId = pFile->pId;
27839 #else
27840   fileId.ino = statbuf.st_ino;
27841 #endif
27842   pInode = inodeList;
27843   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
27844     pInode = pInode->pNext;
27845   }
27846   if( pInode==0 ){
27847     pInode = sqlcipher3_malloc( sizeof(*pInode) );
27848     if( pInode==0 ){
27849       return SQLCIPHER_NOMEM;
27850     }
27851     memset(pInode, 0, sizeof(*pInode));
27852     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
27853     pInode->nRef = 1;
27854     pInode->pNext = inodeList;
27855     pInode->pPrev = 0;
27856     if( inodeList ) inodeList->pPrev = pInode;
27857     inodeList = pInode;
27858   }else{
27859     pInode->nRef++;
27860   }
27861   *ppInode = pInode;
27862   return SQLCIPHER_OK;
27863 }
27864
27865
27866 /*
27867 ** This routine checks if there is a RESERVED lock held on the specified
27868 ** file by this or any other process. If such a lock is held, set *pResOut
27869 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27870 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
27871 */
27872 static int unixCheckReservedLock(sqlcipher3_file *id, int *pResOut){
27873   int rc = SQLCIPHER_OK;
27874   int reserved = 0;
27875   unixFile *pFile = (unixFile*)id;
27876
27877   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
27878
27879   assert( pFile );
27880   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27881
27882   /* Check if a thread in this process holds such a lock */
27883   if( pFile->pInode->eFileLock>SHARED_LOCK ){
27884     reserved = 1;
27885   }
27886
27887   /* Otherwise see if some other process holds it.
27888   */
27889 #ifndef __DJGPP__
27890   if( !reserved && !pFile->pInode->bProcessLock ){
27891     struct flock lock;
27892     lock.l_whence = SEEK_SET;
27893     lock.l_start = RESERVED_BYTE;
27894     lock.l_len = 1;
27895     lock.l_type = F_WRLCK;
27896     if( osFcntl(pFile->h, F_GETLK, &lock) ){
27897       rc = SQLCIPHER_IOERR_CHECKRESERVEDLOCK;
27898       pFile->lastErrno = errno;
27899     } else if( lock.l_type!=F_UNLCK ){
27900       reserved = 1;
27901     }
27902   }
27903 #endif
27904   
27905   unixLeaveMutex();
27906   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
27907
27908   *pResOut = reserved;
27909   return rc;
27910 }
27911
27912 /*
27913 ** Attempt to set a system-lock on the file pFile.  The lock is 
27914 ** described by pLock.
27915 **
27916 ** If the pFile was opened read/write from unix-excl, then the only lock
27917 ** ever obtained is an exclusive lock, and it is obtained exactly once
27918 ** the first time any lock is attempted.  All subsequent system locking
27919 ** operations become no-ops.  Locking operations still happen internally,
27920 ** in order to coordinate access between separate database connections
27921 ** within this process, but all of that is handled in memory and the
27922 ** operating system does not participate.
27923 **
27924 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
27925 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
27926 ** and is read-only.
27927 **
27928 ** Zero is returned if the call completes successfully, or -1 if a call
27929 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
27930 */
27931 static int unixFileLock(unixFile *pFile, struct flock *pLock){
27932   int rc;
27933   unixInodeInfo *pInode = pFile->pInode;
27934   assert( unixMutexHeld() );
27935   assert( pInode!=0 );
27936   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
27937    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
27938   ){
27939     if( pInode->bProcessLock==0 ){
27940       struct flock lock;
27941       assert( pInode->nLock==0 );
27942       lock.l_whence = SEEK_SET;
27943       lock.l_start = SHARED_FIRST;
27944       lock.l_len = SHARED_SIZE;
27945       lock.l_type = F_WRLCK;
27946       rc = osFcntl(pFile->h, F_SETLK, &lock);
27947       if( rc<0 ) return rc;
27948       pInode->bProcessLock = 1;
27949       pInode->nLock++;
27950     }else{
27951       rc = 0;
27952     }
27953   }else{
27954     rc = osFcntl(pFile->h, F_SETLK, pLock);
27955   }
27956   return rc;
27957 }
27958
27959 /*
27960 ** Lock the file with the lock specified by parameter eFileLock - one
27961 ** of the following:
27962 **
27963 **     (1) SHARED_LOCK
27964 **     (2) RESERVED_LOCK
27965 **     (3) PENDING_LOCK
27966 **     (4) EXCLUSIVE_LOCK
27967 **
27968 ** Sometimes when requesting one lock state, additional lock states
27969 ** are inserted in between.  The locking might fail on one of the later
27970 ** transitions leaving the lock state different from what it started but
27971 ** still short of its goal.  The following chart shows the allowed
27972 ** transitions and the inserted intermediate states:
27973 **
27974 **    UNLOCKED -> SHARED
27975 **    SHARED -> RESERVED
27976 **    SHARED -> (PENDING) -> EXCLUSIVE
27977 **    RESERVED -> (PENDING) -> EXCLUSIVE
27978 **    PENDING -> EXCLUSIVE
27979 **
27980 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
27981 ** routine to lower a locking level.
27982 */
27983 static int unixLock(sqlcipher3_file *id, int eFileLock){
27984   /* The following describes the implementation of the various locks and
27985   ** lock transitions in terms of the POSIX advisory shared and exclusive
27986   ** lock primitives (called read-locks and write-locks below, to avoid
27987   ** confusion with SQLite lock names). The algorithms are complicated
27988   ** slightly in order to be compatible with windows systems simultaneously
27989   ** accessing the same database file, in case that is ever required.
27990   **
27991   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
27992   ** byte', each single bytes at well known offsets, and the 'shared byte
27993   ** range', a range of 510 bytes at a well known offset.
27994   **
27995   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
27996   ** byte'.  If this is successful, a random byte from the 'shared byte
27997   ** range' is read-locked and the lock on the 'pending byte' released.
27998   **
27999   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
28000   ** A RESERVED lock is implemented by grabbing a write-lock on the
28001   ** 'reserved byte'. 
28002   **
28003   ** A process may only obtain a PENDING lock after it has obtained a
28004   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
28005   ** on the 'pending byte'. This ensures that no new SHARED locks can be
28006   ** obtained, but existing SHARED locks are allowed to persist. A process
28007   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
28008   ** This property is used by the algorithm for rolling back a journal file
28009   ** after a crash.
28010   **
28011   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
28012   ** implemented by obtaining a write-lock on the entire 'shared byte
28013   ** range'. Since all other locks require a read-lock on one of the bytes
28014   ** within this range, this ensures that no other locks are held on the
28015   ** database. 
28016   **
28017   ** The reason a single byte cannot be used instead of the 'shared byte
28018   ** range' is that some versions of windows do not support read-locks. By
28019   ** locking a random byte from a range, concurrent SHARED locks may exist
28020   ** even if the locking primitive used is always a write-lock.
28021   */
28022   int rc = SQLCIPHER_OK;
28023   unixFile *pFile = (unixFile*)id;
28024   unixInodeInfo *pInode;
28025   struct flock lock;
28026   int tErrno = 0;
28027
28028   assert( pFile );
28029   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
28030       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
28031       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
28032
28033   /* If there is already a lock of this type or more restrictive on the
28034   ** unixFile, do nothing. Don't use the end_lock: exit path, as
28035   ** unixEnterMutex() hasn't been called yet.
28036   */
28037   if( pFile->eFileLock>=eFileLock ){
28038     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
28039             azFileLock(eFileLock)));
28040     return SQLCIPHER_OK;
28041   }
28042
28043   /* Make sure the locking sequence is correct.
28044   **  (1) We never move from unlocked to anything higher than shared lock.
28045   **  (2) SQLite never explicitly requests a pendig lock.
28046   **  (3) A shared lock is always held when a reserve lock is requested.
28047   */
28048   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
28049   assert( eFileLock!=PENDING_LOCK );
28050   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
28051
28052   /* This mutex is needed because pFile->pInode is shared across threads
28053   */
28054   unixEnterMutex();
28055   pInode = pFile->pInode;
28056
28057   /* If some thread using this PID has a lock via a different unixFile*
28058   ** handle that precludes the requested lock, return BUSY.
28059   */
28060   if( (pFile->eFileLock!=pInode->eFileLock && 
28061           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
28062   ){
28063     rc = SQLCIPHER_BUSY;
28064     goto end_lock;
28065   }
28066
28067   /* If a SHARED lock is requested, and some thread using this PID already
28068   ** has a SHARED or RESERVED lock, then increment reference counts and
28069   ** return SQLCIPHER_OK.
28070   */
28071   if( eFileLock==SHARED_LOCK && 
28072       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
28073     assert( eFileLock==SHARED_LOCK );
28074     assert( pFile->eFileLock==0 );
28075     assert( pInode->nShared>0 );
28076     pFile->eFileLock = SHARED_LOCK;
28077     pInode->nShared++;
28078     pInode->nLock++;
28079     goto end_lock;
28080   }
28081
28082
28083   /* A PENDING lock is needed before acquiring a SHARED lock and before
28084   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
28085   ** be released.
28086   */
28087   lock.l_len = 1L;
28088   lock.l_whence = SEEK_SET;
28089   if( eFileLock==SHARED_LOCK 
28090       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
28091   ){
28092     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
28093     lock.l_start = PENDING_BYTE;
28094     if( unixFileLock(pFile, &lock) ){
28095       tErrno = errno;
28096       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28097       if( rc!=SQLCIPHER_BUSY ){
28098         pFile->lastErrno = tErrno;
28099       }
28100       goto end_lock;
28101     }
28102   }
28103
28104
28105   /* If control gets to this point, then actually go ahead and make
28106   ** operating system calls for the specified lock.
28107   */
28108   if( eFileLock==SHARED_LOCK ){
28109     assert( pInode->nShared==0 );
28110     assert( pInode->eFileLock==0 );
28111     assert( rc==SQLCIPHER_OK );
28112
28113     /* Now get the read-lock */
28114     lock.l_start = SHARED_FIRST;
28115     lock.l_len = SHARED_SIZE;
28116     if( unixFileLock(pFile, &lock) ){
28117       tErrno = errno;
28118       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28119     }
28120
28121     /* Drop the temporary PENDING lock */
28122     lock.l_start = PENDING_BYTE;
28123     lock.l_len = 1L;
28124     lock.l_type = F_UNLCK;
28125     if( unixFileLock(pFile, &lock) && rc==SQLCIPHER_OK ){
28126       /* This could happen with a network mount */
28127       tErrno = errno;
28128       rc = SQLCIPHER_IOERR_UNLOCK; 
28129     }
28130
28131     if( rc ){
28132       if( rc!=SQLCIPHER_BUSY ){
28133         pFile->lastErrno = tErrno;
28134       }
28135       goto end_lock;
28136     }else{
28137       pFile->eFileLock = SHARED_LOCK;
28138       pInode->nLock++;
28139       pInode->nShared = 1;
28140     }
28141   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
28142     /* We are trying for an exclusive lock but another thread in this
28143     ** same process is still holding a shared lock. */
28144     rc = SQLCIPHER_BUSY;
28145   }else{
28146     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
28147     ** assumed that there is a SHARED or greater lock on the file
28148     ** already.
28149     */
28150     assert( 0!=pFile->eFileLock );
28151     lock.l_type = F_WRLCK;
28152
28153     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
28154     if( eFileLock==RESERVED_LOCK ){
28155       lock.l_start = RESERVED_BYTE;
28156       lock.l_len = 1L;
28157     }else{
28158       lock.l_start = SHARED_FIRST;
28159       lock.l_len = SHARED_SIZE;
28160     }
28161
28162     if( unixFileLock(pFile, &lock) ){
28163       tErrno = errno;
28164       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28165       if( rc!=SQLCIPHER_BUSY ){
28166         pFile->lastErrno = tErrno;
28167       }
28168     }
28169   }
28170   
28171
28172 #ifndef NDEBUG
28173   /* Set up the transaction-counter change checking flags when
28174   ** transitioning from a SHARED to a RESERVED lock.  The change
28175   ** from SHARED to RESERVED marks the beginning of a normal
28176   ** write operation (not a hot journal rollback).
28177   */
28178   if( rc==SQLCIPHER_OK
28179    && pFile->eFileLock<=SHARED_LOCK
28180    && eFileLock==RESERVED_LOCK
28181   ){
28182     pFile->transCntrChng = 0;
28183     pFile->dbUpdate = 0;
28184     pFile->inNormalWrite = 1;
28185   }
28186 #endif
28187
28188
28189   if( rc==SQLCIPHER_OK ){
28190     pFile->eFileLock = eFileLock;
28191     pInode->eFileLock = eFileLock;
28192   }else if( eFileLock==EXCLUSIVE_LOCK ){
28193     pFile->eFileLock = PENDING_LOCK;
28194     pInode->eFileLock = PENDING_LOCK;
28195   }
28196
28197 end_lock:
28198   unixLeaveMutex();
28199   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
28200       rc==SQLCIPHER_OK ? "ok" : "failed"));
28201   return rc;
28202 }
28203
28204 /*
28205 ** Add the file descriptor used by file handle pFile to the corresponding
28206 ** pUnused list.
28207 */
28208 static void setPendingFd(unixFile *pFile){
28209   unixInodeInfo *pInode = pFile->pInode;
28210   UnixUnusedFd *p = pFile->pUnused;
28211   p->pNext = pInode->pUnused;
28212   pInode->pUnused = p;
28213   pFile->h = -1;
28214   pFile->pUnused = 0;
28215 }
28216
28217 /*
28218 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28219 ** must be either NO_LOCK or SHARED_LOCK.
28220 **
28221 ** If the locking level of the file descriptor is already at or below
28222 ** the requested locking level, this routine is a no-op.
28223 ** 
28224 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
28225 ** the byte range is divided into 2 parts and the first part is unlocked then
28226 ** set to a read lock, then the other part is simply unlocked.  This works 
28227 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
28228 ** remove the write lock on a region when a read lock is set.
28229 */
28230 static int posixUnlock(sqlcipher3_file *id, int eFileLock, int handleNFSUnlock){
28231   unixFile *pFile = (unixFile*)id;
28232   unixInodeInfo *pInode;
28233   struct flock lock;
28234   int rc = SQLCIPHER_OK;
28235
28236   assert( pFile );
28237   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
28238       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28239       getpid()));
28240
28241   assert( eFileLock<=SHARED_LOCK );
28242   if( pFile->eFileLock<=eFileLock ){
28243     return SQLCIPHER_OK;
28244   }
28245   unixEnterMutex();
28246   pInode = pFile->pInode;
28247   assert( pInode->nShared!=0 );
28248   if( pFile->eFileLock>SHARED_LOCK ){
28249     assert( pInode->eFileLock==pFile->eFileLock );
28250
28251 #ifndef NDEBUG
28252     /* When reducing a lock such that other processes can start
28253     ** reading the database file again, make sure that the
28254     ** transaction counter was updated if any part of the database
28255     ** file changed.  If the transaction counter is not updated,
28256     ** other connections to the same file might not realize that
28257     ** the file has changed and hence might not know to flush their
28258     ** cache.  The use of a stale cache can lead to database corruption.
28259     */
28260     pFile->inNormalWrite = 0;
28261 #endif
28262
28263     /* downgrading to a shared lock on NFS involves clearing the write lock
28264     ** before establishing the readlock - to avoid a race condition we downgrade
28265     ** the lock in 2 blocks, so that part of the range will be covered by a 
28266     ** write lock until the rest is covered by a read lock:
28267     **  1:   [WWWWW]
28268     **  2:   [....W]
28269     **  3:   [RRRRW]
28270     **  4:   [RRRR.]
28271     */
28272     if( eFileLock==SHARED_LOCK ){
28273
28274 #if !defined(__APPLE__) || !SQLCIPHER_ENABLE_LOCKING_STYLE
28275       (void)handleNFSUnlock;
28276       assert( handleNFSUnlock==0 );
28277 #endif
28278 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
28279       if( handleNFSUnlock ){
28280         int tErrno;               /* Error code from system call errors */
28281         off_t divSize = SHARED_SIZE - 1;
28282         
28283         lock.l_type = F_UNLCK;
28284         lock.l_whence = SEEK_SET;
28285         lock.l_start = SHARED_FIRST;
28286         lock.l_len = divSize;
28287         if( unixFileLock(pFile, &lock)==(-1) ){
28288           tErrno = errno;
28289           rc = SQLCIPHER_IOERR_UNLOCK;
28290           if( IS_LOCK_ERROR(rc) ){
28291             pFile->lastErrno = tErrno;
28292           }
28293           goto end_unlock;
28294         }
28295         lock.l_type = F_RDLCK;
28296         lock.l_whence = SEEK_SET;
28297         lock.l_start = SHARED_FIRST;
28298         lock.l_len = divSize;
28299         if( unixFileLock(pFile, &lock)==(-1) ){
28300           tErrno = errno;
28301           rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_RDLOCK);
28302           if( IS_LOCK_ERROR(rc) ){
28303             pFile->lastErrno = tErrno;
28304           }
28305           goto end_unlock;
28306         }
28307         lock.l_type = F_UNLCK;
28308         lock.l_whence = SEEK_SET;
28309         lock.l_start = SHARED_FIRST+divSize;
28310         lock.l_len = SHARED_SIZE-divSize;
28311         if( unixFileLock(pFile, &lock)==(-1) ){
28312           tErrno = errno;
28313           rc = SQLCIPHER_IOERR_UNLOCK;
28314           if( IS_LOCK_ERROR(rc) ){
28315             pFile->lastErrno = tErrno;
28316           }
28317           goto end_unlock;
28318         }
28319       }else
28320 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
28321       {
28322         lock.l_type = F_RDLCK;
28323         lock.l_whence = SEEK_SET;
28324         lock.l_start = SHARED_FIRST;
28325         lock.l_len = SHARED_SIZE;
28326         if( unixFileLock(pFile, &lock) ){
28327           /* In theory, the call to unixFileLock() cannot fail because another
28328           ** process is holding an incompatible lock. If it does, this 
28329           ** indicates that the other process is not following the locking
28330           ** protocol. If this happens, return SQLCIPHER_IOERR_RDLOCK. Returning
28331           ** SQLCIPHER_BUSY would confuse the upper layer (in practice it causes 
28332           ** an assert to fail). */ 
28333           rc = SQLCIPHER_IOERR_RDLOCK;
28334           pFile->lastErrno = errno;
28335           goto end_unlock;
28336         }
28337       }
28338     }
28339     lock.l_type = F_UNLCK;
28340     lock.l_whence = SEEK_SET;
28341     lock.l_start = PENDING_BYTE;
28342     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
28343     if( unixFileLock(pFile, &lock)==0 ){
28344       pInode->eFileLock = SHARED_LOCK;
28345     }else{
28346       rc = SQLCIPHER_IOERR_UNLOCK;
28347       pFile->lastErrno = errno;
28348       goto end_unlock;
28349     }
28350   }
28351   if( eFileLock==NO_LOCK ){
28352     /* Decrement the shared lock counter.  Release the lock using an
28353     ** OS call only when all threads in this same process have released
28354     ** the lock.
28355     */
28356     pInode->nShared--;
28357     if( pInode->nShared==0 ){
28358       lock.l_type = F_UNLCK;
28359       lock.l_whence = SEEK_SET;
28360       lock.l_start = lock.l_len = 0L;
28361       if( unixFileLock(pFile, &lock)==0 ){
28362         pInode->eFileLock = NO_LOCK;
28363       }else{
28364         rc = SQLCIPHER_IOERR_UNLOCK;
28365         pFile->lastErrno = errno;
28366         pInode->eFileLock = NO_LOCK;
28367         pFile->eFileLock = NO_LOCK;
28368       }
28369     }
28370
28371     /* Decrement the count of locks against this same file.  When the
28372     ** count reaches zero, close any other file descriptors whose close
28373     ** was deferred because of outstanding locks.
28374     */
28375     pInode->nLock--;
28376     assert( pInode->nLock>=0 );
28377     if( pInode->nLock==0 ){
28378       closePendingFds(pFile);
28379     }
28380   }
28381         
28382 end_unlock:
28383   unixLeaveMutex();
28384   if( rc==SQLCIPHER_OK ) pFile->eFileLock = eFileLock;
28385   return rc;
28386 }
28387
28388 /*
28389 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28390 ** must be either NO_LOCK or SHARED_LOCK.
28391 **
28392 ** If the locking level of the file descriptor is already at or below
28393 ** the requested locking level, this routine is a no-op.
28394 */
28395 static int unixUnlock(sqlcipher3_file *id, int eFileLock){
28396   return posixUnlock(id, eFileLock, 0);
28397 }
28398
28399 /*
28400 ** This function performs the parts of the "close file" operation 
28401 ** common to all locking schemes. It closes the directory and file
28402 ** handles, if they are valid, and sets all fields of the unixFile
28403 ** structure to 0.
28404 **
28405 ** It is *not* necessary to hold the mutex when this routine is called,
28406 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
28407 ** vxworksReleaseFileId() routine.
28408 */
28409 static int closeUnixFile(sqlcipher3_file *id){
28410   unixFile *pFile = (unixFile*)id;
28411   if( pFile->h>=0 ){
28412     robust_close(pFile, pFile->h, __LINE__);
28413     pFile->h = -1;
28414   }
28415 #if OS_VXWORKS
28416   if( pFile->pId ){
28417     if( pFile->isDelete ){
28418       osUnlink(pFile->pId->zCanonicalName);
28419     }
28420     vxworksReleaseFileId(pFile->pId);
28421     pFile->pId = 0;
28422   }
28423 #endif
28424   OSTRACE(("CLOSE   %-3d\n", pFile->h));
28425   OpenCounter(-1);
28426   sqlcipher3_free(pFile->pUnused);
28427   memset(pFile, 0, sizeof(unixFile));
28428   return SQLCIPHER_OK;
28429 }
28430
28431 /*
28432 ** Close a file.
28433 */
28434 static int unixClose(sqlcipher3_file *id){
28435   int rc = SQLCIPHER_OK;
28436   unixFile *pFile = (unixFile *)id;
28437   unixUnlock(id, NO_LOCK);
28438   unixEnterMutex();
28439
28440   /* unixFile.pInode is always valid here. Otherwise, a different close
28441   ** routine (e.g. nolockClose()) would be called instead.
28442   */
28443   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
28444   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
28445     /* If there are outstanding locks, do not actually close the file just
28446     ** yet because that would clear those locks.  Instead, add the file
28447     ** descriptor to pInode->pUnused list.  It will be automatically closed 
28448     ** when the last lock is cleared.
28449     */
28450     setPendingFd(pFile);
28451   }
28452   releaseInodeInfo(pFile);
28453   rc = closeUnixFile(id);
28454   unixLeaveMutex();
28455   return rc;
28456 }
28457
28458 /************** End of the posix advisory lock implementation *****************
28459 ******************************************************************************/
28460
28461 /******************************************************************************
28462 ****************************** No-op Locking **********************************
28463 **
28464 ** Of the various locking implementations available, this is by far the
28465 ** simplest:  locking is ignored.  No attempt is made to lock the database
28466 ** file for reading or writing.
28467 **
28468 ** This locking mode is appropriate for use on read-only databases
28469 ** (ex: databases that are burned into CD-ROM, for example.)  It can
28470 ** also be used if the application employs some external mechanism to
28471 ** prevent simultaneous access of the same database by two or more
28472 ** database connections.  But there is a serious risk of database
28473 ** corruption if this locking mode is used in situations where multiple
28474 ** database connections are accessing the same database file at the same
28475 ** time and one or more of those connections are writing.
28476 */
28477
28478 static int nolockCheckReservedLock(sqlcipher3_file *NotUsed, int *pResOut){
28479   UNUSED_PARAMETER(NotUsed);
28480   *pResOut = 0;
28481   return SQLCIPHER_OK;
28482 }
28483 static int nolockLock(sqlcipher3_file *NotUsed, int NotUsed2){
28484   UNUSED_PARAMETER2(NotUsed, NotUsed2);
28485   return SQLCIPHER_OK;
28486 }
28487 static int nolockUnlock(sqlcipher3_file *NotUsed, int NotUsed2){
28488   UNUSED_PARAMETER2(NotUsed, NotUsed2);
28489   return SQLCIPHER_OK;
28490 }
28491
28492 /*
28493 ** Close the file.
28494 */
28495 static int nolockClose(sqlcipher3_file *id) {
28496   return closeUnixFile(id);
28497 }
28498
28499 /******************* End of the no-op lock implementation *********************
28500 ******************************************************************************/
28501
28502 /******************************************************************************
28503 ************************* Begin dot-file Locking ******************************
28504 **
28505 ** The dotfile locking implementation uses the existance of separate lock
28506 ** files in order to control access to the database.  This works on just
28507 ** about every filesystem imaginable.  But there are serious downsides:
28508 **
28509 **    (1)  There is zero concurrency.  A single reader blocks all other
28510 **         connections from reading or writing the database.
28511 **
28512 **    (2)  An application crash or power loss can leave stale lock files
28513 **         sitting around that need to be cleared manually.
28514 **
28515 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
28516 ** other locking strategy is available.
28517 **
28518 ** Dotfile locking works by creating a file in the same directory as the
28519 ** database and with the same name but with a ".lock" extension added.
28520 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
28521 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
28522 */
28523
28524 /*
28525 ** The file suffix added to the data base filename in order to create the
28526 ** lock file.
28527 */
28528 #define DOTLOCK_SUFFIX ".lock"
28529
28530 /*
28531 ** This routine checks if there is a RESERVED lock held on the specified
28532 ** file by this or any other process. If such a lock is held, set *pResOut
28533 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28534 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
28535 **
28536 ** In dotfile locking, either a lock exists or it does not.  So in this
28537 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
28538 ** is held on the file and false if the file is unlocked.
28539 */
28540 static int dotlockCheckReservedLock(sqlcipher3_file *id, int *pResOut) {
28541   int rc = SQLCIPHER_OK;
28542   int reserved = 0;
28543   unixFile *pFile = (unixFile*)id;
28544
28545   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
28546   
28547   assert( pFile );
28548
28549   /* Check if a thread in this process holds such a lock */
28550   if( pFile->eFileLock>SHARED_LOCK ){
28551     /* Either this connection or some other connection in the same process
28552     ** holds a lock on the file.  No need to check further. */
28553     reserved = 1;
28554   }else{
28555     /* The lock is held if and only if the lockfile exists */
28556     const char *zLockFile = (const char*)pFile->lockingContext;
28557     reserved = osAccess(zLockFile, 0)==0;
28558   }
28559   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
28560   *pResOut = reserved;
28561   return rc;
28562 }
28563
28564 /*
28565 ** Lock the file with the lock specified by parameter eFileLock - one
28566 ** of the following:
28567 **
28568 **     (1) SHARED_LOCK
28569 **     (2) RESERVED_LOCK
28570 **     (3) PENDING_LOCK
28571 **     (4) EXCLUSIVE_LOCK
28572 **
28573 ** Sometimes when requesting one lock state, additional lock states
28574 ** are inserted in between.  The locking might fail on one of the later
28575 ** transitions leaving the lock state different from what it started but
28576 ** still short of its goal.  The following chart shows the allowed
28577 ** transitions and the inserted intermediate states:
28578 **
28579 **    UNLOCKED -> SHARED
28580 **    SHARED -> RESERVED
28581 **    SHARED -> (PENDING) -> EXCLUSIVE
28582 **    RESERVED -> (PENDING) -> EXCLUSIVE
28583 **    PENDING -> EXCLUSIVE
28584 **
28585 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
28586 ** routine to lower a locking level.
28587 **
28588 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
28589 ** But we track the other locking levels internally.
28590 */
28591 static int dotlockLock(sqlcipher3_file *id, int eFileLock) {
28592   unixFile *pFile = (unixFile*)id;
28593   int fd;
28594   char *zLockFile = (char *)pFile->lockingContext;
28595   int rc = SQLCIPHER_OK;
28596
28597
28598   /* If we have any lock, then the lock file already exists.  All we have
28599   ** to do is adjust our internal record of the lock level.
28600   */
28601   if( pFile->eFileLock > NO_LOCK ){
28602     pFile->eFileLock = eFileLock;
28603     /* Always update the timestamp on the old file */
28604 #ifdef HAVE_UTIME
28605     utime(zLockFile, NULL);
28606 #else
28607     utimes(zLockFile, NULL);
28608 #endif
28609     return SQLCIPHER_OK;
28610   }
28611   
28612   /* grab an exclusive lock */
28613   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
28614   if( fd<0 ){
28615     /* failed to open/create the file, someone else may have stolen the lock */
28616     int tErrno = errno;
28617     if( EEXIST == tErrno ){
28618       rc = SQLCIPHER_BUSY;
28619     } else {
28620       rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28621       if( IS_LOCK_ERROR(rc) ){
28622         pFile->lastErrno = tErrno;
28623       }
28624     }
28625     return rc;
28626   } 
28627   robust_close(pFile, fd, __LINE__);
28628   
28629   /* got it, set the type and return ok */
28630   pFile->eFileLock = eFileLock;
28631   return rc;
28632 }
28633
28634 /*
28635 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28636 ** must be either NO_LOCK or SHARED_LOCK.
28637 **
28638 ** If the locking level of the file descriptor is already at or below
28639 ** the requested locking level, this routine is a no-op.
28640 **
28641 ** When the locking level reaches NO_LOCK, delete the lock file.
28642 */
28643 static int dotlockUnlock(sqlcipher3_file *id, int eFileLock) {
28644   unixFile *pFile = (unixFile*)id;
28645   char *zLockFile = (char *)pFile->lockingContext;
28646
28647   assert( pFile );
28648   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
28649            pFile->eFileLock, getpid()));
28650   assert( eFileLock<=SHARED_LOCK );
28651   
28652   /* no-op if possible */
28653   if( pFile->eFileLock==eFileLock ){
28654     return SQLCIPHER_OK;
28655   }
28656
28657   /* To downgrade to shared, simply update our internal notion of the
28658   ** lock state.  No need to mess with the file on disk.
28659   */
28660   if( eFileLock==SHARED_LOCK ){
28661     pFile->eFileLock = SHARED_LOCK;
28662     return SQLCIPHER_OK;
28663   }
28664   
28665   /* To fully unlock the database, delete the lock file */
28666   assert( eFileLock==NO_LOCK );
28667   if( osUnlink(zLockFile) ){
28668     int rc = 0;
28669     int tErrno = errno;
28670     if( ENOENT != tErrno ){
28671       rc = SQLCIPHER_IOERR_UNLOCK;
28672     }
28673     if( IS_LOCK_ERROR(rc) ){
28674       pFile->lastErrno = tErrno;
28675     }
28676     return rc; 
28677   }
28678   pFile->eFileLock = NO_LOCK;
28679   return SQLCIPHER_OK;
28680 }
28681
28682 /*
28683 ** Close a file.  Make sure the lock has been released before closing.
28684 */
28685 static int dotlockClose(sqlcipher3_file *id) {
28686   int rc;
28687   if( id ){
28688     unixFile *pFile = (unixFile*)id;
28689     dotlockUnlock(id, NO_LOCK);
28690     sqlcipher3_free(pFile->lockingContext);
28691   }
28692   rc = closeUnixFile(id);
28693   return rc;
28694 }
28695 /****************** End of the dot-file lock implementation *******************
28696 ******************************************************************************/
28697
28698 /******************************************************************************
28699 ************************** Begin flock Locking ********************************
28700 **
28701 ** Use the flock() system call to do file locking.
28702 **
28703 ** flock() locking is like dot-file locking in that the various
28704 ** fine-grain locking levels supported by SQLite are collapsed into
28705 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
28706 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
28707 ** still works when you do this, but concurrency is reduced since
28708 ** only a single process can be reading the database at a time.
28709 **
28710 ** Omit this section if SQLCIPHER_ENABLE_LOCKING_STYLE is turned off or if
28711 ** compiling for VXWORKS.
28712 */
28713 #if SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28714
28715 /*
28716 ** Retry flock() calls that fail with EINTR
28717 */
28718 #ifdef EINTR
28719 static int robust_flock(int fd, int op){
28720   int rc;
28721   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
28722   return rc;
28723 }
28724 #else
28725 # define robust_flock(a,b) flock(a,b)
28726 #endif
28727      
28728
28729 /*
28730 ** This routine checks if there is a RESERVED lock held on the specified
28731 ** file by this or any other process. If such a lock is held, set *pResOut
28732 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28733 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
28734 */
28735 static int flockCheckReservedLock(sqlcipher3_file *id, int *pResOut){
28736   int rc = SQLCIPHER_OK;
28737   int reserved = 0;
28738   unixFile *pFile = (unixFile*)id;
28739   
28740   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
28741   
28742   assert( pFile );
28743   
28744   /* Check if a thread in this process holds such a lock */
28745   if( pFile->eFileLock>SHARED_LOCK ){
28746     reserved = 1;
28747   }
28748   
28749   /* Otherwise see if some other process holds it. */
28750   if( !reserved ){
28751     /* attempt to get the lock */
28752     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
28753     if( !lrc ){
28754       /* got the lock, unlock it */
28755       lrc = robust_flock(pFile->h, LOCK_UN);
28756       if ( lrc ) {
28757         int tErrno = errno;
28758         /* unlock failed with an error */
28759         lrc = SQLCIPHER_IOERR_UNLOCK; 
28760         if( IS_LOCK_ERROR(lrc) ){
28761           pFile->lastErrno = tErrno;
28762           rc = lrc;
28763         }
28764       }
28765     } else {
28766       int tErrno = errno;
28767       reserved = 1;
28768       /* someone else might have it reserved */
28769       lrc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK); 
28770       if( IS_LOCK_ERROR(lrc) ){
28771         pFile->lastErrno = tErrno;
28772         rc = lrc;
28773       }
28774     }
28775   }
28776   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
28777
28778 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
28779   if( (rc & SQLCIPHER_IOERR) == SQLCIPHER_IOERR ){
28780     rc = SQLCIPHER_OK;
28781     reserved=1;
28782   }
28783 #endif /* SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS */
28784   *pResOut = reserved;
28785   return rc;
28786 }
28787
28788 /*
28789 ** Lock the file with the lock specified by parameter eFileLock - one
28790 ** of the following:
28791 **
28792 **     (1) SHARED_LOCK
28793 **     (2) RESERVED_LOCK
28794 **     (3) PENDING_LOCK
28795 **     (4) EXCLUSIVE_LOCK
28796 **
28797 ** Sometimes when requesting one lock state, additional lock states
28798 ** are inserted in between.  The locking might fail on one of the later
28799 ** transitions leaving the lock state different from what it started but
28800 ** still short of its goal.  The following chart shows the allowed
28801 ** transitions and the inserted intermediate states:
28802 **
28803 **    UNLOCKED -> SHARED
28804 **    SHARED -> RESERVED
28805 **    SHARED -> (PENDING) -> EXCLUSIVE
28806 **    RESERVED -> (PENDING) -> EXCLUSIVE
28807 **    PENDING -> EXCLUSIVE
28808 **
28809 ** flock() only really support EXCLUSIVE locks.  We track intermediate
28810 ** lock states in the sqlcipher3_file structure, but all locks SHARED or
28811 ** above are really EXCLUSIVE locks and exclude all other processes from
28812 ** access the file.
28813 **
28814 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
28815 ** routine to lower a locking level.
28816 */
28817 static int flockLock(sqlcipher3_file *id, int eFileLock) {
28818   int rc = SQLCIPHER_OK;
28819   unixFile *pFile = (unixFile*)id;
28820
28821   assert( pFile );
28822
28823   /* if we already have a lock, it is exclusive.  
28824   ** Just adjust level and punt on outta here. */
28825   if (pFile->eFileLock > NO_LOCK) {
28826     pFile->eFileLock = eFileLock;
28827     return SQLCIPHER_OK;
28828   }
28829   
28830   /* grab an exclusive lock */
28831   
28832   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
28833     int tErrno = errno;
28834     /* didn't get, must be busy */
28835     rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_LOCK);
28836     if( IS_LOCK_ERROR(rc) ){
28837       pFile->lastErrno = tErrno;
28838     }
28839   } else {
28840     /* got it, set the type and return ok */
28841     pFile->eFileLock = eFileLock;
28842   }
28843   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
28844            rc==SQLCIPHER_OK ? "ok" : "failed"));
28845 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
28846   if( (rc & SQLCIPHER_IOERR) == SQLCIPHER_IOERR ){
28847     rc = SQLCIPHER_BUSY;
28848   }
28849 #endif /* SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS */
28850   return rc;
28851 }
28852
28853
28854 /*
28855 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28856 ** must be either NO_LOCK or SHARED_LOCK.
28857 **
28858 ** If the locking level of the file descriptor is already at or below
28859 ** the requested locking level, this routine is a no-op.
28860 */
28861 static int flockUnlock(sqlcipher3_file *id, int eFileLock) {
28862   unixFile *pFile = (unixFile*)id;
28863   
28864   assert( pFile );
28865   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
28866            pFile->eFileLock, getpid()));
28867   assert( eFileLock<=SHARED_LOCK );
28868   
28869   /* no-op if possible */
28870   if( pFile->eFileLock==eFileLock ){
28871     return SQLCIPHER_OK;
28872   }
28873   
28874   /* shared can just be set because we always have an exclusive */
28875   if (eFileLock==SHARED_LOCK) {
28876     pFile->eFileLock = eFileLock;
28877     return SQLCIPHER_OK;
28878   }
28879   
28880   /* no, really, unlock. */
28881   if( robust_flock(pFile->h, LOCK_UN) ){
28882 #ifdef SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS
28883     return SQLCIPHER_OK;
28884 #endif /* SQLCIPHER_IGNORE_FLOCK_LOCK_ERRORS */
28885     return SQLCIPHER_IOERR_UNLOCK;
28886   }else{
28887     pFile->eFileLock = NO_LOCK;
28888     return SQLCIPHER_OK;
28889   }
28890 }
28891
28892 /*
28893 ** Close a file.
28894 */
28895 static int flockClose(sqlcipher3_file *id) {
28896   if( id ){
28897     flockUnlock(id, NO_LOCK);
28898   }
28899   return closeUnixFile(id);
28900 }
28901
28902 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORK */
28903
28904 /******************* End of the flock lock implementation *********************
28905 ******************************************************************************/
28906
28907 /******************************************************************************
28908 ************************ Begin Named Semaphore Locking ************************
28909 **
28910 ** Named semaphore locking is only supported on VxWorks.
28911 **
28912 ** Semaphore locking is like dot-lock and flock in that it really only
28913 ** supports EXCLUSIVE locking.  Only a single process can read or write
28914 ** the database file at a time.  This reduces potential concurrency, but
28915 ** makes the lock implementation much easier.
28916 */
28917 #if OS_VXWORKS
28918
28919 /*
28920 ** This routine checks if there is a RESERVED lock held on the specified
28921 ** file by this or any other process. If such a lock is held, set *pResOut
28922 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28923 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
28924 */
28925 static int semCheckReservedLock(sqlcipher3_file *id, int *pResOut) {
28926   int rc = SQLCIPHER_OK;
28927   int reserved = 0;
28928   unixFile *pFile = (unixFile*)id;
28929
28930   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
28931   
28932   assert( pFile );
28933
28934   /* Check if a thread in this process holds such a lock */
28935   if( pFile->eFileLock>SHARED_LOCK ){
28936     reserved = 1;
28937   }
28938   
28939   /* Otherwise see if some other process holds it. */
28940   if( !reserved ){
28941     sem_t *pSem = pFile->pInode->pSem;
28942     struct stat statBuf;
28943
28944     if( sem_trywait(pSem)==-1 ){
28945       int tErrno = errno;
28946       if( EAGAIN != tErrno ){
28947         rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_CHECKRESERVEDLOCK);
28948         pFile->lastErrno = tErrno;
28949       } else {
28950         /* someone else has the lock when we are in NO_LOCK */
28951         reserved = (pFile->eFileLock < SHARED_LOCK);
28952       }
28953     }else{
28954       /* we could have it if we want it */
28955       sem_post(pSem);
28956     }
28957   }
28958   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
28959
28960   *pResOut = reserved;
28961   return rc;
28962 }
28963
28964 /*
28965 ** Lock the file with the lock specified by parameter eFileLock - one
28966 ** of the following:
28967 **
28968 **     (1) SHARED_LOCK
28969 **     (2) RESERVED_LOCK
28970 **     (3) PENDING_LOCK
28971 **     (4) EXCLUSIVE_LOCK
28972 **
28973 ** Sometimes when requesting one lock state, additional lock states
28974 ** are inserted in between.  The locking might fail on one of the later
28975 ** transitions leaving the lock state different from what it started but
28976 ** still short of its goal.  The following chart shows the allowed
28977 ** transitions and the inserted intermediate states:
28978 **
28979 **    UNLOCKED -> SHARED
28980 **    SHARED -> RESERVED
28981 **    SHARED -> (PENDING) -> EXCLUSIVE
28982 **    RESERVED -> (PENDING) -> EXCLUSIVE
28983 **    PENDING -> EXCLUSIVE
28984 **
28985 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
28986 ** lock states in the sqlcipher3_file structure, but all locks SHARED or
28987 ** above are really EXCLUSIVE locks and exclude all other processes from
28988 ** access the file.
28989 **
28990 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
28991 ** routine to lower a locking level.
28992 */
28993 static int semLock(sqlcipher3_file *id, int eFileLock) {
28994   unixFile *pFile = (unixFile*)id;
28995   int fd;
28996   sem_t *pSem = pFile->pInode->pSem;
28997   int rc = SQLCIPHER_OK;
28998
28999   /* if we already have a lock, it is exclusive.  
29000   ** Just adjust level and punt on outta here. */
29001   if (pFile->eFileLock > NO_LOCK) {
29002     pFile->eFileLock = eFileLock;
29003     rc = SQLCIPHER_OK;
29004     goto sem_end_lock;
29005   }
29006   
29007   /* lock semaphore now but bail out when already locked. */
29008   if( sem_trywait(pSem)==-1 ){
29009     rc = SQLCIPHER_BUSY;
29010     goto sem_end_lock;
29011   }
29012
29013   /* got it, set the type and return ok */
29014   pFile->eFileLock = eFileLock;
29015
29016  sem_end_lock:
29017   return rc;
29018 }
29019
29020 /*
29021 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29022 ** must be either NO_LOCK or SHARED_LOCK.
29023 **
29024 ** If the locking level of the file descriptor is already at or below
29025 ** the requested locking level, this routine is a no-op.
29026 */
29027 static int semUnlock(sqlcipher3_file *id, int eFileLock) {
29028   unixFile *pFile = (unixFile*)id;
29029   sem_t *pSem = pFile->pInode->pSem;
29030
29031   assert( pFile );
29032   assert( pSem );
29033   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
29034            pFile->eFileLock, getpid()));
29035   assert( eFileLock<=SHARED_LOCK );
29036   
29037   /* no-op if possible */
29038   if( pFile->eFileLock==eFileLock ){
29039     return SQLCIPHER_OK;
29040   }
29041   
29042   /* shared can just be set because we always have an exclusive */
29043   if (eFileLock==SHARED_LOCK) {
29044     pFile->eFileLock = eFileLock;
29045     return SQLCIPHER_OK;
29046   }
29047   
29048   /* no, really unlock. */
29049   if ( sem_post(pSem)==-1 ) {
29050     int rc, tErrno = errno;
29051     rc = sqlcipherErrorFromPosixError(tErrno, SQLCIPHER_IOERR_UNLOCK);
29052     if( IS_LOCK_ERROR(rc) ){
29053       pFile->lastErrno = tErrno;
29054     }
29055     return rc; 
29056   }
29057   pFile->eFileLock = NO_LOCK;
29058   return SQLCIPHER_OK;
29059 }
29060
29061 /*
29062  ** Close a file.
29063  */
29064 static int semClose(sqlcipher3_file *id) {
29065   if( id ){
29066     unixFile *pFile = (unixFile*)id;
29067     semUnlock(id, NO_LOCK);
29068     assert( pFile );
29069     unixEnterMutex();
29070     releaseInodeInfo(pFile);
29071     unixLeaveMutex();
29072     closeUnixFile(id);
29073   }
29074   return SQLCIPHER_OK;
29075 }
29076
29077 #endif /* OS_VXWORKS */
29078 /*
29079 ** Named semaphore locking is only available on VxWorks.
29080 **
29081 *************** End of the named semaphore lock implementation ****************
29082 ******************************************************************************/
29083
29084
29085 /******************************************************************************
29086 *************************** Begin AFP Locking *********************************
29087 **
29088 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
29089 ** on Apple Macintosh computers - both OS9 and OSX.
29090 **
29091 ** Third-party implementations of AFP are available.  But this code here
29092 ** only works on OSX.
29093 */
29094
29095 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
29096 /*
29097 ** The afpLockingContext structure contains all afp lock specific state
29098 */
29099 typedef struct afpLockingContext afpLockingContext;
29100 struct afpLockingContext {
29101   int reserved;
29102   const char *dbPath;             /* Name of the open file */
29103 };
29104
29105 struct ByteRangeLockPB2
29106 {
29107   unsigned long long offset;        /* offset to first byte to lock */
29108   unsigned long long length;        /* nbr of bytes to lock */
29109   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
29110   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
29111   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
29112   int fd;                           /* file desc to assoc this lock with */
29113 };
29114
29115 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
29116
29117 /*
29118 ** This is a utility for setting or clearing a bit-range lock on an
29119 ** AFP filesystem.
29120 ** 
29121 ** Return SQLCIPHER_OK on success, SQLCIPHER_BUSY on failure.
29122 */
29123 static int afpSetLock(
29124   const char *path,              /* Name of the file to be locked or unlocked */
29125   unixFile *pFile,               /* Open file descriptor on path */
29126   unsigned long long offset,     /* First byte to be locked */
29127   unsigned long long length,     /* Number of bytes to lock */
29128   int setLockFlag                /* True to set lock.  False to clear lock */
29129 ){
29130   struct ByteRangeLockPB2 pb;
29131   int err;
29132   
29133   pb.unLockFlag = setLockFlag ? 0 : 1;
29134   pb.startEndFlag = 0;
29135   pb.offset = offset;
29136   pb.length = length; 
29137   pb.fd = pFile->h;
29138   
29139   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
29140     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
29141     offset, length));
29142   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
29143   if ( err==-1 ) {
29144     int rc;
29145     int tErrno = errno;
29146     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
29147              path, tErrno, strerror(tErrno)));
29148 #ifdef SQLCIPHER_IGNORE_AFP_LOCK_ERRORS
29149     rc = SQLCIPHER_BUSY;
29150 #else
29151     rc = sqlcipherErrorFromPosixError(tErrno,
29152                     setLockFlag ? SQLCIPHER_IOERR_LOCK : SQLCIPHER_IOERR_UNLOCK);
29153 #endif /* SQLCIPHER_IGNORE_AFP_LOCK_ERRORS */
29154     if( IS_LOCK_ERROR(rc) ){
29155       pFile->lastErrno = tErrno;
29156     }
29157     return rc;
29158   } else {
29159     return SQLCIPHER_OK;
29160   }
29161 }
29162
29163 /*
29164 ** This routine checks if there is a RESERVED lock held on the specified
29165 ** file by this or any other process. If such a lock is held, set *pResOut
29166 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29167 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
29168 */
29169 static int afpCheckReservedLock(sqlcipher3_file *id, int *pResOut){
29170   int rc = SQLCIPHER_OK;
29171   int reserved = 0;
29172   unixFile *pFile = (unixFile*)id;
29173   afpLockingContext *context;
29174   
29175   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
29176   
29177   assert( pFile );
29178   context = (afpLockingContext *) pFile->lockingContext;
29179   if( context->reserved ){
29180     *pResOut = 1;
29181     return SQLCIPHER_OK;
29182   }
29183   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
29184   
29185   /* Check if a thread in this process holds such a lock */
29186   if( pFile->pInode->eFileLock>SHARED_LOCK ){
29187     reserved = 1;
29188   }
29189   
29190   /* Otherwise see if some other process holds it.
29191    */
29192   if( !reserved ){
29193     /* lock the RESERVED byte */
29194     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
29195     if( SQLCIPHER_OK==lrc ){
29196       /* if we succeeded in taking the reserved lock, unlock it to restore
29197       ** the original state */
29198       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29199     } else {
29200       /* if we failed to get the lock then someone else must have it */
29201       reserved = 1;
29202     }
29203     if( IS_LOCK_ERROR(lrc) ){
29204       rc=lrc;
29205     }
29206   }
29207   
29208   unixLeaveMutex();
29209   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
29210   
29211   *pResOut = reserved;
29212   return rc;
29213 }
29214
29215 /*
29216 ** Lock the file with the lock specified by parameter eFileLock - one
29217 ** of the following:
29218 **
29219 **     (1) SHARED_LOCK
29220 **     (2) RESERVED_LOCK
29221 **     (3) PENDING_LOCK
29222 **     (4) EXCLUSIVE_LOCK
29223 **
29224 ** Sometimes when requesting one lock state, additional lock states
29225 ** are inserted in between.  The locking might fail on one of the later
29226 ** transitions leaving the lock state different from what it started but
29227 ** still short of its goal.  The following chart shows the allowed
29228 ** transitions and the inserted intermediate states:
29229 **
29230 **    UNLOCKED -> SHARED
29231 **    SHARED -> RESERVED
29232 **    SHARED -> (PENDING) -> EXCLUSIVE
29233 **    RESERVED -> (PENDING) -> EXCLUSIVE
29234 **    PENDING -> EXCLUSIVE
29235 **
29236 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
29237 ** routine to lower a locking level.
29238 */
29239 static int afpLock(sqlcipher3_file *id, int eFileLock){
29240   int rc = SQLCIPHER_OK;
29241   unixFile *pFile = (unixFile*)id;
29242   unixInodeInfo *pInode = pFile->pInode;
29243   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29244   
29245   assert( pFile );
29246   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
29247            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
29248            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
29249
29250   /* If there is already a lock of this type or more restrictive on the
29251   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
29252   ** unixEnterMutex() hasn't been called yet.
29253   */
29254   if( pFile->eFileLock>=eFileLock ){
29255     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
29256            azFileLock(eFileLock)));
29257     return SQLCIPHER_OK;
29258   }
29259
29260   /* Make sure the locking sequence is correct
29261   **  (1) We never move from unlocked to anything higher than shared lock.
29262   **  (2) SQLite never explicitly requests a pendig lock.
29263   **  (3) A shared lock is always held when a reserve lock is requested.
29264   */
29265   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
29266   assert( eFileLock!=PENDING_LOCK );
29267   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
29268   
29269   /* This mutex is needed because pFile->pInode is shared across threads
29270   */
29271   unixEnterMutex();
29272   pInode = pFile->pInode;
29273
29274   /* If some thread using this PID has a lock via a different unixFile*
29275   ** handle that precludes the requested lock, return BUSY.
29276   */
29277   if( (pFile->eFileLock!=pInode->eFileLock && 
29278        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
29279      ){
29280     rc = SQLCIPHER_BUSY;
29281     goto afp_end_lock;
29282   }
29283   
29284   /* If a SHARED lock is requested, and some thread using this PID already
29285   ** has a SHARED or RESERVED lock, then increment reference counts and
29286   ** return SQLCIPHER_OK.
29287   */
29288   if( eFileLock==SHARED_LOCK && 
29289      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
29290     assert( eFileLock==SHARED_LOCK );
29291     assert( pFile->eFileLock==0 );
29292     assert( pInode->nShared>0 );
29293     pFile->eFileLock = SHARED_LOCK;
29294     pInode->nShared++;
29295     pInode->nLock++;
29296     goto afp_end_lock;
29297   }
29298     
29299   /* A PENDING lock is needed before acquiring a SHARED lock and before
29300   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
29301   ** be released.
29302   */
29303   if( eFileLock==SHARED_LOCK 
29304       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
29305   ){
29306     int failed;
29307     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
29308     if (failed) {
29309       rc = failed;
29310       goto afp_end_lock;
29311     }
29312   }
29313   
29314   /* If control gets to this point, then actually go ahead and make
29315   ** operating system calls for the specified lock.
29316   */
29317   if( eFileLock==SHARED_LOCK ){
29318     int lrc1, lrc2, lrc1Errno = 0;
29319     long lk, mask;
29320     
29321     assert( pInode->nShared==0 );
29322     assert( pInode->eFileLock==0 );
29323         
29324     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
29325     /* Now get the read-lock SHARED_LOCK */
29326     /* note that the quality of the randomness doesn't matter that much */
29327     lk = random(); 
29328     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
29329     lrc1 = afpSetLock(context->dbPath, pFile, 
29330           SHARED_FIRST+pInode->sharedByte, 1, 1);
29331     if( IS_LOCK_ERROR(lrc1) ){
29332       lrc1Errno = pFile->lastErrno;
29333     }
29334     /* Drop the temporary PENDING lock */
29335     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29336     
29337     if( IS_LOCK_ERROR(lrc1) ) {
29338       pFile->lastErrno = lrc1Errno;
29339       rc = lrc1;
29340       goto afp_end_lock;
29341     } else if( IS_LOCK_ERROR(lrc2) ){
29342       rc = lrc2;
29343       goto afp_end_lock;
29344     } else if( lrc1 != SQLCIPHER_OK ) {
29345       rc = lrc1;
29346     } else {
29347       pFile->eFileLock = SHARED_LOCK;
29348       pInode->nLock++;
29349       pInode->nShared = 1;
29350     }
29351   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
29352     /* We are trying for an exclusive lock but another thread in this
29353      ** same process is still holding a shared lock. */
29354     rc = SQLCIPHER_BUSY;
29355   }else{
29356     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
29357     ** assumed that there is a SHARED or greater lock on the file
29358     ** already.
29359     */
29360     int failed = 0;
29361     assert( 0!=pFile->eFileLock );
29362     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
29363         /* Acquire a RESERVED lock */
29364         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
29365       if( !failed ){
29366         context->reserved = 1;
29367       }
29368     }
29369     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
29370       /* Acquire an EXCLUSIVE lock */
29371         
29372       /* Remove the shared lock before trying the range.  we'll need to 
29373       ** reestablish the shared lock if we can't get the  afpUnlock
29374       */
29375       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
29376                          pInode->sharedByte, 1, 0)) ){
29377         int failed2 = SQLCIPHER_OK;
29378         /* now attemmpt to get the exclusive lock range */
29379         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
29380                                SHARED_SIZE, 1);
29381         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
29382                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
29383           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
29384           ** a critical I/O error
29385           */
29386           rc = ((failed & SQLCIPHER_IOERR) == SQLCIPHER_IOERR) ? failed2 : 
29387                SQLCIPHER_IOERR_LOCK;
29388           goto afp_end_lock;
29389         } 
29390       }else{
29391         rc = failed; 
29392       }
29393     }
29394     if( failed ){
29395       rc = failed;
29396     }
29397   }
29398   
29399   if( rc==SQLCIPHER_OK ){
29400     pFile->eFileLock = eFileLock;
29401     pInode->eFileLock = eFileLock;
29402   }else if( eFileLock==EXCLUSIVE_LOCK ){
29403     pFile->eFileLock = PENDING_LOCK;
29404     pInode->eFileLock = PENDING_LOCK;
29405   }
29406   
29407 afp_end_lock:
29408   unixLeaveMutex();
29409   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
29410          rc==SQLCIPHER_OK ? "ok" : "failed"));
29411   return rc;
29412 }
29413
29414 /*
29415 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29416 ** must be either NO_LOCK or SHARED_LOCK.
29417 **
29418 ** If the locking level of the file descriptor is already at or below
29419 ** the requested locking level, this routine is a no-op.
29420 */
29421 static int afpUnlock(sqlcipher3_file *id, int eFileLock) {
29422   int rc = SQLCIPHER_OK;
29423   unixFile *pFile = (unixFile*)id;
29424   unixInodeInfo *pInode;
29425   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29426   int skipShared = 0;
29427 #ifdef SQLCIPHER_TEST
29428   int h = pFile->h;
29429 #endif
29430
29431   assert( pFile );
29432   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
29433            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
29434            getpid()));
29435
29436   assert( eFileLock<=SHARED_LOCK );
29437   if( pFile->eFileLock<=eFileLock ){
29438     return SQLCIPHER_OK;
29439   }
29440   unixEnterMutex();
29441   pInode = pFile->pInode;
29442   assert( pInode->nShared!=0 );
29443   if( pFile->eFileLock>SHARED_LOCK ){
29444     assert( pInode->eFileLock==pFile->eFileLock );
29445     SimulateIOErrorBenign(1);
29446     SimulateIOError( h=(-1) )
29447     SimulateIOErrorBenign(0);
29448     
29449 #ifndef NDEBUG
29450     /* When reducing a lock such that other processes can start
29451     ** reading the database file again, make sure that the
29452     ** transaction counter was updated if any part of the database
29453     ** file changed.  If the transaction counter is not updated,
29454     ** other connections to the same file might not realize that
29455     ** the file has changed and hence might not know to flush their
29456     ** cache.  The use of a stale cache can lead to database corruption.
29457     */
29458     assert( pFile->inNormalWrite==0
29459            || pFile->dbUpdate==0
29460            || pFile->transCntrChng==1 );
29461     pFile->inNormalWrite = 0;
29462 #endif
29463     
29464     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
29465       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
29466       if( rc==SQLCIPHER_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
29467         /* only re-establish the shared lock if necessary */
29468         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29469         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
29470       } else {
29471         skipShared = 1;
29472       }
29473     }
29474     if( rc==SQLCIPHER_OK && pFile->eFileLock>=PENDING_LOCK ){
29475       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29476     } 
29477     if( rc==SQLCIPHER_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
29478       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29479       if( !rc ){ 
29480         context->reserved = 0; 
29481       }
29482     }
29483     if( rc==SQLCIPHER_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
29484       pInode->eFileLock = SHARED_LOCK;
29485     }
29486   }
29487   if( rc==SQLCIPHER_OK && eFileLock==NO_LOCK ){
29488
29489     /* Decrement the shared lock counter.  Release the lock using an
29490     ** OS call only when all threads in this same process have released
29491     ** the lock.
29492     */
29493     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29494     pInode->nShared--;
29495     if( pInode->nShared==0 ){
29496       SimulateIOErrorBenign(1);
29497       SimulateIOError( h=(-1) )
29498       SimulateIOErrorBenign(0);
29499       if( !skipShared ){
29500         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
29501       }
29502       if( !rc ){
29503         pInode->eFileLock = NO_LOCK;
29504         pFile->eFileLock = NO_LOCK;
29505       }
29506     }
29507     if( rc==SQLCIPHER_OK ){
29508       pInode->nLock--;
29509       assert( pInode->nLock>=0 );
29510       if( pInode->nLock==0 ){
29511         closePendingFds(pFile);
29512       }
29513     }
29514   }
29515   
29516   unixLeaveMutex();
29517   if( rc==SQLCIPHER_OK ) pFile->eFileLock = eFileLock;
29518   return rc;
29519 }
29520
29521 /*
29522 ** Close a file & cleanup AFP specific locking context 
29523 */
29524 static int afpClose(sqlcipher3_file *id) {
29525   int rc = SQLCIPHER_OK;
29526   if( id ){
29527     unixFile *pFile = (unixFile*)id;
29528     afpUnlock(id, NO_LOCK);
29529     unixEnterMutex();
29530     if( pFile->pInode && pFile->pInode->nLock ){
29531       /* If there are outstanding locks, do not actually close the file just
29532       ** yet because that would clear those locks.  Instead, add the file
29533       ** descriptor to pInode->aPending.  It will be automatically closed when
29534       ** the last lock is cleared.
29535       */
29536       setPendingFd(pFile);
29537     }
29538     releaseInodeInfo(pFile);
29539     sqlcipher3_free(pFile->lockingContext);
29540     rc = closeUnixFile(id);
29541     unixLeaveMutex();
29542   }
29543   return rc;
29544 }
29545
29546 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
29547 /*
29548 ** The code above is the AFP lock implementation.  The code is specific
29549 ** to MacOSX and does not work on other unix platforms.  No alternative
29550 ** is available.  If you don't compile for a mac, then the "unix-afp"
29551 ** VFS is not available.
29552 **
29553 ********************* End of the AFP lock implementation **********************
29554 ******************************************************************************/
29555
29556 /******************************************************************************
29557 *************************** Begin NFS Locking ********************************/
29558
29559 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
29560 /*
29561  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29562  ** must be either NO_LOCK or SHARED_LOCK.
29563  **
29564  ** If the locking level of the file descriptor is already at or below
29565  ** the requested locking level, this routine is a no-op.
29566  */
29567 static int nfsUnlock(sqlcipher3_file *id, int eFileLock){
29568   return posixUnlock(id, eFileLock, 1);
29569 }
29570
29571 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
29572 /*
29573 ** The code above is the NFS lock implementation.  The code is specific
29574 ** to MacOSX and does not work on other unix platforms.  No alternative
29575 ** is available.  
29576 **
29577 ********************* End of the NFS lock implementation **********************
29578 ******************************************************************************/
29579
29580 /******************************************************************************
29581 **************** Non-locking sqlcipher3_file methods *****************************
29582 **
29583 ** The next division contains implementations for all methods of the 
29584 ** sqlcipher3_file object other than the locking methods.  The locking
29585 ** methods were defined in divisions above (one locking method per
29586 ** division).  Those methods that are common to all locking modes
29587 ** are gather together into this division.
29588 */
29589
29590 /*
29591 ** Seek to the offset passed as the second argument, then read cnt 
29592 ** bytes into pBuf. Return the number of bytes actually read.
29593 **
29594 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
29595 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
29596 ** one system to another.  Since SQLite does not define USE_PREAD
29597 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
29598 ** See tickets #2741 and #2681.
29599 **
29600 ** To avoid stomping the errno value on a failed read the lastErrno value
29601 ** is set before returning.
29602 */
29603 static int seekAndRead(unixFile *id, sqlcipher3_int64 offset, void *pBuf, int cnt){
29604   int got;
29605 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
29606   i64 newOffset;
29607 #endif
29608   TIMER_START;
29609 #if defined(USE_PREAD)
29610   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
29611   SimulateIOError( got = -1 );
29612 #elif defined(USE_PREAD64)
29613   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
29614   SimulateIOError( got = -1 );
29615 #else
29616   newOffset = lseek(id->h, offset, SEEK_SET);
29617   SimulateIOError( newOffset-- );
29618   if( newOffset!=offset ){
29619     if( newOffset == -1 ){
29620       ((unixFile*)id)->lastErrno = errno;
29621     }else{
29622       ((unixFile*)id)->lastErrno = 0;                   
29623     }
29624     return -1;
29625   }
29626   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
29627 #endif
29628   TIMER_END;
29629   if( got<0 ){
29630     ((unixFile*)id)->lastErrno = errno;
29631   }
29632   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
29633   return got;
29634 }
29635
29636 /*
29637 ** Read data from a file into a buffer.  Return SQLCIPHER_OK if all
29638 ** bytes were read successfully and SQLCIPHER_IOERR if anything goes
29639 ** wrong.
29640 */
29641 static int unixRead(
29642   sqlcipher3_file *id, 
29643   void *pBuf, 
29644   int amt,
29645   sqlcipher3_int64 offset
29646 ){
29647   unixFile *pFile = (unixFile *)id;
29648   int got;
29649   assert( id );
29650
29651   /* If this is a database file (not a journal, master-journal or temp
29652   ** file), the bytes in the locking range should never be read or written. */
29653 #if 0
29654   assert( pFile->pUnused==0
29655        || offset>=PENDING_BYTE+512
29656        || offset+amt<=PENDING_BYTE 
29657   );
29658 #endif
29659
29660   got = seekAndRead(pFile, offset, pBuf, amt);
29661   if( got==amt ){
29662     return SQLCIPHER_OK;
29663   }else if( got<0 ){
29664     /* lastErrno set by seekAndRead */
29665     return SQLCIPHER_IOERR_READ;
29666   }else{
29667     pFile->lastErrno = 0; /* not a system error */
29668     /* Unread parts of the buffer must be zero-filled */
29669     memset(&((char*)pBuf)[got], 0, amt-got);
29670     return SQLCIPHER_IOERR_SHORT_READ;
29671   }
29672 }
29673
29674 /*
29675 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
29676 ** Return the number of bytes actually read.  Update the offset.
29677 **
29678 ** To avoid stomping the errno value on a failed write the lastErrno value
29679 ** is set before returning.
29680 */
29681 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
29682   int got;
29683 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
29684   i64 newOffset;
29685 #endif
29686   TIMER_START;
29687 #if defined(USE_PREAD)
29688   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
29689 #elif defined(USE_PREAD64)
29690   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
29691 #else
29692   do{
29693     newOffset = lseek(id->h, offset, SEEK_SET);
29694     SimulateIOError( newOffset-- );
29695     if( newOffset!=offset ){
29696       if( newOffset == -1 ){
29697         ((unixFile*)id)->lastErrno = errno;
29698       }else{
29699         ((unixFile*)id)->lastErrno = 0;                 
29700       }
29701       return -1;
29702     }
29703     got = osWrite(id->h, pBuf, cnt);
29704   }while( got<0 && errno==EINTR );
29705 #endif
29706   TIMER_END;
29707   if( got<0 ){
29708     ((unixFile*)id)->lastErrno = errno;
29709   }
29710
29711   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
29712   return got;
29713 }
29714
29715
29716 /*
29717 ** Write data from a buffer into a file.  Return SQLCIPHER_OK on success
29718 ** or some other error code on failure.
29719 */
29720 static int unixWrite(
29721   sqlcipher3_file *id, 
29722   const void *pBuf, 
29723   int amt,
29724   sqlcipher3_int64 offset 
29725 ){
29726   unixFile *pFile = (unixFile*)id;
29727   int wrote = 0;
29728   assert( id );
29729   assert( amt>0 );
29730
29731   /* If this is a database file (not a journal, master-journal or temp
29732   ** file), the bytes in the locking range should never be read or written. */
29733 #if 0
29734   assert( pFile->pUnused==0
29735        || offset>=PENDING_BYTE+512
29736        || offset+amt<=PENDING_BYTE 
29737   );
29738 #endif
29739
29740 #ifndef NDEBUG
29741   /* If we are doing a normal write to a database file (as opposed to
29742   ** doing a hot-journal rollback or a write to some file other than a
29743   ** normal database file) then record the fact that the database
29744   ** has changed.  If the transaction counter is modified, record that
29745   ** fact too.
29746   */
29747   if( pFile->inNormalWrite ){
29748     pFile->dbUpdate = 1;  /* The database has been modified */
29749     if( offset<=24 && offset+amt>=27 ){
29750       int rc;
29751       char oldCntr[4];
29752       SimulateIOErrorBenign(1);
29753       rc = seekAndRead(pFile, 24, oldCntr, 4);
29754       SimulateIOErrorBenign(0);
29755       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
29756         pFile->transCntrChng = 1;  /* The transaction counter has changed */
29757       }
29758     }
29759   }
29760 #endif
29761
29762   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
29763     amt -= wrote;
29764     offset += wrote;
29765     pBuf = &((char*)pBuf)[wrote];
29766   }
29767   SimulateIOError(( wrote=(-1), amt=1 ));
29768   SimulateDiskfullError(( wrote=0, amt=1 ));
29769
29770   if( amt>0 ){
29771     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
29772       /* lastErrno set by seekAndWrite */
29773       return SQLCIPHER_IOERR_WRITE;
29774     }else{
29775       pFile->lastErrno = 0; /* not a system error */
29776       return SQLCIPHER_FULL;
29777     }
29778   }
29779
29780   return SQLCIPHER_OK;
29781 }
29782
29783 #ifdef SQLCIPHER_TEST
29784 /*
29785 ** Count the number of fullsyncs and normal syncs.  This is used to test
29786 ** that syncs and fullsyncs are occurring at the right times.
29787 */
29788 SQLCIPHER_API int sqlcipher3_sync_count = 0;
29789 SQLCIPHER_API int sqlcipher3_fullsync_count = 0;
29790 #endif
29791
29792 /*
29793 ** We do not trust systems to provide a working fdatasync().  Some do.
29794 ** Others do no.  To be safe, we will stick with the (slightly slower)
29795 ** fsync(). If you know that your system does support fdatasync() correctly,
29796 ** then simply compile with -Dfdatasync=fdatasync
29797 */
29798 #if !defined(fdatasync)
29799 # define fdatasync fsync
29800 #endif
29801
29802 /*
29803 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
29804 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
29805 ** only available on Mac OS X.  But that could change.
29806 */
29807 #ifdef F_FULLFSYNC
29808 # define HAVE_FULLFSYNC 1
29809 #else
29810 # define HAVE_FULLFSYNC 0
29811 #endif
29812
29813
29814 /*
29815 ** The fsync() system call does not work as advertised on many
29816 ** unix systems.  The following procedure is an attempt to make
29817 ** it work better.
29818 **
29819 ** The SQLCIPHER_NO_SYNC macro disables all fsync()s.  This is useful
29820 ** for testing when we want to run through the test suite quickly.
29821 ** You are strongly advised *not* to deploy with SQLCIPHER_NO_SYNC
29822 ** enabled, however, since with SQLCIPHER_NO_SYNC enabled, an OS crash
29823 ** or power failure will likely corrupt the database file.
29824 **
29825 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
29826 ** The idea behind dataOnly is that it should only write the file content
29827 ** to disk, not the inode.  We only set dataOnly if the file size is 
29828 ** unchanged since the file size is part of the inode.  However, 
29829 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
29830 ** file size has changed.  The only real difference between fdatasync()
29831 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
29832 ** inode if the mtime or owner or other inode attributes have changed.
29833 ** We only care about the file size, not the other file attributes, so
29834 ** as far as SQLite is concerned, an fdatasync() is always adequate.
29835 ** So, we always use fdatasync() if it is available, regardless of
29836 ** the value of the dataOnly flag.
29837 */
29838 static int full_fsync(int fd, int fullSync, int dataOnly){
29839   int rc;
29840
29841   /* The following "ifdef/elif/else/" block has the same structure as
29842   ** the one below. It is replicated here solely to avoid cluttering 
29843   ** up the real code with the UNUSED_PARAMETER() macros.
29844   */
29845 #ifdef SQLCIPHER_NO_SYNC
29846   UNUSED_PARAMETER(fd);
29847   UNUSED_PARAMETER(fullSync);
29848   UNUSED_PARAMETER(dataOnly);
29849 #elif HAVE_FULLFSYNC
29850   UNUSED_PARAMETER(dataOnly);
29851 #else
29852   UNUSED_PARAMETER(fullSync);
29853   UNUSED_PARAMETER(dataOnly);
29854 #endif
29855
29856   /* Record the number of times that we do a normal fsync() and 
29857   ** FULLSYNC.  This is used during testing to verify that this procedure
29858   ** gets called with the correct arguments.
29859   */
29860 #ifdef SQLCIPHER_TEST
29861   if( fullSync ) sqlcipher3_fullsync_count++;
29862   sqlcipher3_sync_count++;
29863 #endif
29864
29865   /* If we compiled with the SQLCIPHER_NO_SYNC flag, then syncing is a
29866   ** no-op
29867   */
29868 #ifdef SQLCIPHER_NO_SYNC
29869   rc = SQLCIPHER_OK;
29870 #elif HAVE_FULLFSYNC
29871   if( fullSync ){
29872     rc = osFcntl(fd, F_FULLFSYNC, 0);
29873   }else{
29874     rc = 1;
29875   }
29876   /* If the FULLFSYNC failed, fall back to attempting an fsync().
29877   ** It shouldn't be possible for fullfsync to fail on the local 
29878   ** file system (on OSX), so failure indicates that FULLFSYNC
29879   ** isn't supported for this file system. So, attempt an fsync 
29880   ** and (for now) ignore the overhead of a superfluous fcntl call.  
29881   ** It'd be better to detect fullfsync support once and avoid 
29882   ** the fcntl call every time sync is called.
29883   */
29884   if( rc ) rc = fsync(fd);
29885
29886 #elif defined(__APPLE__)
29887   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
29888   ** so currently we default to the macro that redefines fdatasync to fsync
29889   */
29890   rc = fsync(fd);
29891 #else 
29892   rc = fdatasync(fd);
29893 #if OS_VXWORKS
29894   if( rc==-1 && errno==ENOTSUP ){
29895     rc = fsync(fd);
29896   }
29897 #endif /* OS_VXWORKS */
29898 #endif /* ifdef SQLCIPHER_NO_SYNC elif HAVE_FULLFSYNC */
29899
29900   if( OS_VXWORKS && rc!= -1 ){
29901     rc = 0;
29902   }
29903   return rc;
29904 }
29905
29906 /*
29907 ** Open a file descriptor to the directory containing file zFilename.
29908 ** If successful, *pFd is set to the opened file descriptor and
29909 ** SQLCIPHER_OK is returned. If an error occurs, either SQLCIPHER_NOMEM
29910 ** or SQLCIPHER_CANTOPEN is returned and *pFd is set to an undefined
29911 ** value.
29912 **
29913 ** The directory file descriptor is used for only one thing - to
29914 ** fsync() a directory to make sure file creation and deletion events
29915 ** are flushed to disk.  Such fsyncs are not needed on newer
29916 ** journaling filesystems, but are required on older filesystems.
29917 **
29918 ** This routine can be overridden using the xSetSysCall interface.
29919 ** The ability to override this routine was added in support of the
29920 ** chromium sandbox.  Opening a directory is a security risk (we are
29921 ** told) so making it overrideable allows the chromium sandbox to
29922 ** replace this routine with a harmless no-op.  To make this routine
29923 ** a no-op, replace it with a stub that returns SQLCIPHER_OK but leaves
29924 ** *pFd set to a negative number.
29925 **
29926 ** If SQLCIPHER_OK is returned, the caller is responsible for closing
29927 ** the file descriptor *pFd using close().
29928 */
29929 static int openDirectory(const char *zFilename, int *pFd){
29930   int ii;
29931   int fd = -1;
29932   char zDirname[MAX_PATHNAME+1];
29933
29934   sqlcipher3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
29935   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
29936   if( ii>0 ){
29937     zDirname[ii] = '\0';
29938     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
29939     if( fd>=0 ){
29940 #ifdef FD_CLOEXEC
29941       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29942 #endif
29943       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
29944     }
29945   }
29946   *pFd = fd;
29947   return (fd>=0?SQLCIPHER_OK:unixLogError(SQLCIPHER_CANTOPEN_BKPT, "open", zDirname));
29948 }
29949
29950 /*
29951 ** Make sure all writes to a particular file are committed to disk.
29952 **
29953 ** If dataOnly==0 then both the file itself and its metadata (file
29954 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
29955 ** file data is synced.
29956 **
29957 ** Under Unix, also make sure that the directory entry for the file
29958 ** has been created by fsync-ing the directory that contains the file.
29959 ** If we do not do this and we encounter a power failure, the directory
29960 ** entry for the journal might not exist after we reboot.  The next
29961 ** SQLite to access the file will not know that the journal exists (because
29962 ** the directory entry for the journal was never created) and the transaction
29963 ** will not roll back - possibly leading to database corruption.
29964 */
29965 static int unixSync(sqlcipher3_file *id, int flags){
29966   int rc;
29967   unixFile *pFile = (unixFile*)id;
29968
29969   int isDataOnly = (flags&SQLCIPHER_SYNC_DATAONLY);
29970   int isFullsync = (flags&0x0F)==SQLCIPHER_SYNC_FULL;
29971
29972   /* Check that one of SQLCIPHER_SYNC_NORMAL or FULL was passed */
29973   assert((flags&0x0F)==SQLCIPHER_SYNC_NORMAL
29974       || (flags&0x0F)==SQLCIPHER_SYNC_FULL
29975   );
29976
29977   /* Unix cannot, but some systems may return SQLCIPHER_FULL from here. This
29978   ** line is to test that doing so does not cause any problems.
29979   */
29980   SimulateDiskfullError( return SQLCIPHER_FULL );
29981
29982   assert( pFile );
29983   OSTRACE(("SYNC    %-3d\n", pFile->h));
29984   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
29985   SimulateIOError( rc=1 );
29986   if( rc ){
29987     pFile->lastErrno = errno;
29988     return unixLogError(SQLCIPHER_IOERR_FSYNC, "full_fsync", pFile->zPath);
29989   }
29990
29991   /* Also fsync the directory containing the file if the DIRSYNC flag
29992   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
29993   ** are unable to fsync a directory, so ignore errors on the fsync.
29994   */
29995   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
29996     int dirfd;
29997     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
29998             HAVE_FULLFSYNC, isFullsync));
29999     rc = osOpenDirectory(pFile->zPath, &dirfd);
30000     if( rc==SQLCIPHER_OK && dirfd>=0 ){
30001       full_fsync(dirfd, 0, 0);
30002       robust_close(pFile, dirfd, __LINE__);
30003     }else if( rc==SQLCIPHER_CANTOPEN ){
30004       rc = SQLCIPHER_OK;
30005     }
30006     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
30007   }
30008   return rc;
30009 }
30010
30011 /*
30012 ** Truncate an open file to a specified size
30013 */
30014 static int unixTruncate(sqlcipher3_file *id, i64 nByte){
30015   unixFile *pFile = (unixFile *)id;
30016   int rc;
30017   assert( pFile );
30018   SimulateIOError( return SQLCIPHER_IOERR_TRUNCATE );
30019
30020   /* If the user has configured a chunk-size for this file, truncate the
30021   ** file so that it consists of an integer number of chunks (i.e. the
30022   ** actual file size after the operation may be larger than the requested
30023   ** size).
30024   */
30025   if( pFile->szChunk ){
30026     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
30027   }
30028
30029   rc = robust_ftruncate(pFile->h, (off_t)nByte);
30030   if( rc ){
30031     pFile->lastErrno = errno;
30032     return unixLogError(SQLCIPHER_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30033   }else{
30034 #ifndef NDEBUG
30035     /* If we are doing a normal write to a database file (as opposed to
30036     ** doing a hot-journal rollback or a write to some file other than a
30037     ** normal database file) and we truncate the file to zero length,
30038     ** that effectively updates the change counter.  This might happen
30039     ** when restoring a database using the backup API from a zero-length
30040     ** source.
30041     */
30042     if( pFile->inNormalWrite && nByte==0 ){
30043       pFile->transCntrChng = 1;
30044     }
30045 #endif
30046
30047     return SQLCIPHER_OK;
30048   }
30049 }
30050
30051 /*
30052 ** Determine the current size of a file in bytes
30053 */
30054 static int unixFileSize(sqlcipher3_file *id, i64 *pSize){
30055   int rc;
30056   struct stat buf;
30057   assert( id );
30058   rc = osFstat(((unixFile*)id)->h, &buf);
30059   SimulateIOError( rc=1 );
30060   if( rc!=0 ){
30061     ((unixFile*)id)->lastErrno = errno;
30062     return SQLCIPHER_IOERR_FSTAT;
30063   }
30064   *pSize = buf.st_size;
30065
30066   /* When opening a zero-size database, the findInodeInfo() procedure
30067   ** writes a single byte into that file in order to work around a bug
30068   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
30069   ** layers, we need to report this file size as zero even though it is
30070   ** really 1.   Ticket #3260.
30071   */
30072   if( *pSize==1 ) *pSize = 0;
30073
30074
30075   return SQLCIPHER_OK;
30076 }
30077
30078 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30079 /*
30080 ** Handler for proxy-locking file-control verbs.  Defined below in the
30081 ** proxying locking division.
30082 */
30083 static int proxyFileControl(sqlcipher3_file*,int,void*);
30084 #endif
30085
30086 /* 
30087 ** This function is called to handle the SQLCIPHER_FCNTL_SIZE_HINT 
30088 ** file-control operation.  Enlarge the database to nBytes in size
30089 ** (rounded up to the next chunk-size).  If the database is already
30090 ** nBytes or larger, this routine is a no-op.
30091 */
30092 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
30093   if( pFile->szChunk>0 ){
30094     i64 nSize;                    /* Required file size */
30095     struct stat buf;              /* Used to hold return values of fstat() */
30096    
30097     if( osFstat(pFile->h, &buf) ) return SQLCIPHER_IOERR_FSTAT;
30098
30099     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
30100     if( nSize>(i64)buf.st_size ){
30101
30102 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30103       /* The code below is handling the return value of osFallocate() 
30104       ** correctly. posix_fallocate() is defined to "returns zero on success, 
30105       ** or an error number on  failure". See the manpage for details. */
30106       int err;
30107       do{
30108         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
30109       }while( err==EINTR );
30110       if( err ) return SQLCIPHER_IOERR_WRITE;
30111 #else
30112       /* If the OS does not have posix_fallocate(), fake it. First use
30113       ** ftruncate() to set the file size, then write a single byte to
30114       ** the last byte in each block within the extended region. This
30115       ** is the same technique used by glibc to implement posix_fallocate()
30116       ** on systems that do not have a real fallocate() system call.
30117       */
30118       int nBlk = buf.st_blksize;  /* File-system block size */
30119       i64 iWrite;                 /* Next offset to write to */
30120
30121       if( robust_ftruncate(pFile->h, nSize) ){
30122         pFile->lastErrno = errno;
30123         return unixLogError(SQLCIPHER_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30124       }
30125       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
30126       while( iWrite<nSize ){
30127         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
30128         if( nWrite!=1 ) return SQLCIPHER_IOERR_WRITE;
30129         iWrite += nBlk;
30130       }
30131 #endif
30132     }
30133   }
30134
30135   return SQLCIPHER_OK;
30136 }
30137
30138 /*
30139 ** Information and control of an open file handle.
30140 */
30141 static int unixFileControl(sqlcipher3_file *id, int op, void *pArg){
30142   unixFile *pFile = (unixFile*)id;
30143   switch( op ){
30144     case SQLCIPHER_FCNTL_LOCKSTATE: {
30145       *(int*)pArg = pFile->eFileLock;
30146       return SQLCIPHER_OK;
30147     }
30148     case SQLCIPHER_LAST_ERRNO: {
30149       *(int*)pArg = pFile->lastErrno;
30150       return SQLCIPHER_OK;
30151     }
30152     case SQLCIPHER_FCNTL_CHUNK_SIZE: {
30153       pFile->szChunk = *(int *)pArg;
30154       return SQLCIPHER_OK;
30155     }
30156     case SQLCIPHER_FCNTL_SIZE_HINT: {
30157       int rc;
30158       SimulateIOErrorBenign(1);
30159       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
30160       SimulateIOErrorBenign(0);
30161       return rc;
30162     }
30163     case SQLCIPHER_FCNTL_PERSIST_WAL: {
30164       int bPersist = *(int*)pArg;
30165       if( bPersist<0 ){
30166         *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
30167       }else if( bPersist==0 ){
30168         pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
30169       }else{
30170         pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
30171       }
30172       return SQLCIPHER_OK;
30173     }
30174 #ifndef NDEBUG
30175     /* The pager calls this method to signal that it has done
30176     ** a rollback and that the database is therefore unchanged and
30177     ** it hence it is OK for the transaction change counter to be
30178     ** unchanged.
30179     */
30180     case SQLCIPHER_FCNTL_DB_UNCHANGED: {
30181       ((unixFile*)id)->dbUpdate = 0;
30182       return SQLCIPHER_OK;
30183     }
30184 #endif
30185 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30186     case SQLCIPHER_SET_LOCKPROXYFILE:
30187     case SQLCIPHER_GET_LOCKPROXYFILE: {
30188       return proxyFileControl(id,op,pArg);
30189     }
30190 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
30191     case SQLCIPHER_FCNTL_SYNC_OMITTED: {
30192       return SQLCIPHER_OK;  /* A no-op */
30193     }
30194   }
30195   return SQLCIPHER_NOTFOUND;
30196 }
30197
30198 /*
30199 ** Return the sector size in bytes of the underlying block device for
30200 ** the specified file. This is almost always 512 bytes, but may be
30201 ** larger for some devices.
30202 **
30203 ** SQLite code assumes this function cannot fail. It also assumes that
30204 ** if two files are created in the same file-system directory (i.e.
30205 ** a database and its journal file) that the sector size will be the
30206 ** same for both.
30207 */
30208 static int unixSectorSize(sqlcipher3_file *NotUsed){
30209   UNUSED_PARAMETER(NotUsed);
30210   return SQLCIPHER_DEFAULT_SECTOR_SIZE;
30211 }
30212
30213 /*
30214 ** Return the device characteristics for the file. This is always 0 for unix.
30215 */
30216 static int unixDeviceCharacteristics(sqlcipher3_file *NotUsed){
30217   UNUSED_PARAMETER(NotUsed);
30218   return 0;
30219 }
30220
30221 #ifndef SQLCIPHER_OMIT_WAL
30222
30223
30224 /*
30225 ** Object used to represent an shared memory buffer.  
30226 **
30227 ** When multiple threads all reference the same wal-index, each thread
30228 ** has its own unixShm object, but they all point to a single instance
30229 ** of this unixShmNode object.  In other words, each wal-index is opened
30230 ** only once per process.
30231 **
30232 ** Each unixShmNode object is connected to a single unixInodeInfo object.
30233 ** We could coalesce this object into unixInodeInfo, but that would mean
30234 ** every open file that does not use shared memory (in other words, most
30235 ** open files) would have to carry around this extra information.  So
30236 ** the unixInodeInfo object contains a pointer to this unixShmNode object
30237 ** and the unixShmNode object is created only when needed.
30238 **
30239 ** unixMutexHeld() must be true when creating or destroying
30240 ** this object or while reading or writing the following fields:
30241 **
30242 **      nRef
30243 **
30244 ** The following fields are read-only after the object is created:
30245 ** 
30246 **      fid
30247 **      zFilename
30248 **
30249 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
30250 ** unixMutexHeld() is true when reading or writing any other field
30251 ** in this structure.
30252 */
30253 struct unixShmNode {
30254   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
30255   sqlcipher3_mutex *mutex;      /* Mutex to access this object */
30256   char *zFilename;           /* Name of the mmapped file */
30257   int h;                     /* Open file descriptor */
30258   int szRegion;              /* Size of shared-memory regions */
30259   u16 nRegion;               /* Size of array apRegion */
30260   u8 isReadonly;             /* True if read-only */
30261   char **apRegion;           /* Array of mapped shared-memory regions */
30262   int nRef;                  /* Number of unixShm objects pointing to this */
30263   unixShm *pFirst;           /* All unixShm objects pointing to this */
30264 #ifdef SQLCIPHER_DEBUG
30265   u8 exclMask;               /* Mask of exclusive locks held */
30266   u8 sharedMask;             /* Mask of shared locks held */
30267   u8 nextShmId;              /* Next available unixShm.id value */
30268 #endif
30269 };
30270
30271 /*
30272 ** Structure used internally by this VFS to record the state of an
30273 ** open shared memory connection.
30274 **
30275 ** The following fields are initialized when this object is created and
30276 ** are read-only thereafter:
30277 **
30278 **    unixShm.pFile
30279 **    unixShm.id
30280 **
30281 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
30282 ** while accessing any read/write fields.
30283 */
30284 struct unixShm {
30285   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
30286   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
30287   u8 hasMutex;               /* True if holding the unixShmNode mutex */
30288   u8 id;                     /* Id of this connection within its unixShmNode */
30289   u16 sharedMask;            /* Mask of shared locks held */
30290   u16 exclMask;              /* Mask of exclusive locks held */
30291 };
30292
30293 /*
30294 ** Constants used for locking
30295 */
30296 #define UNIX_SHM_BASE   ((22+SQLCIPHER_SHM_NLOCK)*4)         /* first lock byte */
30297 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLCIPHER_SHM_NLOCK)  /* deadman switch */
30298
30299 /*
30300 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
30301 **
30302 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
30303 ** otherwise.
30304 */
30305 static int unixShmSystemLock(
30306   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
30307   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
30308   int ofst,              /* First byte of the locking range */
30309   int n                  /* Number of bytes to lock */
30310 ){
30311   struct flock f;       /* The posix advisory locking structure */
30312   int rc = SQLCIPHER_OK;   /* Result code form fcntl() */
30313
30314   /* Access to the unixShmNode object is serialized by the caller */
30315   assert( sqlcipher3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
30316
30317   /* Shared locks never span more than one byte */
30318   assert( n==1 || lockType!=F_RDLCK );
30319
30320   /* Locks are within range */
30321   assert( n>=1 && n<SQLCIPHER_SHM_NLOCK );
30322
30323   if( pShmNode->h>=0 ){
30324     /* Initialize the locking parameters */
30325     memset(&f, 0, sizeof(f));
30326     f.l_type = lockType;
30327     f.l_whence = SEEK_SET;
30328     f.l_start = ofst;
30329     f.l_len = n;
30330
30331     rc = osFcntl(pShmNode->h, F_SETLK, &f);
30332     rc = (rc!=(-1)) ? SQLCIPHER_OK : SQLCIPHER_BUSY;
30333   }
30334
30335   /* Update the global lock state and do debug tracing */
30336 #ifdef SQLCIPHER_DEBUG
30337   { u16 mask;
30338   OSTRACE(("SHM-LOCK "));
30339   mask = (1<<(ofst+n)) - (1<<ofst);
30340   if( rc==SQLCIPHER_OK ){
30341     if( lockType==F_UNLCK ){
30342       OSTRACE(("unlock %d ok", ofst));
30343       pShmNode->exclMask &= ~mask;
30344       pShmNode->sharedMask &= ~mask;
30345     }else if( lockType==F_RDLCK ){
30346       OSTRACE(("read-lock %d ok", ofst));
30347       pShmNode->exclMask &= ~mask;
30348       pShmNode->sharedMask |= mask;
30349     }else{
30350       assert( lockType==F_WRLCK );
30351       OSTRACE(("write-lock %d ok", ofst));
30352       pShmNode->exclMask |= mask;
30353       pShmNode->sharedMask &= ~mask;
30354     }
30355   }else{
30356     if( lockType==F_UNLCK ){
30357       OSTRACE(("unlock %d failed", ofst));
30358     }else if( lockType==F_RDLCK ){
30359       OSTRACE(("read-lock failed"));
30360     }else{
30361       assert( lockType==F_WRLCK );
30362       OSTRACE(("write-lock %d failed", ofst));
30363     }
30364   }
30365   OSTRACE((" - afterwards %03x,%03x\n",
30366            pShmNode->sharedMask, pShmNode->exclMask));
30367   }
30368 #endif
30369
30370   return rc;        
30371 }
30372
30373
30374 /*
30375 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
30376 **
30377 ** This is not a VFS shared-memory method; it is a utility function called
30378 ** by VFS shared-memory methods.
30379 */
30380 static void unixShmPurge(unixFile *pFd){
30381   unixShmNode *p = pFd->pInode->pShmNode;
30382   assert( unixMutexHeld() );
30383   if( p && p->nRef==0 ){
30384     int i;
30385     assert( p->pInode==pFd->pInode );
30386     sqlcipher3_mutex_free(p->mutex);
30387     for(i=0; i<p->nRegion; i++){
30388       if( p->h>=0 ){
30389         munmap(p->apRegion[i], p->szRegion);
30390       }else{
30391         sqlcipher3_free(p->apRegion[i]);
30392       }
30393     }
30394     sqlcipher3_free(p->apRegion);
30395     if( p->h>=0 ){
30396       robust_close(pFd, p->h, __LINE__);
30397       p->h = -1;
30398     }
30399     p->pInode->pShmNode = 0;
30400     sqlcipher3_free(p);
30401   }
30402 }
30403
30404 /*
30405 ** Open a shared-memory area associated with open database file pDbFd.  
30406 ** This particular implementation uses mmapped files.
30407 **
30408 ** The file used to implement shared-memory is in the same directory
30409 ** as the open database file and has the same name as the open database
30410 ** file with the "-shm" suffix added.  For example, if the database file
30411 ** is "/home/user1/config.db" then the file that is created and mmapped
30412 ** for shared memory will be called "/home/user1/config.db-shm".  
30413 **
30414 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
30415 ** some other tmpfs mount. But if a file in a different directory
30416 ** from the database file is used, then differing access permissions
30417 ** or a chroot() might cause two different processes on the same
30418 ** database to end up using different files for shared memory - 
30419 ** meaning that their memory would not really be shared - resulting
30420 ** in database corruption.  Nevertheless, this tmpfs file usage
30421 ** can be enabled at compile-time using -DSQLCIPHER_SHM_DIRECTORY="/dev/shm"
30422 ** or the equivalent.  The use of the SQLCIPHER_SHM_DIRECTORY compile-time
30423 ** option results in an incompatible build of SQLite;  builds of SQLite
30424 ** that with differing SQLCIPHER_SHM_DIRECTORY settings attempt to use the
30425 ** same database file at the same time, database corruption will likely
30426 ** result. The SQLCIPHER_SHM_DIRECTORY compile-time option is considered
30427 ** "unsupported" and may go away in a future SQLite release.
30428 **
30429 ** When opening a new shared-memory file, if no other instances of that
30430 ** file are currently open, in this process or in other processes, then
30431 ** the file must be truncated to zero length or have its header cleared.
30432 **
30433 ** If the original database file (pDbFd) is using the "unix-excl" VFS
30434 ** that means that an exclusive lock is held on the database file and
30435 ** that no other processes are able to read or write the database.  In
30436 ** that case, we do not really need shared memory.  No shared memory
30437 ** file is created.  The shared memory will be simulated with heap memory.
30438 */
30439 static int unixOpenSharedMemory(unixFile *pDbFd){
30440   struct unixShm *p = 0;          /* The connection to be opened */
30441   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
30442   int rc;                         /* Result code */
30443   unixInodeInfo *pInode;          /* The inode of fd */
30444   char *zShmFilename;             /* Name of the file used for SHM */
30445   int nShmFilename;               /* Size of the SHM filename in bytes */
30446
30447   /* Allocate space for the new unixShm object. */
30448   p = sqlcipher3_malloc( sizeof(*p) );
30449   if( p==0 ) return SQLCIPHER_NOMEM;
30450   memset(p, 0, sizeof(*p));
30451   assert( pDbFd->pShm==0 );
30452
30453   /* Check to see if a unixShmNode object already exists. Reuse an existing
30454   ** one if present. Create a new one if necessary.
30455   */
30456   unixEnterMutex();
30457   pInode = pDbFd->pInode;
30458   pShmNode = pInode->pShmNode;
30459   if( pShmNode==0 ){
30460     struct stat sStat;                 /* fstat() info for database file */
30461
30462     /* Call fstat() to figure out the permissions on the database file. If
30463     ** a new *-shm file is created, an attempt will be made to create it
30464     ** with the same permissions. The actual permissions the file is created
30465     ** with are subject to the current umask setting.
30466     */
30467     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
30468       rc = SQLCIPHER_IOERR_FSTAT;
30469       goto shm_open_err;
30470     }
30471
30472 #ifdef SQLCIPHER_SHM_DIRECTORY
30473     nShmFilename = sizeof(SQLCIPHER_SHM_DIRECTORY) + 30;
30474 #else
30475     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
30476 #endif
30477     pShmNode = sqlcipher3_malloc( sizeof(*pShmNode) + nShmFilename );
30478     if( pShmNode==0 ){
30479       rc = SQLCIPHER_NOMEM;
30480       goto shm_open_err;
30481     }
30482     memset(pShmNode, 0, sizeof(*pShmNode));
30483     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
30484 #ifdef SQLCIPHER_SHM_DIRECTORY
30485     sqlcipher3_snprintf(nShmFilename, zShmFilename, 
30486                      SQLCIPHER_SHM_DIRECTORY "/sqlcipher-shm-%x-%x",
30487                      (u32)sStat.st_ino, (u32)sStat.st_dev);
30488 #else
30489     sqlcipher3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
30490     sqlcipher3FileSuffix3(pDbFd->zPath, zShmFilename);
30491 #endif
30492     pShmNode->h = -1;
30493     pDbFd->pInode->pShmNode = pShmNode;
30494     pShmNode->pInode = pDbFd->pInode;
30495     pShmNode->mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_FAST);
30496     if( pShmNode->mutex==0 ){
30497       rc = SQLCIPHER_NOMEM;
30498       goto shm_open_err;
30499     }
30500
30501     if( pInode->bProcessLock==0 ){
30502       const char *zRO;
30503       int openFlags = O_RDWR | O_CREAT;
30504       zRO = sqlcipher3_uri_parameter(pDbFd->zPath, "readonly_shm");
30505       if( zRO && sqlcipher3GetBoolean(zRO) ){
30506         openFlags = O_RDONLY;
30507         pShmNode->isReadonly = 1;
30508       }
30509       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
30510       if( pShmNode->h<0 ){
30511         if( pShmNode->h<0 ){
30512           rc = unixLogError(SQLCIPHER_CANTOPEN_BKPT, "open", zShmFilename);
30513           goto shm_open_err;
30514         }
30515       }
30516   
30517       /* Check to see if another process is holding the dead-man switch.
30518       ** If not, truncate the file to zero length. 
30519       */
30520       rc = SQLCIPHER_OK;
30521       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLCIPHER_OK ){
30522         if( robust_ftruncate(pShmNode->h, 0) ){
30523           rc = unixLogError(SQLCIPHER_IOERR_SHMOPEN, "ftruncate", zShmFilename);
30524         }
30525       }
30526       if( rc==SQLCIPHER_OK ){
30527         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
30528       }
30529       if( rc ) goto shm_open_err;
30530     }
30531   }
30532
30533   /* Make the new connection a child of the unixShmNode */
30534   p->pShmNode = pShmNode;
30535 #ifdef SQLCIPHER_DEBUG
30536   p->id = pShmNode->nextShmId++;
30537 #endif
30538   pShmNode->nRef++;
30539   pDbFd->pShm = p;
30540   unixLeaveMutex();
30541
30542   /* The reference count on pShmNode has already been incremented under
30543   ** the cover of the unixEnterMutex() mutex and the pointer from the
30544   ** new (struct unixShm) object to the pShmNode has been set. All that is
30545   ** left to do is to link the new object into the linked list starting
30546   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
30547   ** mutex.
30548   */
30549   sqlcipher3_mutex_enter(pShmNode->mutex);
30550   p->pNext = pShmNode->pFirst;
30551   pShmNode->pFirst = p;
30552   sqlcipher3_mutex_leave(pShmNode->mutex);
30553   return SQLCIPHER_OK;
30554
30555   /* Jump here on any error */
30556 shm_open_err:
30557   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
30558   sqlcipher3_free(p);
30559   unixLeaveMutex();
30560   return rc;
30561 }
30562
30563 /*
30564 ** This function is called to obtain a pointer to region iRegion of the 
30565 ** shared-memory associated with the database file fd. Shared-memory regions 
30566 ** are numbered starting from zero. Each shared-memory region is szRegion 
30567 ** bytes in size.
30568 **
30569 ** If an error occurs, an error code is returned and *pp is set to NULL.
30570 **
30571 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
30572 ** region has not been allocated (by any client, including one running in a
30573 ** separate process), then *pp is set to NULL and SQLCIPHER_OK returned. If 
30574 ** bExtend is non-zero and the requested shared-memory region has not yet 
30575 ** been allocated, it is allocated by this function.
30576 **
30577 ** If the shared-memory region has already been allocated or is allocated by
30578 ** this call as described above, then it is mapped into this processes 
30579 ** address space (if it is not already), *pp is set to point to the mapped 
30580 ** memory and SQLCIPHER_OK returned.
30581 */
30582 static int unixShmMap(
30583   sqlcipher3_file *fd,               /* Handle open on database file */
30584   int iRegion,                    /* Region to retrieve */
30585   int szRegion,                   /* Size of regions */
30586   int bExtend,                    /* True to extend file if necessary */
30587   void volatile **pp              /* OUT: Mapped memory */
30588 ){
30589   unixFile *pDbFd = (unixFile*)fd;
30590   unixShm *p;
30591   unixShmNode *pShmNode;
30592   int rc = SQLCIPHER_OK;
30593
30594   /* If the shared-memory file has not yet been opened, open it now. */
30595   if( pDbFd->pShm==0 ){
30596     rc = unixOpenSharedMemory(pDbFd);
30597     if( rc!=SQLCIPHER_OK ) return rc;
30598   }
30599
30600   p = pDbFd->pShm;
30601   pShmNode = p->pShmNode;
30602   sqlcipher3_mutex_enter(pShmNode->mutex);
30603   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30604   assert( pShmNode->pInode==pDbFd->pInode );
30605   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
30606   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
30607
30608   if( pShmNode->nRegion<=iRegion ){
30609     char **apNew;                      /* New apRegion[] array */
30610     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30611     struct stat sStat;                 /* Used by fstat() */
30612
30613     pShmNode->szRegion = szRegion;
30614
30615     if( pShmNode->h>=0 ){
30616       /* The requested region is not mapped into this processes address space.
30617       ** Check to see if it has been allocated (i.e. if the wal-index file is
30618       ** large enough to contain the requested region).
30619       */
30620       if( osFstat(pShmNode->h, &sStat) ){
30621         rc = SQLCIPHER_IOERR_SHMSIZE;
30622         goto shmpage_out;
30623       }
30624   
30625       if( sStat.st_size<nByte ){
30626         /* The requested memory region does not exist. If bExtend is set to
30627         ** false, exit early. *pp will be set to NULL and SQLCIPHER_OK returned.
30628         **
30629         ** Alternatively, if bExtend is true, use ftruncate() to allocate
30630         ** the requested memory region.
30631         */
30632         if( !bExtend ) goto shmpage_out;
30633         if( robust_ftruncate(pShmNode->h, nByte) ){
30634           rc = unixLogError(SQLCIPHER_IOERR_SHMSIZE, "ftruncate",
30635                             pShmNode->zFilename);
30636           goto shmpage_out;
30637         }
30638       }
30639     }
30640
30641     /* Map the requested memory region into this processes address space. */
30642     apNew = (char **)sqlcipher3_realloc(
30643         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
30644     );
30645     if( !apNew ){
30646       rc = SQLCIPHER_IOERR_NOMEM;
30647       goto shmpage_out;
30648     }
30649     pShmNode->apRegion = apNew;
30650     while(pShmNode->nRegion<=iRegion){
30651       void *pMem;
30652       if( pShmNode->h>=0 ){
30653         pMem = mmap(0, szRegion,
30654             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
30655             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
30656         );
30657         if( pMem==MAP_FAILED ){
30658           rc = unixLogError(SQLCIPHER_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
30659           goto shmpage_out;
30660         }
30661       }else{
30662         pMem = sqlcipher3_malloc(szRegion);
30663         if( pMem==0 ){
30664           rc = SQLCIPHER_NOMEM;
30665           goto shmpage_out;
30666         }
30667         memset(pMem, 0, szRegion);
30668       }
30669       pShmNode->apRegion[pShmNode->nRegion] = pMem;
30670       pShmNode->nRegion++;
30671     }
30672   }
30673
30674 shmpage_out:
30675   if( pShmNode->nRegion>iRegion ){
30676     *pp = pShmNode->apRegion[iRegion];
30677   }else{
30678     *pp = 0;
30679   }
30680   if( pShmNode->isReadonly && rc==SQLCIPHER_OK ) rc = SQLCIPHER_READONLY;
30681   sqlcipher3_mutex_leave(pShmNode->mutex);
30682   return rc;
30683 }
30684
30685 /*
30686 ** Change the lock state for a shared-memory segment.
30687 **
30688 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
30689 ** different here than in posix.  In xShmLock(), one can go from unlocked
30690 ** to shared and back or from unlocked to exclusive and back.  But one may
30691 ** not go from shared to exclusive or from exclusive to shared.
30692 */
30693 static int unixShmLock(
30694   sqlcipher3_file *fd,          /* Database file holding the shared memory */
30695   int ofst,                  /* First lock to acquire or release */
30696   int n,                     /* Number of locks to acquire or release */
30697   int flags                  /* What to do with the lock */
30698 ){
30699   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
30700   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
30701   unixShm *pX;                          /* For looping over all siblings */
30702   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
30703   int rc = SQLCIPHER_OK;                   /* Result code */
30704   u16 mask;                             /* Mask of locks to take or release */
30705
30706   assert( pShmNode==pDbFd->pInode->pShmNode );
30707   assert( pShmNode->pInode==pDbFd->pInode );
30708   assert( ofst>=0 && ofst+n<=SQLCIPHER_SHM_NLOCK );
30709   assert( n>=1 );
30710   assert( flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED)
30711        || flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE)
30712        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED)
30713        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE) );
30714   assert( n==1 || (flags & SQLCIPHER_SHM_EXCLUSIVE)!=0 );
30715   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
30716   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
30717
30718   mask = (1<<(ofst+n)) - (1<<ofst);
30719   assert( n>1 || mask==(1<<ofst) );
30720   sqlcipher3_mutex_enter(pShmNode->mutex);
30721   if( flags & SQLCIPHER_SHM_UNLOCK ){
30722     u16 allMask = 0; /* Mask of locks held by siblings */
30723
30724     /* See if any siblings hold this same lock */
30725     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30726       if( pX==p ) continue;
30727       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30728       allMask |= pX->sharedMask;
30729     }
30730
30731     /* Unlock the system-level locks */
30732     if( (mask & allMask)==0 ){
30733       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
30734     }else{
30735       rc = SQLCIPHER_OK;
30736     }
30737
30738     /* Undo the local locks */
30739     if( rc==SQLCIPHER_OK ){
30740       p->exclMask &= ~mask;
30741       p->sharedMask &= ~mask;
30742     } 
30743   }else if( flags & SQLCIPHER_SHM_SHARED ){
30744     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30745
30746     /* Find out which shared locks are already held by sibling connections.
30747     ** If any sibling already holds an exclusive lock, go ahead and return
30748     ** SQLCIPHER_BUSY.
30749     */
30750     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30751       if( (pX->exclMask & mask)!=0 ){
30752         rc = SQLCIPHER_BUSY;
30753         break;
30754       }
30755       allShared |= pX->sharedMask;
30756     }
30757
30758     /* Get shared locks at the system level, if necessary */
30759     if( rc==SQLCIPHER_OK ){
30760       if( (allShared & mask)==0 ){
30761         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
30762       }else{
30763         rc = SQLCIPHER_OK;
30764       }
30765     }
30766
30767     /* Get the local shared locks */
30768     if( rc==SQLCIPHER_OK ){
30769       p->sharedMask |= mask;
30770     }
30771   }else{
30772     /* Make sure no sibling connections hold locks that will block this
30773     ** lock.  If any do, return SQLCIPHER_BUSY right away.
30774     */
30775     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30776       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30777         rc = SQLCIPHER_BUSY;
30778         break;
30779       }
30780     }
30781   
30782     /* Get the exclusive locks at the system level.  Then if successful
30783     ** also mark the local connection as being locked.
30784     */
30785     if( rc==SQLCIPHER_OK ){
30786       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
30787       if( rc==SQLCIPHER_OK ){
30788         assert( (p->sharedMask & mask)==0 );
30789         p->exclMask |= mask;
30790       }
30791     }
30792   }
30793   sqlcipher3_mutex_leave(pShmNode->mutex);
30794   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
30795            p->id, getpid(), p->sharedMask, p->exclMask));
30796   return rc;
30797 }
30798
30799 /*
30800 ** Implement a memory barrier or memory fence on shared memory.  
30801 **
30802 ** All loads and stores begun before the barrier must complete before
30803 ** any load or store begun after the barrier.
30804 */
30805 static void unixShmBarrier(
30806   sqlcipher3_file *fd                /* Database file holding the shared memory */
30807 ){
30808   UNUSED_PARAMETER(fd);
30809   unixEnterMutex();
30810   unixLeaveMutex();
30811 }
30812
30813 /*
30814 ** Close a connection to shared-memory.  Delete the underlying 
30815 ** storage if deleteFlag is true.
30816 **
30817 ** If there is no shared memory associated with the connection then this
30818 ** routine is a harmless no-op.
30819 */
30820 static int unixShmUnmap(
30821   sqlcipher3_file *fd,               /* The underlying database file */
30822   int deleteFlag                  /* Delete shared-memory if true */
30823 ){
30824   unixShm *p;                     /* The connection to be closed */
30825   unixShmNode *pShmNode;          /* The underlying shared-memory file */
30826   unixShm **pp;                   /* For looping over sibling connections */
30827   unixFile *pDbFd;                /* The underlying database file */
30828
30829   pDbFd = (unixFile*)fd;
30830   p = pDbFd->pShm;
30831   if( p==0 ) return SQLCIPHER_OK;
30832   pShmNode = p->pShmNode;
30833
30834   assert( pShmNode==pDbFd->pInode->pShmNode );
30835   assert( pShmNode->pInode==pDbFd->pInode );
30836
30837   /* Remove connection p from the set of connections associated
30838   ** with pShmNode */
30839   sqlcipher3_mutex_enter(pShmNode->mutex);
30840   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30841   *pp = p->pNext;
30842
30843   /* Free the connection p */
30844   sqlcipher3_free(p);
30845   pDbFd->pShm = 0;
30846   sqlcipher3_mutex_leave(pShmNode->mutex);
30847
30848   /* If pShmNode->nRef has reached 0, then close the underlying
30849   ** shared-memory file, too */
30850   unixEnterMutex();
30851   assert( pShmNode->nRef>0 );
30852   pShmNode->nRef--;
30853   if( pShmNode->nRef==0 ){
30854     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
30855     unixShmPurge(pDbFd);
30856   }
30857   unixLeaveMutex();
30858
30859   return SQLCIPHER_OK;
30860 }
30861
30862
30863 #else
30864 # define unixShmMap     0
30865 # define unixShmLock    0
30866 # define unixShmBarrier 0
30867 # define unixShmUnmap   0
30868 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
30869
30870 /*
30871 ** Here ends the implementation of all sqlcipher3_file methods.
30872 **
30873 ********************** End sqlcipher3_file Methods *******************************
30874 ******************************************************************************/
30875
30876 /*
30877 ** This division contains definitions of sqlcipher3_io_methods objects that
30878 ** implement various file locking strategies.  It also contains definitions
30879 ** of "finder" functions.  A finder-function is used to locate the appropriate
30880 ** sqlcipher3_io_methods object for a particular database file.  The pAppData
30881 ** field of the sqlcipher3_vfs VFS objects are initialized to be pointers to
30882 ** the correct finder-function for that VFS.
30883 **
30884 ** Most finder functions return a pointer to a fixed sqlcipher3_io_methods
30885 ** object.  The only interesting finder-function is autolockIoFinder, which
30886 ** looks at the filesystem type and tries to guess the best locking
30887 ** strategy from that.
30888 **
30889 ** For finder-funtion F, two objects are created:
30890 **
30891 **    (1) The real finder-function named "FImpt()".
30892 **
30893 **    (2) A constant pointer to this function named just "F".
30894 **
30895 **
30896 ** A pointer to the F pointer is used as the pAppData value for VFS
30897 ** objects.  We have to do this instead of letting pAppData point
30898 ** directly at the finder-function since C90 rules prevent a void*
30899 ** from be cast into a function pointer.
30900 **
30901 **
30902 ** Each instance of this macro generates two objects:
30903 **
30904 **   *  A constant sqlcipher3_io_methods object call METHOD that has locking
30905 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
30906 **
30907 **   *  An I/O method finder function called FINDER that returns a pointer
30908 **      to the METHOD object in the previous bullet.
30909 */
30910 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
30911 static const sqlcipher3_io_methods METHOD = {                                   \
30912    VERSION,                    /* iVersion */                                \
30913    CLOSE,                      /* xClose */                                  \
30914    unixRead,                   /* xRead */                                   \
30915    unixWrite,                  /* xWrite */                                  \
30916    unixTruncate,               /* xTruncate */                               \
30917    unixSync,                   /* xSync */                                   \
30918    unixFileSize,               /* xFileSize */                               \
30919    LOCK,                       /* xLock */                                   \
30920    UNLOCK,                     /* xUnlock */                                 \
30921    CKLOCK,                     /* xCheckReservedLock */                      \
30922    unixFileControl,            /* xFileControl */                            \
30923    unixSectorSize,             /* xSectorSize */                             \
30924    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
30925    unixShmMap,                 /* xShmMap */                                 \
30926    unixShmLock,                /* xShmLock */                                \
30927    unixShmBarrier,             /* xShmBarrier */                             \
30928    unixShmUnmap                /* xShmUnmap */                               \
30929 };                                                                           \
30930 static const sqlcipher3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
30931   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
30932   return &METHOD;                                                            \
30933 }                                                                            \
30934 static const sqlcipher3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
30935     = FINDER##Impl;
30936
30937 /*
30938 ** Here are all of the sqlcipher3_io_methods objects for each of the
30939 ** locking strategies.  Functions that return pointers to these methods
30940 ** are also created.
30941 */
30942 IOMETHODS(
30943   posixIoFinder,            /* Finder function name */
30944   posixIoMethods,           /* sqlcipher3_io_methods object name */
30945   2,                        /* shared memory is enabled */
30946   unixClose,                /* xClose method */
30947   unixLock,                 /* xLock method */
30948   unixUnlock,               /* xUnlock method */
30949   unixCheckReservedLock     /* xCheckReservedLock method */
30950 )
30951 IOMETHODS(
30952   nolockIoFinder,           /* Finder function name */
30953   nolockIoMethods,          /* sqlcipher3_io_methods object name */
30954   1,                        /* shared memory is disabled */
30955   nolockClose,              /* xClose method */
30956   nolockLock,               /* xLock method */
30957   nolockUnlock,             /* xUnlock method */
30958   nolockCheckReservedLock   /* xCheckReservedLock method */
30959 )
30960 IOMETHODS(
30961   dotlockIoFinder,          /* Finder function name */
30962   dotlockIoMethods,         /* sqlcipher3_io_methods object name */
30963   1,                        /* shared memory is disabled */
30964   dotlockClose,             /* xClose method */
30965   dotlockLock,              /* xLock method */
30966   dotlockUnlock,            /* xUnlock method */
30967   dotlockCheckReservedLock  /* xCheckReservedLock method */
30968 )
30969
30970 #if SQLCIPHER_ENABLE_LOCKING_STYLE && !OS_VXWORKS
30971 IOMETHODS(
30972   flockIoFinder,            /* Finder function name */
30973   flockIoMethods,           /* sqlcipher3_io_methods object name */
30974   1,                        /* shared memory is disabled */
30975   flockClose,               /* xClose method */
30976   flockLock,                /* xLock method */
30977   flockUnlock,              /* xUnlock method */
30978   flockCheckReservedLock    /* xCheckReservedLock method */
30979 )
30980 #endif
30981
30982 #if OS_VXWORKS
30983 IOMETHODS(
30984   semIoFinder,              /* Finder function name */
30985   semIoMethods,             /* sqlcipher3_io_methods object name */
30986   1,                        /* shared memory is disabled */
30987   semClose,                 /* xClose method */
30988   semLock,                  /* xLock method */
30989   semUnlock,                /* xUnlock method */
30990   semCheckReservedLock      /* xCheckReservedLock method */
30991 )
30992 #endif
30993
30994 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
30995 IOMETHODS(
30996   afpIoFinder,              /* Finder function name */
30997   afpIoMethods,             /* sqlcipher3_io_methods object name */
30998   1,                        /* shared memory is disabled */
30999   afpClose,                 /* xClose method */
31000   afpLock,                  /* xLock method */
31001   afpUnlock,                /* xUnlock method */
31002   afpCheckReservedLock      /* xCheckReservedLock method */
31003 )
31004 #endif
31005
31006 /*
31007 ** The proxy locking method is a "super-method" in the sense that it
31008 ** opens secondary file descriptors for the conch and lock files and
31009 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
31010 ** secondary files.  For this reason, the division that implements
31011 ** proxy locking is located much further down in the file.  But we need
31012 ** to go ahead and define the sqlcipher3_io_methods and finder function
31013 ** for proxy locking here.  So we forward declare the I/O methods.
31014 */
31015 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31016 static int proxyClose(sqlcipher3_file*);
31017 static int proxyLock(sqlcipher3_file*, int);
31018 static int proxyUnlock(sqlcipher3_file*, int);
31019 static int proxyCheckReservedLock(sqlcipher3_file*, int*);
31020 IOMETHODS(
31021   proxyIoFinder,            /* Finder function name */
31022   proxyIoMethods,           /* sqlcipher3_io_methods object name */
31023   1,                        /* shared memory is disabled */
31024   proxyClose,               /* xClose method */
31025   proxyLock,                /* xLock method */
31026   proxyUnlock,              /* xUnlock method */
31027   proxyCheckReservedLock    /* xCheckReservedLock method */
31028 )
31029 #endif
31030
31031 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
31032 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31033 IOMETHODS(
31034   nfsIoFinder,               /* Finder function name */
31035   nfsIoMethods,              /* sqlcipher3_io_methods object name */
31036   1,                         /* shared memory is disabled */
31037   unixClose,                 /* xClose method */
31038   unixLock,                  /* xLock method */
31039   nfsUnlock,                 /* xUnlock method */
31040   unixCheckReservedLock      /* xCheckReservedLock method */
31041 )
31042 #endif
31043
31044 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31045 /* 
31046 ** This "finder" function attempts to determine the best locking strategy 
31047 ** for the database file "filePath".  It then returns the sqlcipher3_io_methods
31048 ** object that implements that strategy.
31049 **
31050 ** This is for MacOSX only.
31051 */
31052 static const sqlcipher3_io_methods *autolockIoFinderImpl(
31053   const char *filePath,    /* name of the database file */
31054   unixFile *pNew           /* open file object for the database file */
31055 ){
31056   static const struct Mapping {
31057     const char *zFilesystem;              /* Filesystem type name */
31058     const sqlcipher3_io_methods *pMethods;   /* Appropriate locking method */
31059   } aMap[] = {
31060     { "hfs",    &posixIoMethods },
31061     { "ufs",    &posixIoMethods },
31062     { "afpfs",  &afpIoMethods },
31063     { "smbfs",  &afpIoMethods },
31064     { "webdav", &nolockIoMethods },
31065     { 0, 0 }
31066   };
31067   int i;
31068   struct statfs fsInfo;
31069   struct flock lockInfo;
31070
31071   if( !filePath ){
31072     /* If filePath==NULL that means we are dealing with a transient file
31073     ** that does not need to be locked. */
31074     return &nolockIoMethods;
31075   }
31076   if( statfs(filePath, &fsInfo) != -1 ){
31077     if( fsInfo.f_flags & MNT_RDONLY ){
31078       return &nolockIoMethods;
31079     }
31080     for(i=0; aMap[i].zFilesystem; i++){
31081       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
31082         return aMap[i].pMethods;
31083       }
31084     }
31085   }
31086
31087   /* Default case. Handles, amongst others, "nfs".
31088   ** Test byte-range lock using fcntl(). If the call succeeds, 
31089   ** assume that the file-system supports POSIX style locks. 
31090   */
31091   lockInfo.l_len = 1;
31092   lockInfo.l_start = 0;
31093   lockInfo.l_whence = SEEK_SET;
31094   lockInfo.l_type = F_RDLCK;
31095   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31096     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
31097       return &nfsIoMethods;
31098     } else {
31099       return &posixIoMethods;
31100     }
31101   }else{
31102     return &dotlockIoMethods;
31103   }
31104 }
31105 static const sqlcipher3_io_methods 
31106   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
31107
31108 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
31109
31110 #if OS_VXWORKS && SQLCIPHER_ENABLE_LOCKING_STYLE
31111 /* 
31112 ** This "finder" function attempts to determine the best locking strategy 
31113 ** for the database file "filePath".  It then returns the sqlcipher3_io_methods
31114 ** object that implements that strategy.
31115 **
31116 ** This is for VXWorks only.
31117 */
31118 static const sqlcipher3_io_methods *autolockIoFinderImpl(
31119   const char *filePath,    /* name of the database file */
31120   unixFile *pNew           /* the open file object */
31121 ){
31122   struct flock lockInfo;
31123
31124   if( !filePath ){
31125     /* If filePath==NULL that means we are dealing with a transient file
31126     ** that does not need to be locked. */
31127     return &nolockIoMethods;
31128   }
31129
31130   /* Test if fcntl() is supported and use POSIX style locks.
31131   ** Otherwise fall back to the named semaphore method.
31132   */
31133   lockInfo.l_len = 1;
31134   lockInfo.l_start = 0;
31135   lockInfo.l_whence = SEEK_SET;
31136   lockInfo.l_type = F_RDLCK;
31137   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31138     return &posixIoMethods;
31139   }else{
31140     return &semIoMethods;
31141   }
31142 }
31143 static const sqlcipher3_io_methods 
31144   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
31145
31146 #endif /* OS_VXWORKS && SQLCIPHER_ENABLE_LOCKING_STYLE */
31147
31148 /*
31149 ** An abstract type for a pointer to a IO method finder function:
31150 */
31151 typedef const sqlcipher3_io_methods *(*finder_type)(const char*,unixFile*);
31152
31153
31154 /****************************************************************************
31155 **************************** sqlcipher3_vfs methods ****************************
31156 **
31157 ** This division contains the implementation of methods on the
31158 ** sqlcipher3_vfs object.
31159 */
31160
31161 /*
31162 ** Initialize the contents of the unixFile structure pointed to by pId.
31163 */
31164 static int fillInUnixFile(
31165   sqlcipher3_vfs *pVfs,      /* Pointer to vfs object */
31166   int h,                  /* Open file descriptor of file being opened */
31167   int syncDir,            /* True to sync directory on first sync */
31168   sqlcipher3_file *pId,      /* Write to the unixFile structure here */
31169   const char *zFilename,  /* Name of the file being opened */
31170   int noLock,             /* Omit locking if true */
31171   int isDelete,           /* Delete on close if true */
31172   int isReadOnly          /* True if the file is opened read-only */
31173 ){
31174   const sqlcipher3_io_methods *pLockingStyle;
31175   unixFile *pNew = (unixFile *)pId;
31176   int rc = SQLCIPHER_OK;
31177
31178   assert( pNew->pInode==NULL );
31179
31180   /* Parameter isDelete is only used on vxworks. Express this explicitly 
31181   ** here to prevent compiler warnings about unused parameters.
31182   */
31183   UNUSED_PARAMETER(isDelete);
31184
31185   /* Usually the path zFilename should not be a relative pathname. The
31186   ** exception is when opening the proxy "conch" file in builds that
31187   ** include the special Apple locking styles.
31188   */
31189 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31190   assert( zFilename==0 || zFilename[0]=='/' 
31191     || pVfs->pAppData==(void*)&autolockIoFinder );
31192 #else
31193   assert( zFilename==0 || zFilename[0]=='/' );
31194 #endif
31195
31196   /* No locking occurs in temporary files */
31197   assert( zFilename!=0 || noLock );
31198
31199   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
31200   pNew->h = h;
31201   pNew->zPath = zFilename;
31202   if( strcmp(pVfs->zName,"unix-excl")==0 ){
31203     pNew->ctrlFlags = UNIXFILE_EXCL;
31204   }else{
31205     pNew->ctrlFlags = 0;
31206   }
31207   if( isReadOnly ){
31208     pNew->ctrlFlags |= UNIXFILE_RDONLY;
31209   }
31210   if( syncDir ){
31211     pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
31212   }
31213
31214 #if OS_VXWORKS
31215   pNew->pId = vxworksFindFileId(zFilename);
31216   if( pNew->pId==0 ){
31217     noLock = 1;
31218     rc = SQLCIPHER_NOMEM;
31219   }
31220 #endif
31221
31222   if( noLock ){
31223     pLockingStyle = &nolockIoMethods;
31224   }else{
31225     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
31226 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31227     /* Cache zFilename in the locking context (AFP and dotlock override) for
31228     ** proxyLock activation is possible (remote proxy is based on db name)
31229     ** zFilename remains valid until file is closed, to support */
31230     pNew->lockingContext = (void*)zFilename;
31231 #endif
31232   }
31233
31234   if( pLockingStyle == &posixIoMethods
31235 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
31236     || pLockingStyle == &nfsIoMethods
31237 #endif
31238   ){
31239     unixEnterMutex();
31240     rc = findInodeInfo(pNew, &pNew->pInode);
31241     if( rc!=SQLCIPHER_OK ){
31242       /* If an error occured in findInodeInfo(), close the file descriptor
31243       ** immediately, before releasing the mutex. findInodeInfo() may fail
31244       ** in two scenarios:
31245       **
31246       **   (a) A call to fstat() failed.
31247       **   (b) A malloc failed.
31248       **
31249       ** Scenario (b) may only occur if the process is holding no other
31250       ** file descriptors open on the same file. If there were other file
31251       ** descriptors on this file, then no malloc would be required by
31252       ** findInodeInfo(). If this is the case, it is quite safe to close
31253       ** handle h - as it is guaranteed that no posix locks will be released
31254       ** by doing so.
31255       **
31256       ** If scenario (a) caused the error then things are not so safe. The
31257       ** implicit assumption here is that if fstat() fails, things are in
31258       ** such bad shape that dropping a lock or two doesn't matter much.
31259       */
31260       robust_close(pNew, h, __LINE__);
31261       h = -1;
31262     }
31263     unixLeaveMutex();
31264   }
31265
31266 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31267   else if( pLockingStyle == &afpIoMethods ){
31268     /* AFP locking uses the file path so it needs to be included in
31269     ** the afpLockingContext.
31270     */
31271     afpLockingContext *pCtx;
31272     pNew->lockingContext = pCtx = sqlcipher3_malloc( sizeof(*pCtx) );
31273     if( pCtx==0 ){
31274       rc = SQLCIPHER_NOMEM;
31275     }else{
31276       /* NB: zFilename exists and remains valid until the file is closed
31277       ** according to requirement F11141.  So we do not need to make a
31278       ** copy of the filename. */
31279       pCtx->dbPath = zFilename;
31280       pCtx->reserved = 0;
31281       srandomdev();
31282       unixEnterMutex();
31283       rc = findInodeInfo(pNew, &pNew->pInode);
31284       if( rc!=SQLCIPHER_OK ){
31285         sqlcipher3_free(pNew->lockingContext);
31286         robust_close(pNew, h, __LINE__);
31287         h = -1;
31288       }
31289       unixLeaveMutex();        
31290     }
31291   }
31292 #endif
31293
31294   else if( pLockingStyle == &dotlockIoMethods ){
31295     /* Dotfile locking uses the file path so it needs to be included in
31296     ** the dotlockLockingContext 
31297     */
31298     char *zLockFile;
31299     int nFilename;
31300     assert( zFilename!=0 );
31301     nFilename = (int)strlen(zFilename) + 6;
31302     zLockFile = (char *)sqlcipher3_malloc(nFilename);
31303     if( zLockFile==0 ){
31304       rc = SQLCIPHER_NOMEM;
31305     }else{
31306       sqlcipher3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
31307     }
31308     pNew->lockingContext = zLockFile;
31309   }
31310
31311 #if OS_VXWORKS
31312   else if( pLockingStyle == &semIoMethods ){
31313     /* Named semaphore locking uses the file path so it needs to be
31314     ** included in the semLockingContext
31315     */
31316     unixEnterMutex();
31317     rc = findInodeInfo(pNew, &pNew->pInode);
31318     if( (rc==SQLCIPHER_OK) && (pNew->pInode->pSem==NULL) ){
31319       char *zSemName = pNew->pInode->aSemName;
31320       int n;
31321       sqlcipher3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
31322                        pNew->pId->zCanonicalName);
31323       for( n=1; zSemName[n]; n++ )
31324         if( zSemName[n]=='/' ) zSemName[n] = '_';
31325       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
31326       if( pNew->pInode->pSem == SEM_FAILED ){
31327         rc = SQLCIPHER_NOMEM;
31328         pNew->pInode->aSemName[0] = '\0';
31329       }
31330     }
31331     unixLeaveMutex();
31332   }
31333 #endif
31334   
31335   pNew->lastErrno = 0;
31336 #if OS_VXWORKS
31337   if( rc!=SQLCIPHER_OK ){
31338     if( h>=0 ) robust_close(pNew, h, __LINE__);
31339     h = -1;
31340     osUnlink(zFilename);
31341     isDelete = 0;
31342   }
31343   pNew->isDelete = isDelete;
31344 #endif
31345   if( rc!=SQLCIPHER_OK ){
31346     if( h>=0 ) robust_close(pNew, h, __LINE__);
31347   }else{
31348     pNew->pMethod = pLockingStyle;
31349     OpenCounter(+1);
31350   }
31351   return rc;
31352 }
31353
31354 /*
31355 ** Return the name of a directory in which to put temporary files.
31356 ** If no suitable temporary file directory can be found, return NULL.
31357 */
31358 static const char *unixTempFileDir(void){
31359   static const char *azDirs[] = {
31360      0,
31361      0,
31362      "/tmp",
31363      "/var/tmp",
31364      "/usr/tmp",
31365      0        /* List terminator */
31366   };
31367   unsigned int i;
31368   struct stat buf;
31369   const char *zDir = 0;
31370
31371   azDirs[0] = sqlcipher3_temp_directory;
31372   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
31373   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
31374     if( zDir==0 ) continue;
31375     if( osStat(zDir, &buf) ) continue;
31376     if( !S_ISDIR(buf.st_mode) ) continue;
31377     if( osAccess(zDir, 07) ) continue;
31378     break;
31379   }
31380   return zDir;
31381 }
31382
31383 /*
31384 ** Create a temporary file name in zBuf.  zBuf must be allocated
31385 ** by the calling process and must be big enough to hold at least
31386 ** pVfs->mxPathname bytes.
31387 */
31388 static int unixGetTempname(int nBuf, char *zBuf){
31389   static const unsigned char zChars[] =
31390     "abcdefghijklmnopqrstuvwxyz"
31391     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
31392     "0123456789";
31393   unsigned int i, j;
31394   const char *zDir;
31395
31396   /* It's odd to simulate an io-error here, but really this is just
31397   ** using the io-error infrastructure to test that SQLite handles this
31398   ** function failing. 
31399   */
31400   SimulateIOError( return SQLCIPHER_IOERR );
31401
31402   zDir = unixTempFileDir();
31403   if( zDir==0 ) zDir = ".";
31404
31405   /* Check that the output buffer is large enough for the temporary file 
31406   ** name. If it is not, return SQLCIPHER_ERROR.
31407   */
31408   if( (strlen(zDir) + strlen(SQLCIPHER_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
31409     return SQLCIPHER_ERROR;
31410   }
31411
31412   do{
31413     sqlcipher3_snprintf(nBuf-17, zBuf, "%s/"SQLCIPHER_TEMP_FILE_PREFIX, zDir);
31414     j = (int)strlen(zBuf);
31415     sqlcipher3_randomness(15, &zBuf[j]);
31416     for(i=0; i<15; i++, j++){
31417       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31418     }
31419     zBuf[j] = 0;
31420   }while( osAccess(zBuf,0)==0 );
31421   return SQLCIPHER_OK;
31422 }
31423
31424 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31425 /*
31426 ** Routine to transform a unixFile into a proxy-locking unixFile.
31427 ** Implementation in the proxy-lock division, but used by unixOpen()
31428 ** if SQLCIPHER_PREFER_PROXY_LOCKING is defined.
31429 */
31430 static int proxyTransformUnixFile(unixFile*, const char*);
31431 #endif
31432
31433 /*
31434 ** Search for an unused file descriptor that was opened on the database 
31435 ** file (not a journal or master-journal file) identified by pathname
31436 ** zPath with SQLCIPHER_OPEN_XXX flags matching those passed as the second
31437 ** argument to this function.
31438 **
31439 ** Such a file descriptor may exist if a database connection was closed
31440 ** but the associated file descriptor could not be closed because some
31441 ** other file descriptor open on the same file is holding a file-lock.
31442 ** Refer to comments in the unixClose() function and the lengthy comment
31443 ** describing "Posix Advisory Locking" at the start of this file for 
31444 ** further details. Also, ticket #4018.
31445 **
31446 ** If a suitable file descriptor is found, then it is returned. If no
31447 ** such file descriptor is located, -1 is returned.
31448 */
31449 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
31450   UnixUnusedFd *pUnused = 0;
31451
31452   /* Do not search for an unused file descriptor on vxworks. Not because
31453   ** vxworks would not benefit from the change (it might, we're not sure),
31454   ** but because no way to test it is currently available. It is better 
31455   ** not to risk breaking vxworks support for the sake of such an obscure 
31456   ** feature.  */
31457 #if !OS_VXWORKS
31458   struct stat sStat;                   /* Results of stat() call */
31459
31460   /* A stat() call may fail for various reasons. If this happens, it is
31461   ** almost certain that an open() call on the same path will also fail.
31462   ** For this reason, if an error occurs in the stat() call here, it is
31463   ** ignored and -1 is returned. The caller will try to open a new file
31464   ** descriptor on the same path, fail, and return an error to SQLite.
31465   **
31466   ** Even if a subsequent open() call does succeed, the consequences of
31467   ** not searching for a resusable file descriptor are not dire.  */
31468   if( 0==osStat(zPath, &sStat) ){
31469     unixInodeInfo *pInode;
31470
31471     unixEnterMutex();
31472     pInode = inodeList;
31473     while( pInode && (pInode->fileId.dev!=sStat.st_dev
31474                      || pInode->fileId.ino!=sStat.st_ino) ){
31475        pInode = pInode->pNext;
31476     }
31477     if( pInode ){
31478       UnixUnusedFd **pp;
31479       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
31480       pUnused = *pp;
31481       if( pUnused ){
31482         *pp = pUnused->pNext;
31483       }
31484     }
31485     unixLeaveMutex();
31486   }
31487 #endif    /* if !OS_VXWORKS */
31488   return pUnused;
31489 }
31490
31491 /*
31492 ** This function is called by unixOpen() to determine the unix permissions
31493 ** to create new files with. If no error occurs, then SQLCIPHER_OK is returned
31494 ** and a value suitable for passing as the third argument to open(2) is
31495 ** written to *pMode. If an IO error occurs, an SQLite error code is 
31496 ** returned and the value of *pMode is not modified.
31497 **
31498 ** If the file being opened is a temporary file, it is always created with
31499 ** the octal permissions 0600 (read/writable by owner only). If the file
31500 ** is a database or master journal file, it is created with the permissions 
31501 ** mask SQLCIPHER_DEFAULT_FILE_PERMISSIONS.
31502 **
31503 ** Finally, if the file being opened is a WAL or regular journal file, then 
31504 ** this function queries the file-system for the permissions on the 
31505 ** corresponding database file and sets *pMode to this value. Whenever 
31506 ** possible, WAL and journal files are created using the same permissions 
31507 ** as the associated database file.
31508 **
31509 ** If the SQLCIPHER_ENABLE_8_3_NAMES option is enabled, then the
31510 ** original filename is unavailable.  But 8_3_NAMES is only used for
31511 ** FAT filesystems and permissions do not matter there, so just use
31512 ** the default permissions.
31513 */
31514 static int findCreateFileMode(
31515   const char *zPath,              /* Path of file (possibly) being created */
31516   int flags,                      /* Flags passed as 4th argument to xOpen() */
31517   mode_t *pMode                   /* OUT: Permissions to open file with */
31518 ){
31519   int rc = SQLCIPHER_OK;             /* Return Code */
31520   *pMode = SQLCIPHER_DEFAULT_FILE_PERMISSIONS;
31521   if( flags & (SQLCIPHER_OPEN_WAL|SQLCIPHER_OPEN_MAIN_JOURNAL) ){
31522     char zDb[MAX_PATHNAME+1];     /* Database file path */
31523     int nDb;                      /* Number of valid bytes in zDb */
31524     struct stat sStat;            /* Output of stat() on database file */
31525
31526     /* zPath is a path to a WAL or journal file. The following block derives
31527     ** the path to the associated database file from zPath. This block handles
31528     ** the following naming conventions:
31529     **
31530     **   "<path to db>-journal"
31531     **   "<path to db>-wal"
31532     **   "<path to db>-journalNN"
31533     **   "<path to db>-walNN"
31534     **
31535     ** where NN is a decimal number. The NN naming schemes are 
31536     ** used by the test_multiplex.c module.
31537     */
31538     nDb = sqlcipher3Strlen30(zPath) - 1; 
31539 #ifdef SQLCIPHER_ENABLE_8_3_NAMES
31540     while( nDb>0 && !sqlcipher3Isalnum(zPath[nDb]) ) nDb--;
31541     if( nDb==0 || zPath[nDb]!='-' ) return SQLCIPHER_OK;
31542 #else
31543     while( zPath[nDb]!='-' ){
31544       assert( nDb>0 );
31545       assert( zPath[nDb]!='\n' );
31546       nDb--;
31547     }
31548 #endif
31549     memcpy(zDb, zPath, nDb);
31550     zDb[nDb] = '\0';
31551
31552     if( 0==osStat(zDb, &sStat) ){
31553       *pMode = sStat.st_mode & 0777;
31554     }else{
31555       rc = SQLCIPHER_IOERR_FSTAT;
31556     }
31557   }else if( flags & SQLCIPHER_OPEN_DELETEONCLOSE ){
31558     *pMode = 0600;
31559   }
31560   return rc;
31561 }
31562
31563 /*
31564 ** Open the file zPath.
31565 ** 
31566 ** Previously, the SQLite OS layer used three functions in place of this
31567 ** one:
31568 **
31569 **     sqlcipher3OsOpenReadWrite();
31570 **     sqlcipher3OsOpenReadOnly();
31571 **     sqlcipher3OsOpenExclusive();
31572 **
31573 ** These calls correspond to the following combinations of flags:
31574 **
31575 **     ReadWrite() ->     (READWRITE | CREATE)
31576 **     ReadOnly()  ->     (READONLY) 
31577 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
31578 **
31579 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
31580 ** true, the file was configured to be automatically deleted when the
31581 ** file handle closed. To achieve the same effect using this new 
31582 ** interface, add the DELETEONCLOSE flag to those specified above for 
31583 ** OpenExclusive().
31584 */
31585 static int unixOpen(
31586   sqlcipher3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
31587   const char *zPath,           /* Pathname of file to be opened */
31588   sqlcipher3_file *pFile,         /* The file descriptor to be filled in */
31589   int flags,                   /* Input flags to control the opening */
31590   int *pOutFlags               /* Output flags returned to SQLite core */
31591 ){
31592   unixFile *p = (unixFile *)pFile;
31593   int fd = -1;                   /* File descriptor returned by open() */
31594   int openFlags = 0;             /* Flags to pass to open() */
31595   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31596   int noLock;                    /* True to omit locking primitives */
31597   int rc = SQLCIPHER_OK;            /* Function Return Code */
31598
31599   int isExclusive  = (flags & SQLCIPHER_OPEN_EXCLUSIVE);
31600   int isDelete     = (flags & SQLCIPHER_OPEN_DELETEONCLOSE);
31601   int isCreate     = (flags & SQLCIPHER_OPEN_CREATE);
31602   int isReadonly   = (flags & SQLCIPHER_OPEN_READONLY);
31603   int isReadWrite  = (flags & SQLCIPHER_OPEN_READWRITE);
31604 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31605   int isAutoProxy  = (flags & SQLCIPHER_OPEN_AUTOPROXY);
31606 #endif
31607 #if defined(__APPLE__) || SQLCIPHER_ENABLE_LOCKING_STYLE
31608   struct statfs fsInfo;
31609 #endif
31610
31611   /* If creating a master or main-file journal, this function will open
31612   ** a file-descriptor on the directory too. The first time unixSync()
31613   ** is called the directory file descriptor will be fsync()ed and close()d.
31614   */
31615   int syncDir = (isCreate && (
31616         eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
31617      || eType==SQLCIPHER_OPEN_MAIN_JOURNAL 
31618      || eType==SQLCIPHER_OPEN_WAL
31619   ));
31620
31621   /* If argument zPath is a NULL pointer, this function is required to open
31622   ** a temporary file. Use this buffer to store the file name in.
31623   */
31624   char zTmpname[MAX_PATHNAME+1];
31625   const char *zName = zPath;
31626
31627   /* Check the following statements are true: 
31628   **
31629   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
31630   **   (b) if CREATE is set, then READWRITE must also be set, and
31631   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31632   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31633   */
31634   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31635   assert(isCreate==0 || isReadWrite);
31636   assert(isExclusive==0 || isCreate);
31637   assert(isDelete==0 || isCreate);
31638
31639   /* The main DB, main journal, WAL file and master journal are never 
31640   ** automatically deleted. Nor are they ever temporary files.  */
31641   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_DB );
31642   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_JOURNAL );
31643   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MASTER_JOURNAL );
31644   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_WAL );
31645
31646   /* Assert that the upper layer has set one of the "file-type" flags. */
31647   assert( eType==SQLCIPHER_OPEN_MAIN_DB      || eType==SQLCIPHER_OPEN_TEMP_DB 
31648        || eType==SQLCIPHER_OPEN_MAIN_JOURNAL || eType==SQLCIPHER_OPEN_TEMP_JOURNAL 
31649        || eType==SQLCIPHER_OPEN_SUBJOURNAL   || eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
31650        || eType==SQLCIPHER_OPEN_TRANSIENT_DB || eType==SQLCIPHER_OPEN_WAL
31651   );
31652
31653   memset(p, 0, sizeof(unixFile));
31654
31655   if( eType==SQLCIPHER_OPEN_MAIN_DB ){
31656     UnixUnusedFd *pUnused;
31657     pUnused = findReusableFd(zName, flags);
31658     if( pUnused ){
31659       fd = pUnused->fd;
31660     }else{
31661       pUnused = sqlcipher3_malloc(sizeof(*pUnused));
31662       if( !pUnused ){
31663         return SQLCIPHER_NOMEM;
31664       }
31665     }
31666     p->pUnused = pUnused;
31667   }else if( !zName ){
31668     /* If zName is NULL, the upper layer is requesting a temp file. */
31669     assert(isDelete && !syncDir);
31670     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
31671     if( rc!=SQLCIPHER_OK ){
31672       return rc;
31673     }
31674     zName = zTmpname;
31675   }
31676
31677   /* Determine the value of the flags parameter passed to POSIX function
31678   ** open(). These must be calculated even if open() is not called, as
31679   ** they may be stored as part of the file handle and used by the 
31680   ** 'conch file' locking functions later on.  */
31681   if( isReadonly )  openFlags |= O_RDONLY;
31682   if( isReadWrite ) openFlags |= O_RDWR;
31683   if( isCreate )    openFlags |= O_CREAT;
31684   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
31685   openFlags |= (O_LARGEFILE|O_BINARY);
31686
31687   if( fd<0 ){
31688     mode_t openMode;              /* Permissions to create file with */
31689     rc = findCreateFileMode(zName, flags, &openMode);
31690     if( rc!=SQLCIPHER_OK ){
31691       assert( !p->pUnused );
31692       assert( eType==SQLCIPHER_OPEN_WAL || eType==SQLCIPHER_OPEN_MAIN_JOURNAL );
31693       return rc;
31694     }
31695     fd = robust_open(zName, openFlags, openMode);
31696     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
31697     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
31698       /* Failed to open the file for read/write access. Try read-only. */
31699       flags &= ~(SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE);
31700       openFlags &= ~(O_RDWR|O_CREAT);
31701       flags |= SQLCIPHER_OPEN_READONLY;
31702       openFlags |= O_RDONLY;
31703       isReadonly = 1;
31704       fd = robust_open(zName, openFlags, openMode);
31705     }
31706     if( fd<0 ){
31707       rc = unixLogError(SQLCIPHER_CANTOPEN_BKPT, "open", zName);
31708       goto open_finished;
31709     }
31710   }
31711   assert( fd>=0 );
31712   if( pOutFlags ){
31713     *pOutFlags = flags;
31714   }
31715
31716   if( p->pUnused ){
31717     p->pUnused->fd = fd;
31718     p->pUnused->flags = flags;
31719   }
31720
31721   if( isDelete ){
31722 #if OS_VXWORKS
31723     zPath = zName;
31724 #else
31725     osUnlink(zName);
31726 #endif
31727   }
31728 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31729   else{
31730     p->openFlags = openFlags;
31731   }
31732 #endif
31733
31734 #ifdef FD_CLOEXEC
31735   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
31736 #endif
31737
31738   noLock = eType!=SQLCIPHER_OPEN_MAIN_DB;
31739
31740   
31741 #if defined(__APPLE__) || SQLCIPHER_ENABLE_LOCKING_STYLE
31742   if( fstatfs(fd, &fsInfo) == -1 ){
31743     ((unixFile*)pFile)->lastErrno = errno;
31744     robust_close(p, fd, __LINE__);
31745     return SQLCIPHER_IOERR_ACCESS;
31746   }
31747   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
31748     ((unixFile*)pFile)->fsFlags |= SQLCIPHER_FSFLAGS_IS_MSDOS;
31749   }
31750 #endif
31751   
31752 #if SQLCIPHER_ENABLE_LOCKING_STYLE
31753 #if SQLCIPHER_PREFER_PROXY_LOCKING
31754   isAutoProxy = 1;
31755 #endif
31756   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
31757     char *envforce = getenv("SQLCIPHER_FORCE_PROXY_LOCKING");
31758     int useProxy = 0;
31759
31760     /* SQLCIPHER_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
31761     ** never use proxy, NULL means use proxy for non-local files only.  */
31762     if( envforce!=NULL ){
31763       useProxy = atoi(envforce)>0;
31764     }else{
31765       if( statfs(zPath, &fsInfo) == -1 ){
31766         /* In theory, the close(fd) call is sub-optimal. If the file opened
31767         ** with fd is a database file, and there are other connections open
31768         ** on that file that are currently holding advisory locks on it,
31769         ** then the call to close() will cancel those locks. In practice,
31770         ** we're assuming that statfs() doesn't fail very often. At least
31771         ** not while other file descriptors opened by the same process on
31772         ** the same file are working.  */
31773         p->lastErrno = errno;
31774         robust_close(p, fd, __LINE__);
31775         rc = SQLCIPHER_IOERR_ACCESS;
31776         goto open_finished;
31777       }
31778       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
31779     }
31780     if( useProxy ){
31781       rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
31782                           isDelete, isReadonly);
31783       if( rc==SQLCIPHER_OK ){
31784         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
31785         if( rc!=SQLCIPHER_OK ){
31786           /* Use unixClose to clean up the resources added in fillInUnixFile 
31787           ** and clear all the structure's references.  Specifically, 
31788           ** pFile->pMethods will be NULL so sqlcipher3OsClose will be a no-op 
31789           */
31790           unixClose(pFile);
31791           return rc;
31792         }
31793       }
31794       goto open_finished;
31795     }
31796   }
31797 #endif
31798   
31799   rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
31800                       isDelete, isReadonly);
31801 open_finished:
31802   if( rc!=SQLCIPHER_OK ){
31803     sqlcipher3_free(p->pUnused);
31804   }
31805   return rc;
31806 }
31807
31808
31809 /*
31810 ** Delete the file at zPath. If the dirSync argument is true, fsync()
31811 ** the directory after deleting the file.
31812 */
31813 static int unixDelete(
31814   sqlcipher3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
31815   const char *zPath,        /* Name of file to be deleted */
31816   int dirSync               /* If true, fsync() directory after deleting file */
31817 ){
31818   int rc = SQLCIPHER_OK;
31819   UNUSED_PARAMETER(NotUsed);
31820   SimulateIOError(return SQLCIPHER_IOERR_DELETE);
31821   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
31822     return unixLogError(SQLCIPHER_IOERR_DELETE, "unlink", zPath);
31823   }
31824 #ifndef SQLCIPHER_DISABLE_DIRSYNC
31825   if( dirSync ){
31826     int fd;
31827     rc = osOpenDirectory(zPath, &fd);
31828     if( rc==SQLCIPHER_OK ){
31829 #if OS_VXWORKS
31830       if( fsync(fd)==-1 )
31831 #else
31832       if( fsync(fd) )
31833 #endif
31834       {
31835         rc = unixLogError(SQLCIPHER_IOERR_DIR_FSYNC, "fsync", zPath);
31836       }
31837       robust_close(0, fd, __LINE__);
31838     }else if( rc==SQLCIPHER_CANTOPEN ){
31839       rc = SQLCIPHER_OK;
31840     }
31841   }
31842 #endif
31843   return rc;
31844 }
31845
31846 /*
31847 ** Test the existance of or access permissions of file zPath. The
31848 ** test performed depends on the value of flags:
31849 **
31850 **     SQLCIPHER_ACCESS_EXISTS: Return 1 if the file exists
31851 **     SQLCIPHER_ACCESS_READWRITE: Return 1 if the file is read and writable.
31852 **     SQLCIPHER_ACCESS_READONLY: Return 1 if the file is readable.
31853 **
31854 ** Otherwise return 0.
31855 */
31856 static int unixAccess(
31857   sqlcipher3_vfs *NotUsed,   /* The VFS containing this xAccess method */
31858   const char *zPath,      /* Path of the file to examine */
31859   int flags,              /* What do we want to learn about the zPath file? */
31860   int *pResOut            /* Write result boolean here */
31861 ){
31862   int amode = 0;
31863   UNUSED_PARAMETER(NotUsed);
31864   SimulateIOError( return SQLCIPHER_IOERR_ACCESS; );
31865   switch( flags ){
31866     case SQLCIPHER_ACCESS_EXISTS:
31867       amode = F_OK;
31868       break;
31869     case SQLCIPHER_ACCESS_READWRITE:
31870       amode = W_OK|R_OK;
31871       break;
31872     case SQLCIPHER_ACCESS_READ:
31873       amode = R_OK;
31874       break;
31875
31876     default:
31877       assert(!"Invalid flags argument");
31878   }
31879   *pResOut = (osAccess(zPath, amode)==0);
31880   if( flags==SQLCIPHER_ACCESS_EXISTS && *pResOut ){
31881     struct stat buf;
31882     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
31883       *pResOut = 0;
31884     }
31885   }
31886   return SQLCIPHER_OK;
31887 }
31888
31889
31890 /*
31891 ** Turn a relative pathname into a full pathname. The relative path
31892 ** is stored as a nul-terminated string in the buffer pointed to by
31893 ** zPath. 
31894 **
31895 ** zOut points to a buffer of at least sqlcipher3_vfs.mxPathname bytes 
31896 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
31897 ** this buffer before returning.
31898 */
31899 static int unixFullPathname(
31900   sqlcipher3_vfs *pVfs,            /* Pointer to vfs object */
31901   const char *zPath,            /* Possibly relative input path */
31902   int nOut,                     /* Size of output buffer in bytes */
31903   char *zOut                    /* Output buffer */
31904 ){
31905
31906   /* It's odd to simulate an io-error here, but really this is just
31907   ** using the io-error infrastructure to test that SQLite handles this
31908   ** function failing. This function could fail if, for example, the
31909   ** current working directory has been unlinked.
31910   */
31911   SimulateIOError( return SQLCIPHER_ERROR );
31912
31913   assert( pVfs->mxPathname==MAX_PATHNAME );
31914   UNUSED_PARAMETER(pVfs);
31915
31916   zOut[nOut-1] = '\0';
31917   if( zPath[0]=='/' ){
31918     sqlcipher3_snprintf(nOut, zOut, "%s", zPath);
31919   }else{
31920     int nCwd;
31921     if( osGetcwd(zOut, nOut-1)==0 ){
31922       return unixLogError(SQLCIPHER_CANTOPEN_BKPT, "getcwd", zPath);
31923     }
31924     nCwd = (int)strlen(zOut);
31925     sqlcipher3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
31926   }
31927   return SQLCIPHER_OK;
31928 }
31929
31930
31931 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
31932 /*
31933 ** Interfaces for opening a shared library, finding entry points
31934 ** within the shared library, and closing the shared library.
31935 */
31936 #include <dlfcn.h>
31937 static void *unixDlOpen(sqlcipher3_vfs *NotUsed, const char *zFilename){
31938   UNUSED_PARAMETER(NotUsed);
31939   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
31940 }
31941
31942 /*
31943 ** SQLite calls this function immediately after a call to unixDlSym() or
31944 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
31945 ** message is available, it is written to zBufOut. If no error message
31946 ** is available, zBufOut is left unmodified and SQLite uses a default
31947 ** error message.
31948 */
31949 static void unixDlError(sqlcipher3_vfs *NotUsed, int nBuf, char *zBufOut){
31950   const char *zErr;
31951   UNUSED_PARAMETER(NotUsed);
31952   unixEnterMutex();
31953   zErr = dlerror();
31954   if( zErr ){
31955     sqlcipher3_snprintf(nBuf, zBufOut, "%s", zErr);
31956   }
31957   unixLeaveMutex();
31958 }
31959 static void (*unixDlSym(sqlcipher3_vfs *NotUsed, void *p, const char*zSym))(void){
31960   /* 
31961   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
31962   ** cast into a pointer to a function.  And yet the library dlsym() routine
31963   ** returns a void* which is really a pointer to a function.  So how do we
31964   ** use dlsym() with -pedantic-errors?
31965   **
31966   ** Variable x below is defined to be a pointer to a function taking
31967   ** parameters void* and const char* and returning a pointer to a function.
31968   ** We initialize x by assigning it a pointer to the dlsym() function.
31969   ** (That assignment requires a cast.)  Then we call the function that
31970   ** x points to.  
31971   **
31972   ** This work-around is unlikely to work correctly on any system where
31973   ** you really cannot cast a function pointer into void*.  But then, on the
31974   ** other hand, dlsym() will not work on such a system either, so we have
31975   ** not really lost anything.
31976   */
31977   void (*(*x)(void*,const char*))(void);
31978   UNUSED_PARAMETER(NotUsed);
31979   x = (void(*(*)(void*,const char*))(void))dlsym;
31980   return (*x)(p, zSym);
31981 }
31982 static void unixDlClose(sqlcipher3_vfs *NotUsed, void *pHandle){
31983   UNUSED_PARAMETER(NotUsed);
31984   dlclose(pHandle);
31985 }
31986 #else /* if SQLCIPHER_OMIT_LOAD_EXTENSION is defined: */
31987   #define unixDlOpen  0
31988   #define unixDlError 0
31989   #define unixDlSym   0
31990   #define unixDlClose 0
31991 #endif
31992
31993 /*
31994 ** Write nBuf bytes of random data to the supplied buffer zBuf.
31995 */
31996 static int unixRandomness(sqlcipher3_vfs *NotUsed, int nBuf, char *zBuf){
31997   UNUSED_PARAMETER(NotUsed);
31998   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
31999
32000   /* We have to initialize zBuf to prevent valgrind from reporting
32001   ** errors.  The reports issued by valgrind are incorrect - we would
32002   ** prefer that the randomness be increased by making use of the
32003   ** uninitialized space in zBuf - but valgrind errors tend to worry
32004   ** some users.  Rather than argue, it seems easier just to initialize
32005   ** the whole array and silence valgrind, even if that means less randomness
32006   ** in the random seed.
32007   **
32008   ** When testing, initializing zBuf[] to zero is all we do.  That means
32009   ** that we always use the same random number sequence.  This makes the
32010   ** tests repeatable.
32011   */
32012   memset(zBuf, 0, nBuf);
32013 #if !defined(SQLCIPHER_TEST)
32014   {
32015     int pid, fd;
32016     fd = robust_open("/dev/urandom", O_RDONLY, 0);
32017     if( fd<0 ){
32018       time_t t;
32019       time(&t);
32020       memcpy(zBuf, &t, sizeof(t));
32021       pid = getpid();
32022       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
32023       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
32024       nBuf = sizeof(t) + sizeof(pid);
32025     }else{
32026       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
32027       robust_close(0, fd, __LINE__);
32028     }
32029   }
32030 #endif
32031   return nBuf;
32032 }
32033
32034
32035 /*
32036 ** Sleep for a little while.  Return the amount of time slept.
32037 ** The argument is the number of microseconds we want to sleep.
32038 ** The return value is the number of microseconds of sleep actually
32039 ** requested from the underlying operating system, a number which
32040 ** might be greater than or equal to the argument, but not less
32041 ** than the argument.
32042 */
32043 static int unixSleep(sqlcipher3_vfs *NotUsed, int microseconds){
32044 #if OS_VXWORKS
32045   struct timespec sp;
32046
32047   sp.tv_sec = microseconds / 1000000;
32048   sp.tv_nsec = (microseconds % 1000000) * 1000;
32049   nanosleep(&sp, NULL);
32050   UNUSED_PARAMETER(NotUsed);
32051   return microseconds;
32052 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
32053   usleep(microseconds);
32054   UNUSED_PARAMETER(NotUsed);
32055   return microseconds;
32056 #else
32057   int seconds = (microseconds+999999)/1000000;
32058   sleep(seconds);
32059   UNUSED_PARAMETER(NotUsed);
32060   return seconds*1000000;
32061 #endif
32062 }
32063
32064 /*
32065 ** The following variable, if set to a non-zero value, is interpreted as
32066 ** the number of seconds since 1970 and is used to set the result of
32067 ** sqlcipher3OsCurrentTime() during testing.
32068 */
32069 #ifdef SQLCIPHER_TEST
32070 SQLCIPHER_API int sqlcipher3_current_time = 0;  /* Fake system time in seconds since 1970. */
32071 #endif
32072
32073 /*
32074 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
32075 ** the current time and date as a Julian Day number times 86_400_000.  In
32076 ** other words, write into *piNow the number of milliseconds since the Julian
32077 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32078 ** proleptic Gregorian calendar.
32079 **
32080 ** On success, return SQLCIPHER_OK.  Return SQLCIPHER_ERROR if the time and date 
32081 ** cannot be found.
32082 */
32083 static int unixCurrentTimeInt64(sqlcipher3_vfs *NotUsed, sqlcipher3_int64 *piNow){
32084   static const sqlcipher3_int64 unixEpoch = 24405875*(sqlcipher3_int64)8640000;
32085   int rc = SQLCIPHER_OK;
32086 #if defined(NO_GETTOD)
32087   time_t t;
32088   time(&t);
32089   *piNow = ((sqlcipher3_int64)t)*1000 + unixEpoch;
32090 #elif OS_VXWORKS
32091   struct timespec sNow;
32092   clock_gettime(CLOCK_REALTIME, &sNow);
32093   *piNow = unixEpoch + 1000*(sqlcipher3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
32094 #else
32095   struct timeval sNow;
32096   if( gettimeofday(&sNow, 0)==0 ){
32097     *piNow = unixEpoch + 1000*(sqlcipher3_int64)sNow.tv_sec + sNow.tv_usec/1000;
32098   }else{
32099     rc = SQLCIPHER_ERROR;
32100   }
32101 #endif
32102
32103 #ifdef SQLCIPHER_TEST
32104   if( sqlcipher3_current_time ){
32105     *piNow = 1000*(sqlcipher3_int64)sqlcipher3_current_time + unixEpoch;
32106   }
32107 #endif
32108   UNUSED_PARAMETER(NotUsed);
32109   return rc;
32110 }
32111
32112 /*
32113 ** Find the current time (in Universal Coordinated Time).  Write the
32114 ** current time and date as a Julian Day number into *prNow and
32115 ** return 0.  Return 1 if the time and date cannot be found.
32116 */
32117 static int unixCurrentTime(sqlcipher3_vfs *NotUsed, double *prNow){
32118   sqlcipher3_int64 i = 0;
32119   int rc;
32120   UNUSED_PARAMETER(NotUsed);
32121   rc = unixCurrentTimeInt64(0, &i);
32122   *prNow = i/86400000.0;
32123   return rc;
32124 }
32125
32126 /*
32127 ** We added the xGetLastError() method with the intention of providing
32128 ** better low-level error messages when operating-system problems come up
32129 ** during SQLite operation.  But so far, none of that has been implemented
32130 ** in the core.  So this routine is never called.  For now, it is merely
32131 ** a place-holder.
32132 */
32133 static int unixGetLastError(sqlcipher3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
32134   UNUSED_PARAMETER(NotUsed);
32135   UNUSED_PARAMETER(NotUsed2);
32136   UNUSED_PARAMETER(NotUsed3);
32137   return 0;
32138 }
32139
32140
32141 /*
32142 ************************ End of sqlcipher3_vfs methods ***************************
32143 ******************************************************************************/
32144
32145 /******************************************************************************
32146 ************************** Begin Proxy Locking ********************************
32147 **
32148 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
32149 ** other locking methods on secondary lock files.  Proxy locking is a
32150 ** meta-layer over top of the primitive locking implemented above.  For
32151 ** this reason, the division that implements of proxy locking is deferred
32152 ** until late in the file (here) after all of the other I/O methods have
32153 ** been defined - so that the primitive locking methods are available
32154 ** as services to help with the implementation of proxy locking.
32155 **
32156 ****
32157 **
32158 ** The default locking schemes in SQLite use byte-range locks on the
32159 ** database file to coordinate safe, concurrent access by multiple readers
32160 ** and writers [http://sqlcipher.org/lockingv3.html].  The five file locking
32161 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
32162 ** as POSIX read & write locks over fixed set of locations (via fsctl),
32163 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
32164 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
32165 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
32166 ** address in the shared range is taken for a SHARED lock, the entire
32167 ** shared range is taken for an EXCLUSIVE lock):
32168 **
32169 **      PENDING_BYTE        0x40000000                  
32170 **      RESERVED_BYTE       0x40000001
32171 **      SHARED_RANGE        0x40000002 -> 0x40000200
32172 **
32173 ** This works well on the local file system, but shows a nearly 100x
32174 ** slowdown in read performance on AFP because the AFP client disables
32175 ** the read cache when byte-range locks are present.  Enabling the read
32176 ** cache exposes a cache coherency problem that is present on all OS X
32177 ** supported network file systems.  NFS and AFP both observe the
32178 ** close-to-open semantics for ensuring cache coherency
32179 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
32180 ** address the requirements for concurrent database access by multiple
32181 ** readers and writers
32182 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
32183 **
32184 ** To address the performance and cache coherency issues, proxy file locking
32185 ** changes the way database access is controlled by limiting access to a
32186 ** single host at a time and moving file locks off of the database file
32187 ** and onto a proxy file on the local file system.  
32188 **
32189 **
32190 ** Using proxy locks
32191 ** -----------------
32192 **
32193 ** C APIs
32194 **
32195 **  sqlcipher3_file_control(db, dbname, SQLCIPHER_SET_LOCKPROXYFILE,
32196 **                       <proxy_path> | ":auto:");
32197 **  sqlcipher3_file_control(db, dbname, SQLCIPHER_GET_LOCKPROXYFILE, &<proxy_path>);
32198 **
32199 **
32200 ** SQL pragmas
32201 **
32202 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
32203 **  PRAGMA [database.]lock_proxy_file
32204 **
32205 ** Specifying ":auto:" means that if there is a conch file with a matching
32206 ** host ID in it, the proxy path in the conch file will be used, otherwise
32207 ** a proxy path based on the user's temp dir
32208 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
32209 ** actual proxy file name is generated from the name and path of the
32210 ** database file.  For example:
32211 **
32212 **       For database path "/Users/me/foo.db" 
32213 **       The lock path will be "<tmpdir>/sqlcipherplocks/_Users_me_foo.db:auto:")
32214 **
32215 ** Once a lock proxy is configured for a database connection, it can not
32216 ** be removed, however it may be switched to a different proxy path via
32217 ** the above APIs (assuming the conch file is not being held by another
32218 ** connection or process). 
32219 **
32220 **
32221 ** How proxy locking works
32222 ** -----------------------
32223 **
32224 ** Proxy file locking relies primarily on two new supporting files: 
32225 **
32226 **   *  conch file to limit access to the database file to a single host
32227 **      at a time
32228 **
32229 **   *  proxy file to act as a proxy for the advisory locks normally
32230 **      taken on the database
32231 **
32232 ** The conch file - to use a proxy file, sqlcipher must first "hold the conch"
32233 ** by taking an sqlcipher-style shared lock on the conch file, reading the
32234 ** contents and comparing the host's unique host ID (see below) and lock
32235 ** proxy path against the values stored in the conch.  The conch file is
32236 ** stored in the same directory as the database file and the file name
32237 ** is patterned after the database file name as ".<databasename>-conch".
32238 ** If the conch file does not exist, or it's contents do not match the
32239 ** host ID and/or proxy path, then the lock is escalated to an exclusive
32240 ** lock and the conch file contents is updated with the host ID and proxy
32241 ** path and the lock is downgraded to a shared lock again.  If the conch
32242 ** is held by another process (with a shared lock), the exclusive lock
32243 ** will fail and SQLCIPHER_BUSY is returned.
32244 **
32245 ** The proxy file - a single-byte file used for all advisory file locks
32246 ** normally taken on the database file.   This allows for safe sharing
32247 ** of the database file for multiple readers and writers on the same
32248 ** host (the conch ensures that they all use the same local lock file).
32249 **
32250 ** Requesting the lock proxy does not immediately take the conch, it is
32251 ** only taken when the first request to lock database file is made.  
32252 ** This matches the semantics of the traditional locking behavior, where
32253 ** opening a connection to a database file does not take a lock on it.
32254 ** The shared lock and an open file descriptor are maintained until 
32255 ** the connection to the database is closed. 
32256 **
32257 ** The proxy file and the lock file are never deleted so they only need
32258 ** to be created the first time they are used.
32259 **
32260 ** Configuration options
32261 ** ---------------------
32262 **
32263 **  SQLCIPHER_PREFER_PROXY_LOCKING
32264 **
32265 **       Database files accessed on non-local file systems are
32266 **       automatically configured for proxy locking, lock files are
32267 **       named automatically using the same logic as
32268 **       PRAGMA lock_proxy_file=":auto:"
32269 **    
32270 **  SQLCIPHER_PROXY_DEBUG
32271 **
32272 **       Enables the logging of error messages during host id file
32273 **       retrieval and creation
32274 **
32275 **  LOCKPROXYDIR
32276 **
32277 **       Overrides the default directory used for lock proxy files that
32278 **       are named automatically via the ":auto:" setting
32279 **
32280 **  SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS
32281 **
32282 **       Permissions to use when creating a directory for storing the
32283 **       lock proxy files, only used when LOCKPROXYDIR is not set.
32284 **    
32285 **    
32286 ** As mentioned above, when compiled with SQLCIPHER_PREFER_PROXY_LOCKING,
32287 ** setting the environment variable SQLCIPHER_FORCE_PROXY_LOCKING to 1 will
32288 ** force proxy locking to be used for every database file opened, and 0
32289 ** will force automatic proxy locking to be disabled for all database
32290 ** files (explicity calling the SQLCIPHER_SET_LOCKPROXYFILE pragma or
32291 ** sqlcipher_file_control API is not affected by SQLCIPHER_FORCE_PROXY_LOCKING).
32292 */
32293
32294 /*
32295 ** Proxy locking is only available on MacOSX 
32296 */
32297 #if defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE
32298
32299 /*
32300 ** The proxyLockingContext has the path and file structures for the remote 
32301 ** and local proxy files in it
32302 */
32303 typedef struct proxyLockingContext proxyLockingContext;
32304 struct proxyLockingContext {
32305   unixFile *conchFile;         /* Open conch file */
32306   char *conchFilePath;         /* Name of the conch file */
32307   unixFile *lockProxy;         /* Open proxy lock file */
32308   char *lockProxyPath;         /* Name of the proxy lock file */
32309   char *dbPath;                /* Name of the open file */
32310   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
32311   void *oldLockingContext;     /* Original lockingcontext to restore on close */
32312   sqlcipher3_io_methods const *pOldMethod;     /* Original I/O methods for close */
32313 };
32314
32315 /* 
32316 ** The proxy lock file path for the database at dbPath is written into lPath, 
32317 ** which must point to valid, writable memory large enough for a maxLen length
32318 ** file path. 
32319 */
32320 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
32321   int len;
32322   int dbLen;
32323   int i;
32324
32325 #ifdef LOCKPROXYDIR
32326   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
32327 #else
32328 # ifdef _CS_DARWIN_USER_TEMP_DIR
32329   {
32330     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
32331       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
32332                lPath, errno, getpid()));
32333       return SQLCIPHER_IOERR_LOCK;
32334     }
32335     len = strlcat(lPath, "sqlcipherplocks", maxLen);    
32336   }
32337 # else
32338   len = strlcpy(lPath, "/tmp/", maxLen);
32339 # endif
32340 #endif
32341
32342   if( lPath[len-1]!='/' ){
32343     len = strlcat(lPath, "/", maxLen);
32344   }
32345   
32346   /* transform the db path to a unique cache name */
32347   dbLen = (int)strlen(dbPath);
32348   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
32349     char c = dbPath[i];
32350     lPath[i+len] = (c=='/')?'_':c;
32351   }
32352   lPath[i+len]='\0';
32353   strlcat(lPath, ":auto:", maxLen);
32354   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
32355   return SQLCIPHER_OK;
32356 }
32357
32358 /* 
32359  ** Creates the lock file and any missing directories in lockPath
32360  */
32361 static int proxyCreateLockPath(const char *lockPath){
32362   int i, len;
32363   char buf[MAXPATHLEN];
32364   int start = 0;
32365   
32366   assert(lockPath!=NULL);
32367   /* try to create all the intermediate directories */
32368   len = (int)strlen(lockPath);
32369   buf[0] = lockPath[0];
32370   for( i=1; i<len; i++ ){
32371     if( lockPath[i] == '/' && (i - start > 0) ){
32372       /* only mkdir if leaf dir != "." or "/" or ".." */
32373       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
32374          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
32375         buf[i]='\0';
32376         if( mkdir(buf, SQLCIPHER_DEFAULT_PROXYDIR_PERMISSIONS) ){
32377           int err=errno;
32378           if( err!=EEXIST ) {
32379             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
32380                      "'%s' proxy lock path=%s pid=%d\n",
32381                      buf, strerror(err), lockPath, getpid()));
32382             return err;
32383           }
32384         }
32385       }
32386       start=i+1;
32387     }
32388     buf[i] = lockPath[i];
32389   }
32390   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
32391   return 0;
32392 }
32393
32394 /*
32395 ** Create a new VFS file descriptor (stored in memory obtained from
32396 ** sqlcipher3_malloc) and open the file named "path" in the file descriptor.
32397 **
32398 ** The caller is responsible not only for closing the file descriptor
32399 ** but also for freeing the memory associated with the file descriptor.
32400 */
32401 static int proxyCreateUnixFile(
32402     const char *path,        /* path for the new unixFile */
32403     unixFile **ppFile,       /* unixFile created and returned by ref */
32404     int islockfile           /* if non zero missing dirs will be created */
32405 ) {
32406   int fd = -1;
32407   unixFile *pNew;
32408   int rc = SQLCIPHER_OK;
32409   int openFlags = O_RDWR | O_CREAT;
32410   sqlcipher3_vfs dummyVfs;
32411   int terrno = 0;
32412   UnixUnusedFd *pUnused = NULL;
32413
32414   /* 1. first try to open/create the file
32415   ** 2. if that fails, and this is a lock file (not-conch), try creating
32416   ** the parent directories and then try again.
32417   ** 3. if that fails, try to open the file read-only
32418   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
32419   */
32420   pUnused = findReusableFd(path, openFlags);
32421   if( pUnused ){
32422     fd = pUnused->fd;
32423   }else{
32424     pUnused = sqlcipher3_malloc(sizeof(*pUnused));
32425     if( !pUnused ){
32426       return SQLCIPHER_NOMEM;
32427     }
32428   }
32429   if( fd<0 ){
32430     fd = robust_open(path, openFlags, SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32431     terrno = errno;
32432     if( fd<0 && errno==ENOENT && islockfile ){
32433       if( proxyCreateLockPath(path) == SQLCIPHER_OK ){
32434         fd = robust_open(path, openFlags, SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32435       }
32436     }
32437   }
32438   if( fd<0 ){
32439     openFlags = O_RDONLY;
32440     fd = robust_open(path, openFlags, SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32441     terrno = errno;
32442   }
32443   if( fd<0 ){
32444     if( islockfile ){
32445       return SQLCIPHER_BUSY;
32446     }
32447     switch (terrno) {
32448       case EACCES:
32449         return SQLCIPHER_PERM;
32450       case EIO: 
32451         return SQLCIPHER_IOERR_LOCK; /* even though it is the conch */
32452       default:
32453         return SQLCIPHER_CANTOPEN_BKPT;
32454     }
32455   }
32456   
32457   pNew = (unixFile *)sqlcipher3_malloc(sizeof(*pNew));
32458   if( pNew==NULL ){
32459     rc = SQLCIPHER_NOMEM;
32460     goto end_create_proxy;
32461   }
32462   memset(pNew, 0, sizeof(unixFile));
32463   pNew->openFlags = openFlags;
32464   memset(&dummyVfs, 0, sizeof(dummyVfs));
32465   dummyVfs.pAppData = (void*)&autolockIoFinder;
32466   dummyVfs.zName = "dummy";
32467   pUnused->fd = fd;
32468   pUnused->flags = openFlags;
32469   pNew->pUnused = pUnused;
32470   
32471   rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlcipher3_file*)pNew, path, 0, 0, 0);
32472   if( rc==SQLCIPHER_OK ){
32473     *ppFile = pNew;
32474     return SQLCIPHER_OK;
32475   }
32476 end_create_proxy:    
32477   robust_close(pNew, fd, __LINE__);
32478   sqlcipher3_free(pNew);
32479   sqlcipher3_free(pUnused);
32480   return rc;
32481 }
32482
32483 #ifdef SQLCIPHER_TEST
32484 /* simulate multiple hosts by creating unique hostid file paths */
32485 SQLCIPHER_API int sqlcipher3_hostid_num = 0;
32486 #endif
32487
32488 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
32489
32490 /* Not always defined in the headers as it ought to be */
32491 extern int gethostuuid(uuid_t id, const struct timespec *wait);
32492
32493 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
32494 ** bytes of writable memory.
32495 */
32496 static int proxyGetHostID(unsigned char *pHostID, int *pError){
32497   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
32498   memset(pHostID, 0, PROXY_HOSTIDLEN);
32499 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
32500                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
32501   {
32502     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
32503     if( gethostuuid(pHostID, &timeout) ){
32504       int err = errno;
32505       if( pError ){
32506         *pError = err;
32507       }
32508       return SQLCIPHER_IOERR;
32509     }
32510   }
32511 #else
32512   UNUSED_PARAMETER(pError);
32513 #endif
32514 #ifdef SQLCIPHER_TEST
32515   /* simulate multiple hosts by creating unique hostid file paths */
32516   if( sqlcipher3_hostid_num != 0){
32517     pHostID[0] = (char)(pHostID[0] + (char)(sqlcipher3_hostid_num & 0xFF));
32518   }
32519 #endif
32520   
32521   return SQLCIPHER_OK;
32522 }
32523
32524 /* The conch file contains the header, host id and lock file path
32525  */
32526 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
32527 #define PROXY_HEADERLEN    1   /* conch file header length */
32528 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
32529 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
32530
32531 /* 
32532 ** Takes an open conch file, copies the contents to a new path and then moves 
32533 ** it back.  The newly created file's file descriptor is assigned to the
32534 ** conch file structure and finally the original conch file descriptor is 
32535 ** closed.  Returns zero if successful.
32536 */
32537 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
32538   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32539   unixFile *conchFile = pCtx->conchFile;
32540   char tPath[MAXPATHLEN];
32541   char buf[PROXY_MAXCONCHLEN];
32542   char *cPath = pCtx->conchFilePath;
32543   size_t readLen = 0;
32544   size_t pathLen = 0;
32545   char errmsg[64] = "";
32546   int fd = -1;
32547   int rc = -1;
32548   UNUSED_PARAMETER(myHostID);
32549
32550   /* create a new path by replace the trailing '-conch' with '-break' */
32551   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
32552   if( pathLen>MAXPATHLEN || pathLen<6 || 
32553      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
32554     sqlcipher3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
32555     goto end_breaklock;
32556   }
32557   /* read the conch content */
32558   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
32559   if( readLen<PROXY_PATHINDEX ){
32560     sqlcipher3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
32561     goto end_breaklock;
32562   }
32563   /* write it out to the temporary break file */
32564   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
32565                    SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32566   if( fd<0 ){
32567     sqlcipher3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
32568     goto end_breaklock;
32569   }
32570   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
32571     sqlcipher3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
32572     goto end_breaklock;
32573   }
32574   if( rename(tPath, cPath) ){
32575     sqlcipher3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
32576     goto end_breaklock;
32577   }
32578   rc = 0;
32579   fprintf(stderr, "broke stale lock on %s\n", cPath);
32580   robust_close(pFile, conchFile->h, __LINE__);
32581   conchFile->h = fd;
32582   conchFile->openFlags = O_RDWR | O_CREAT;
32583
32584 end_breaklock:
32585   if( rc ){
32586     if( fd>=0 ){
32587       osUnlink(tPath);
32588       robust_close(pFile, fd, __LINE__);
32589     }
32590     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
32591   }
32592   return rc;
32593 }
32594
32595 /* Take the requested lock on the conch file and break a stale lock if the 
32596 ** host id matches.
32597 */
32598 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
32599   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32600   unixFile *conchFile = pCtx->conchFile;
32601   int rc = SQLCIPHER_OK;
32602   int nTries = 0;
32603   struct timespec conchModTime;
32604   
32605   memset(&conchModTime, 0, sizeof(conchModTime));
32606   do {
32607     rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, lockType);
32608     nTries ++;
32609     if( rc==SQLCIPHER_BUSY ){
32610       /* If the lock failed (busy):
32611        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
32612        * 2nd try: fail if the mod time changed or host id is different, wait 
32613        *           10 sec and try again
32614        * 3rd try: break the lock unless the mod time has changed.
32615        */
32616       struct stat buf;
32617       if( osFstat(conchFile->h, &buf) ){
32618         pFile->lastErrno = errno;
32619         return SQLCIPHER_IOERR_LOCK;
32620       }
32621       
32622       if( nTries==1 ){
32623         conchModTime = buf.st_mtimespec;
32624         usleep(500000); /* wait 0.5 sec and try the lock again*/
32625         continue;  
32626       }
32627
32628       assert( nTries>1 );
32629       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
32630          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
32631         return SQLCIPHER_BUSY;
32632       }
32633       
32634       if( nTries==2 ){  
32635         char tBuf[PROXY_MAXCONCHLEN];
32636         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
32637         if( len<0 ){
32638           pFile->lastErrno = errno;
32639           return SQLCIPHER_IOERR_LOCK;
32640         }
32641         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
32642           /* don't break the lock if the host id doesn't match */
32643           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
32644             return SQLCIPHER_BUSY;
32645           }
32646         }else{
32647           /* don't break the lock on short read or a version mismatch */
32648           return SQLCIPHER_BUSY;
32649         }
32650         usleep(10000000); /* wait 10 sec and try the lock again */
32651         continue; 
32652       }
32653       
32654       assert( nTries==3 );
32655       if( 0==proxyBreakConchLock(pFile, myHostID) ){
32656         rc = SQLCIPHER_OK;
32657         if( lockType==EXCLUSIVE_LOCK ){
32658           rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, SHARED_LOCK);          
32659         }
32660         if( !rc ){
32661           rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, lockType);
32662         }
32663       }
32664     }
32665   } while( rc==SQLCIPHER_BUSY && nTries<3 );
32666   
32667   return rc;
32668 }
32669
32670 /* Takes the conch by taking a shared lock and read the contents conch, if 
32671 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
32672 ** lockPath means that the lockPath in the conch file will be used if the 
32673 ** host IDs match, or a new lock path will be generated automatically 
32674 ** and written to the conch file.
32675 */
32676 static int proxyTakeConch(unixFile *pFile){
32677   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32678   
32679   if( pCtx->conchHeld!=0 ){
32680     return SQLCIPHER_OK;
32681   }else{
32682     unixFile *conchFile = pCtx->conchFile;
32683     uuid_t myHostID;
32684     int pError = 0;
32685     char readBuf[PROXY_MAXCONCHLEN];
32686     char lockPath[MAXPATHLEN];
32687     char *tempLockPath = NULL;
32688     int rc = SQLCIPHER_OK;
32689     int createConch = 0;
32690     int hostIdMatch = 0;
32691     int readLen = 0;
32692     int tryOldLockPath = 0;
32693     int forceNewLockPath = 0;
32694     
32695     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
32696              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
32697
32698     rc = proxyGetHostID(myHostID, &pError);
32699     if( (rc&0xff)==SQLCIPHER_IOERR ){
32700       pFile->lastErrno = pError;
32701       goto end_takeconch;
32702     }
32703     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
32704     if( rc!=SQLCIPHER_OK ){
32705       goto end_takeconch;
32706     }
32707     /* read the existing conch file */
32708     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
32709     if( readLen<0 ){
32710       /* I/O error: lastErrno set by seekAndRead */
32711       pFile->lastErrno = conchFile->lastErrno;
32712       rc = SQLCIPHER_IOERR_READ;
32713       goto end_takeconch;
32714     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
32715              readBuf[0]!=(char)PROXY_CONCHVERSION ){
32716       /* a short read or version format mismatch means we need to create a new 
32717       ** conch file. 
32718       */
32719       createConch = 1;
32720     }
32721     /* if the host id matches and the lock path already exists in the conch
32722     ** we'll try to use the path there, if we can't open that path, we'll 
32723     ** retry with a new auto-generated path 
32724     */
32725     do { /* in case we need to try again for an :auto: named lock file */
32726
32727       if( !createConch && !forceNewLockPath ){
32728         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
32729                                   PROXY_HOSTIDLEN);
32730         /* if the conch has data compare the contents */
32731         if( !pCtx->lockProxyPath ){
32732           /* for auto-named local lock file, just check the host ID and we'll
32733            ** use the local lock file path that's already in there
32734            */
32735           if( hostIdMatch ){
32736             size_t pathLen = (readLen - PROXY_PATHINDEX);
32737             
32738             if( pathLen>=MAXPATHLEN ){
32739               pathLen=MAXPATHLEN-1;
32740             }
32741             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
32742             lockPath[pathLen] = 0;
32743             tempLockPath = lockPath;
32744             tryOldLockPath = 1;
32745             /* create a copy of the lock path if the conch is taken */
32746             goto end_takeconch;
32747           }
32748         }else if( hostIdMatch
32749                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
32750                            readLen-PROXY_PATHINDEX)
32751         ){
32752           /* conch host and lock path match */
32753           goto end_takeconch; 
32754         }
32755       }
32756       
32757       /* if the conch isn't writable and doesn't match, we can't take it */
32758       if( (conchFile->openFlags&O_RDWR) == 0 ){
32759         rc = SQLCIPHER_BUSY;
32760         goto end_takeconch;
32761       }
32762       
32763       /* either the conch didn't match or we need to create a new one */
32764       if( !pCtx->lockProxyPath ){
32765         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
32766         tempLockPath = lockPath;
32767         /* create a copy of the lock path _only_ if the conch is taken */
32768       }
32769       
32770       /* update conch with host and path (this will fail if other process
32771       ** has a shared lock already), if the host id matches, use the big
32772       ** stick.
32773       */
32774       futimes(conchFile->h, NULL);
32775       if( hostIdMatch && !createConch ){
32776         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
32777           /* We are trying for an exclusive lock but another thread in this
32778            ** same process is still holding a shared lock. */
32779           rc = SQLCIPHER_BUSY;
32780         } else {          
32781           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
32782         }
32783       }else{
32784         rc = conchFile->pMethod->xLock((sqlcipher3_file*)conchFile, EXCLUSIVE_LOCK);
32785       }
32786       if( rc==SQLCIPHER_OK ){
32787         char writeBuffer[PROXY_MAXCONCHLEN];
32788         int writeSize = 0;
32789         
32790         writeBuffer[0] = (char)PROXY_CONCHVERSION;
32791         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
32792         if( pCtx->lockProxyPath!=NULL ){
32793           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
32794         }else{
32795           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
32796         }
32797         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
32798         robust_ftruncate(conchFile->h, writeSize);
32799         rc = unixWrite((sqlcipher3_file *)conchFile, writeBuffer, writeSize, 0);
32800         fsync(conchFile->h);
32801         /* If we created a new conch file (not just updated the contents of a 
32802          ** valid conch file), try to match the permissions of the database 
32803          */
32804         if( rc==SQLCIPHER_OK && createConch ){
32805           struct stat buf;
32806           int err = osFstat(pFile->h, &buf);
32807           if( err==0 ){
32808             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
32809                                         S_IROTH|S_IWOTH);
32810             /* try to match the database file R/W permissions, ignore failure */
32811 #ifndef SQLCIPHER_PROXY_DEBUG
32812             osFchmod(conchFile->h, cmode);
32813 #else
32814             do{
32815               rc = osFchmod(conchFile->h, cmode);
32816             }while( rc==(-1) && errno==EINTR );
32817             if( rc!=0 ){
32818               int code = errno;
32819               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
32820                       cmode, code, strerror(code));
32821             } else {
32822               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
32823             }
32824           }else{
32825             int code = errno;
32826             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
32827                     err, code, strerror(code));
32828 #endif
32829           }
32830         }
32831       }
32832       conchFile->pMethod->xUnlock((sqlcipher3_file*)conchFile, SHARED_LOCK);
32833       
32834     end_takeconch:
32835       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
32836       if( rc==SQLCIPHER_OK && pFile->openFlags ){
32837         int fd;
32838         if( pFile->h>=0 ){
32839           robust_close(pFile, pFile->h, __LINE__);
32840         }
32841         pFile->h = -1;
32842         fd = robust_open(pCtx->dbPath, pFile->openFlags,
32843                       SQLCIPHER_DEFAULT_FILE_PERMISSIONS);
32844         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
32845         if( fd>=0 ){
32846           pFile->h = fd;
32847         }else{
32848           rc=SQLCIPHER_CANTOPEN_BKPT; /* SQLCIPHER_BUSY? proxyTakeConch called
32849            during locking */
32850         }
32851       }
32852       if( rc==SQLCIPHER_OK && !pCtx->lockProxy ){
32853         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
32854         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
32855         if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_NOMEM && tryOldLockPath ){
32856           /* we couldn't create the proxy lock file with the old lock file path
32857            ** so try again via auto-naming 
32858            */
32859           forceNewLockPath = 1;
32860           tryOldLockPath = 0;
32861           continue; /* go back to the do {} while start point, try again */
32862         }
32863       }
32864       if( rc==SQLCIPHER_OK ){
32865         /* Need to make a copy of path if we extracted the value
32866          ** from the conch file or the path was allocated on the stack
32867          */
32868         if( tempLockPath ){
32869           pCtx->lockProxyPath = sqlcipher3DbStrDup(0, tempLockPath);
32870           if( !pCtx->lockProxyPath ){
32871             rc = SQLCIPHER_NOMEM;
32872           }
32873         }
32874       }
32875       if( rc==SQLCIPHER_OK ){
32876         pCtx->conchHeld = 1;
32877         
32878         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
32879           afpLockingContext *afpCtx;
32880           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
32881           afpCtx->dbPath = pCtx->lockProxyPath;
32882         }
32883       } else {
32884         conchFile->pMethod->xUnlock((sqlcipher3_file*)conchFile, NO_LOCK);
32885       }
32886       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
32887                rc==SQLCIPHER_OK?"ok":"failed"));
32888       return rc;
32889     } while (1); /* in case we need to retry the :auto: lock file - 
32890                  ** we should never get here except via the 'continue' call. */
32891   }
32892 }
32893
32894 /*
32895 ** If pFile holds a lock on a conch file, then release that lock.
32896 */
32897 static int proxyReleaseConch(unixFile *pFile){
32898   int rc = SQLCIPHER_OK;         /* Subroutine return code */
32899   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
32900   unixFile *conchFile;        /* Name of the conch file */
32901
32902   pCtx = (proxyLockingContext *)pFile->lockingContext;
32903   conchFile = pCtx->conchFile;
32904   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
32905            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
32906            getpid()));
32907   if( pCtx->conchHeld>0 ){
32908     rc = conchFile->pMethod->xUnlock((sqlcipher3_file*)conchFile, NO_LOCK);
32909   }
32910   pCtx->conchHeld = 0;
32911   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
32912            (rc==SQLCIPHER_OK ? "ok" : "failed")));
32913   return rc;
32914 }
32915
32916 /*
32917 ** Given the name of a database file, compute the name of its conch file.
32918 ** Store the conch filename in memory obtained from sqlcipher3_malloc().
32919 ** Make *pConchPath point to the new name.  Return SQLCIPHER_OK on success
32920 ** or SQLCIPHER_NOMEM if unable to obtain memory.
32921 **
32922 ** The caller is responsible for ensuring that the allocated memory
32923 ** space is eventually freed.
32924 **
32925 ** *pConchPath is set to NULL if a memory allocation error occurs.
32926 */
32927 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
32928   int i;                        /* Loop counter */
32929   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
32930   char *conchPath;              /* buffer in which to construct conch name */
32931
32932   /* Allocate space for the conch filename and initialize the name to
32933   ** the name of the original database file. */  
32934   *pConchPath = conchPath = (char *)sqlcipher3_malloc(len + 8);
32935   if( conchPath==0 ){
32936     return SQLCIPHER_NOMEM;
32937   }
32938   memcpy(conchPath, dbPath, len+1);
32939   
32940   /* now insert a "." before the last / character */
32941   for( i=(len-1); i>=0; i-- ){
32942     if( conchPath[i]=='/' ){
32943       i++;
32944       break;
32945     }
32946   }
32947   conchPath[i]='.';
32948   while ( i<len ){
32949     conchPath[i+1]=dbPath[i];
32950     i++;
32951   }
32952
32953   /* append the "-conch" suffix to the file */
32954   memcpy(&conchPath[i+1], "-conch", 7);
32955   assert( (int)strlen(conchPath) == len+7 );
32956
32957   return SQLCIPHER_OK;
32958 }
32959
32960
32961 /* Takes a fully configured proxy locking-style unix file and switches
32962 ** the local lock file path 
32963 */
32964 static int switchLockProxyPath(unixFile *pFile, const char *path) {
32965   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32966   char *oldPath = pCtx->lockProxyPath;
32967   int rc = SQLCIPHER_OK;
32968
32969   if( pFile->eFileLock!=NO_LOCK ){
32970     return SQLCIPHER_BUSY;
32971   }  
32972
32973   /* nothing to do if the path is NULL, :auto: or matches the existing path */
32974   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
32975     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
32976     return SQLCIPHER_OK;
32977   }else{
32978     unixFile *lockProxy = pCtx->lockProxy;
32979     pCtx->lockProxy=NULL;
32980     pCtx->conchHeld = 0;
32981     if( lockProxy!=NULL ){
32982       rc=lockProxy->pMethod->xClose((sqlcipher3_file *)lockProxy);
32983       if( rc ) return rc;
32984       sqlcipher3_free(lockProxy);
32985     }
32986     sqlcipher3_free(oldPath);
32987     pCtx->lockProxyPath = sqlcipher3DbStrDup(0, path);
32988   }
32989   
32990   return rc;
32991 }
32992
32993 /*
32994 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
32995 ** is a string buffer at least MAXPATHLEN+1 characters in size.
32996 **
32997 ** This routine find the filename associated with pFile and writes it
32998 ** int dbPath.
32999 */
33000 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
33001 #if defined(__APPLE__)
33002   if( pFile->pMethod == &afpIoMethods ){
33003     /* afp style keeps a reference to the db path in the filePath field 
33004     ** of the struct */
33005     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
33006     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
33007   } else
33008 #endif
33009   if( pFile->pMethod == &dotlockIoMethods ){
33010     /* dot lock style uses the locking context to store the dot lock
33011     ** file path */
33012     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
33013     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
33014   }else{
33015     /* all other styles use the locking context to store the db file path */
33016     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
33017     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
33018   }
33019   return SQLCIPHER_OK;
33020 }
33021
33022 /*
33023 ** Takes an already filled in unix file and alters it so all file locking 
33024 ** will be performed on the local proxy lock file.  The following fields
33025 ** are preserved in the locking context so that they can be restored and 
33026 ** the unix structure properly cleaned up at close time:
33027 **  ->lockingContext
33028 **  ->pMethod
33029 */
33030 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
33031   proxyLockingContext *pCtx;
33032   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
33033   char *lockPath=NULL;
33034   int rc = SQLCIPHER_OK;
33035   
33036   if( pFile->eFileLock!=NO_LOCK ){
33037     return SQLCIPHER_BUSY;
33038   }
33039   proxyGetDbPathForUnixFile(pFile, dbPath);
33040   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
33041     lockPath=NULL;
33042   }else{
33043     lockPath=(char *)path;
33044   }
33045   
33046   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
33047            (lockPath ? lockPath : ":auto:"), getpid()));
33048
33049   pCtx = sqlcipher3_malloc( sizeof(*pCtx) );
33050   if( pCtx==0 ){
33051     return SQLCIPHER_NOMEM;
33052   }
33053   memset(pCtx, 0, sizeof(*pCtx));
33054
33055   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
33056   if( rc==SQLCIPHER_OK ){
33057     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
33058     if( rc==SQLCIPHER_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
33059       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
33060       ** (c) the file system is read-only, then enable no-locking access.
33061       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
33062       ** that openFlags will have only one of O_RDONLY or O_RDWR.
33063       */
33064       struct statfs fsInfo;
33065       struct stat conchInfo;
33066       int goLockless = 0;
33067
33068       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
33069         int err = errno;
33070         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
33071           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
33072         }
33073       }
33074       if( goLockless ){
33075         pCtx->conchHeld = -1; /* read only FS/ lockless */
33076         rc = SQLCIPHER_OK;
33077       }
33078     }
33079   }  
33080   if( rc==SQLCIPHER_OK && lockPath ){
33081     pCtx->lockProxyPath = sqlcipher3DbStrDup(0, lockPath);
33082   }
33083
33084   if( rc==SQLCIPHER_OK ){
33085     pCtx->dbPath = sqlcipher3DbStrDup(0, dbPath);
33086     if( pCtx->dbPath==NULL ){
33087       rc = SQLCIPHER_NOMEM;
33088     }
33089   }
33090   if( rc==SQLCIPHER_OK ){
33091     /* all memory is allocated, proxys are created and assigned, 
33092     ** switch the locking context and pMethod then return.
33093     */
33094     pCtx->oldLockingContext = pFile->lockingContext;
33095     pFile->lockingContext = pCtx;
33096     pCtx->pOldMethod = pFile->pMethod;
33097     pFile->pMethod = &proxyIoMethods;
33098   }else{
33099     if( pCtx->conchFile ){ 
33100       pCtx->conchFile->pMethod->xClose((sqlcipher3_file *)pCtx->conchFile);
33101       sqlcipher3_free(pCtx->conchFile);
33102     }
33103     sqlcipher3DbFree(0, pCtx->lockProxyPath);
33104     sqlcipher3_free(pCtx->conchFilePath); 
33105     sqlcipher3_free(pCtx);
33106   }
33107   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
33108            (rc==SQLCIPHER_OK ? "ok" : "failed")));
33109   return rc;
33110 }
33111
33112
33113 /*
33114 ** This routine handles sqlcipher3_file_control() calls that are specific
33115 ** to proxy locking.
33116 */
33117 static int proxyFileControl(sqlcipher3_file *id, int op, void *pArg){
33118   switch( op ){
33119     case SQLCIPHER_GET_LOCKPROXYFILE: {
33120       unixFile *pFile = (unixFile*)id;
33121       if( pFile->pMethod == &proxyIoMethods ){
33122         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
33123         proxyTakeConch(pFile);
33124         if( pCtx->lockProxyPath ){
33125           *(const char **)pArg = pCtx->lockProxyPath;
33126         }else{
33127           *(const char **)pArg = ":auto: (not held)";
33128         }
33129       } else {
33130         *(const char **)pArg = NULL;
33131       }
33132       return SQLCIPHER_OK;
33133     }
33134     case SQLCIPHER_SET_LOCKPROXYFILE: {
33135       unixFile *pFile = (unixFile*)id;
33136       int rc = SQLCIPHER_OK;
33137       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
33138       if( pArg==NULL || (const char *)pArg==0 ){
33139         if( isProxyStyle ){
33140           /* turn off proxy locking - not supported */
33141           rc = SQLCIPHER_ERROR /*SQLCIPHER_PROTOCOL? SQLCIPHER_MISUSE?*/;
33142         }else{
33143           /* turn off proxy locking - already off - NOOP */
33144           rc = SQLCIPHER_OK;
33145         }
33146       }else{
33147         const char *proxyPath = (const char *)pArg;
33148         if( isProxyStyle ){
33149           proxyLockingContext *pCtx = 
33150             (proxyLockingContext*)pFile->lockingContext;
33151           if( !strcmp(pArg, ":auto:") 
33152            || (pCtx->lockProxyPath &&
33153                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
33154           ){
33155             rc = SQLCIPHER_OK;
33156           }else{
33157             rc = switchLockProxyPath(pFile, proxyPath);
33158           }
33159         }else{
33160           /* turn on proxy file locking */
33161           rc = proxyTransformUnixFile(pFile, proxyPath);
33162         }
33163       }
33164       return rc;
33165     }
33166     default: {
33167       assert( 0 );  /* The call assures that only valid opcodes are sent */
33168     }
33169   }
33170   /*NOTREACHED*/
33171   return SQLCIPHER_ERROR;
33172 }
33173
33174 /*
33175 ** Within this division (the proxying locking implementation) the procedures
33176 ** above this point are all utilities.  The lock-related methods of the
33177 ** proxy-locking sqlcipher3_io_method object follow.
33178 */
33179
33180
33181 /*
33182 ** This routine checks if there is a RESERVED lock held on the specified
33183 ** file by this or any other process. If such a lock is held, set *pResOut
33184 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
33185 ** is set to SQLCIPHER_OK unless an I/O error occurs during lock checking.
33186 */
33187 static int proxyCheckReservedLock(sqlcipher3_file *id, int *pResOut) {
33188   unixFile *pFile = (unixFile*)id;
33189   int rc = proxyTakeConch(pFile);
33190   if( rc==SQLCIPHER_OK ){
33191     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33192     if( pCtx->conchHeld>0 ){
33193       unixFile *proxy = pCtx->lockProxy;
33194       return proxy->pMethod->xCheckReservedLock((sqlcipher3_file*)proxy, pResOut);
33195     }else{ /* conchHeld < 0 is lockless */
33196       pResOut=0;
33197     }
33198   }
33199   return rc;
33200 }
33201
33202 /*
33203 ** Lock the file with the lock specified by parameter eFileLock - one
33204 ** of the following:
33205 **
33206 **     (1) SHARED_LOCK
33207 **     (2) RESERVED_LOCK
33208 **     (3) PENDING_LOCK
33209 **     (4) EXCLUSIVE_LOCK
33210 **
33211 ** Sometimes when requesting one lock state, additional lock states
33212 ** are inserted in between.  The locking might fail on one of the later
33213 ** transitions leaving the lock state different from what it started but
33214 ** still short of its goal.  The following chart shows the allowed
33215 ** transitions and the inserted intermediate states:
33216 **
33217 **    UNLOCKED -> SHARED
33218 **    SHARED -> RESERVED
33219 **    SHARED -> (PENDING) -> EXCLUSIVE
33220 **    RESERVED -> (PENDING) -> EXCLUSIVE
33221 **    PENDING -> EXCLUSIVE
33222 **
33223 ** This routine will only increase a lock.  Use the sqlcipher3OsUnlock()
33224 ** routine to lower a locking level.
33225 */
33226 static int proxyLock(sqlcipher3_file *id, int eFileLock) {
33227   unixFile *pFile = (unixFile*)id;
33228   int rc = proxyTakeConch(pFile);
33229   if( rc==SQLCIPHER_OK ){
33230     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33231     if( pCtx->conchHeld>0 ){
33232       unixFile *proxy = pCtx->lockProxy;
33233       rc = proxy->pMethod->xLock((sqlcipher3_file*)proxy, eFileLock);
33234       pFile->eFileLock = proxy->eFileLock;
33235     }else{
33236       /* conchHeld < 0 is lockless */
33237     }
33238   }
33239   return rc;
33240 }
33241
33242
33243 /*
33244 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
33245 ** must be either NO_LOCK or SHARED_LOCK.
33246 **
33247 ** If the locking level of the file descriptor is already at or below
33248 ** the requested locking level, this routine is a no-op.
33249 */
33250 static int proxyUnlock(sqlcipher3_file *id, int eFileLock) {
33251   unixFile *pFile = (unixFile*)id;
33252   int rc = proxyTakeConch(pFile);
33253   if( rc==SQLCIPHER_OK ){
33254     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33255     if( pCtx->conchHeld>0 ){
33256       unixFile *proxy = pCtx->lockProxy;
33257       rc = proxy->pMethod->xUnlock((sqlcipher3_file*)proxy, eFileLock);
33258       pFile->eFileLock = proxy->eFileLock;
33259     }else{
33260       /* conchHeld < 0 is lockless */
33261     }
33262   }
33263   return rc;
33264 }
33265
33266 /*
33267 ** Close a file that uses proxy locks.
33268 */
33269 static int proxyClose(sqlcipher3_file *id) {
33270   if( id ){
33271     unixFile *pFile = (unixFile*)id;
33272     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33273     unixFile *lockProxy = pCtx->lockProxy;
33274     unixFile *conchFile = pCtx->conchFile;
33275     int rc = SQLCIPHER_OK;
33276     
33277     if( lockProxy ){
33278       rc = lockProxy->pMethod->xUnlock((sqlcipher3_file*)lockProxy, NO_LOCK);
33279       if( rc ) return rc;
33280       rc = lockProxy->pMethod->xClose((sqlcipher3_file*)lockProxy);
33281       if( rc ) return rc;
33282       sqlcipher3_free(lockProxy);
33283       pCtx->lockProxy = 0;
33284     }
33285     if( conchFile ){
33286       if( pCtx->conchHeld ){
33287         rc = proxyReleaseConch(pFile);
33288         if( rc ) return rc;
33289       }
33290       rc = conchFile->pMethod->xClose((sqlcipher3_file*)conchFile);
33291       if( rc ) return rc;
33292       sqlcipher3_free(conchFile);
33293     }
33294     sqlcipher3DbFree(0, pCtx->lockProxyPath);
33295     sqlcipher3_free(pCtx->conchFilePath);
33296     sqlcipher3DbFree(0, pCtx->dbPath);
33297     /* restore the original locking context and pMethod then close it */
33298     pFile->lockingContext = pCtx->oldLockingContext;
33299     pFile->pMethod = pCtx->pOldMethod;
33300     sqlcipher3_free(pCtx);
33301     return pFile->pMethod->xClose(id);
33302   }
33303   return SQLCIPHER_OK;
33304 }
33305
33306
33307
33308 #endif /* defined(__APPLE__) && SQLCIPHER_ENABLE_LOCKING_STYLE */
33309 /*
33310 ** The proxy locking style is intended for use with AFP filesystems.
33311 ** And since AFP is only supported on MacOSX, the proxy locking is also
33312 ** restricted to MacOSX.
33313 ** 
33314 **
33315 ******************* End of the proxy lock implementation **********************
33316 ******************************************************************************/
33317
33318 /*
33319 ** Initialize the operating system interface.
33320 **
33321 ** This routine registers all VFS implementations for unix-like operating
33322 ** systems.  This routine, and the sqlcipher3_os_end() routine that follows,
33323 ** should be the only routines in this file that are visible from other
33324 ** files.
33325 **
33326 ** This routine is called once during SQLite initialization and by a
33327 ** single thread.  The memory allocation and mutex subsystems have not
33328 ** necessarily been initialized when this routine is called, and so they
33329 ** should not be used.
33330 */
33331 SQLCIPHER_API int sqlcipher3_os_init(void){ 
33332   /* 
33333   ** The following macro defines an initializer for an sqlcipher3_vfs object.
33334   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
33335   ** to the "finder" function.  (pAppData is a pointer to a pointer because
33336   ** silly C90 rules prohibit a void* from being cast to a function pointer
33337   ** and so we have to go through the intermediate pointer to avoid problems
33338   ** when compiling with -pedantic-errors on GCC.)
33339   **
33340   ** The FINDER parameter to this macro is the name of the pointer to the
33341   ** finder-function.  The finder-function returns a pointer to the
33342   ** sqlcipher_io_methods object that implements the desired locking
33343   ** behaviors.  See the division above that contains the IOMETHODS
33344   ** macro for addition information on finder-functions.
33345   **
33346   ** Most finders simply return a pointer to a fixed sqlcipher3_io_methods
33347   ** object.  But the "autolockIoFinder" available on MacOSX does a little
33348   ** more than that; it looks at the filesystem type that hosts the 
33349   ** database file and tries to choose an locking method appropriate for
33350   ** that filesystem time.
33351   */
33352   #define UNIXVFS(VFSNAME, FINDER) {                        \
33353     3,                    /* iVersion */                    \
33354     sizeof(unixFile),     /* szOsFile */                    \
33355     MAX_PATHNAME,         /* mxPathname */                  \
33356     0,                    /* pNext */                       \
33357     VFSNAME,              /* zName */                       \
33358     (void*)&FINDER,       /* pAppData */                    \
33359     unixOpen,             /* xOpen */                       \
33360     unixDelete,           /* xDelete */                     \
33361     unixAccess,           /* xAccess */                     \
33362     unixFullPathname,     /* xFullPathname */               \
33363     unixDlOpen,           /* xDlOpen */                     \
33364     unixDlError,          /* xDlError */                    \
33365     unixDlSym,            /* xDlSym */                      \
33366     unixDlClose,          /* xDlClose */                    \
33367     unixRandomness,       /* xRandomness */                 \
33368     unixSleep,            /* xSleep */                      \
33369     unixCurrentTime,      /* xCurrentTime */                \
33370     unixGetLastError,     /* xGetLastError */               \
33371     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
33372     unixSetSystemCall,    /* xSetSystemCall */              \
33373     unixGetSystemCall,    /* xGetSystemCall */              \
33374     unixNextSystemCall,   /* xNextSystemCall */             \
33375   }
33376
33377   /*
33378   ** All default VFSes for unix are contained in the following array.
33379   **
33380   ** Note that the sqlcipher3_vfs.pNext field of the VFS object is modified
33381   ** by the SQLite core when the VFS is registered.  So the following
33382   ** array cannot be const.
33383   */
33384   static sqlcipher3_vfs aVfs[] = {
33385 #if SQLCIPHER_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
33386     UNIXVFS("unix",          autolockIoFinder ),
33387 #else
33388     UNIXVFS("unix",          posixIoFinder ),
33389 #endif
33390     UNIXVFS("unix-none",     nolockIoFinder ),
33391     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
33392     UNIXVFS("unix-excl",     posixIoFinder ),
33393 #if OS_VXWORKS
33394     UNIXVFS("unix-namedsem", semIoFinder ),
33395 #endif
33396 #if SQLCIPHER_ENABLE_LOCKING_STYLE
33397     UNIXVFS("unix-posix",    posixIoFinder ),
33398 #if !OS_VXWORKS
33399     UNIXVFS("unix-flock",    flockIoFinder ),
33400 #endif
33401 #endif
33402 #if SQLCIPHER_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33403     UNIXVFS("unix-afp",      afpIoFinder ),
33404     UNIXVFS("unix-nfs",      nfsIoFinder ),
33405     UNIXVFS("unix-proxy",    proxyIoFinder ),
33406 #endif
33407   };
33408   unsigned int i;          /* Loop counter */
33409
33410   /* Double-check that the aSyscall[] array has been constructed
33411   ** correctly.  See ticket [bb3a86e890c8e96ab] */
33412   assert( ArraySize(aSyscall)==18 );
33413
33414   /* Register all VFSes defined in the aVfs[] array */
33415   for(i=0; i<(sizeof(aVfs)/sizeof(sqlcipher3_vfs)); i++){
33416     sqlcipher3_vfs_register(&aVfs[i], i==0);
33417   }
33418   return SQLCIPHER_OK; 
33419 }
33420
33421 /*
33422 ** Shutdown the operating system interface.
33423 **
33424 ** Some operating systems might need to do some cleanup in this routine,
33425 ** to release dynamically allocated objects.  But not on unix.
33426 ** This routine is a no-op for unix.
33427 */
33428 SQLCIPHER_API int sqlcipher3_os_end(void){ 
33429   return SQLCIPHER_OK; 
33430 }
33431  
33432 #endif /* SQLCIPHER_OS_UNIX */
33433
33434 /************** End of os_unix.c *********************************************/
33435 /************** Begin file os_win.c ******************************************/
33436 /*
33437 ** 2004 May 22
33438 **
33439 ** The author disclaims copyright to this source code.  In place of
33440 ** a legal notice, here is a blessing:
33441 **
33442 **    May you do good and not evil.
33443 **    May you find forgiveness for yourself and forgive others.
33444 **    May you share freely, never taking more than you give.
33445 **
33446 ******************************************************************************
33447 **
33448 ** This file contains code that is specific to windows.
33449 */
33450 #if SQLCIPHER_OS_WIN               /* This file is used for windows only */
33451
33452
33453 /*
33454 ** A Note About Memory Allocation:
33455 **
33456 ** This driver uses malloc()/free() directly rather than going through
33457 ** the SQLite-wrappers sqlcipher3_malloc()/sqlcipher3_free().  Those wrappers
33458 ** are designed for use on embedded systems where memory is scarce and
33459 ** malloc failures happen frequently.  Win32 does not typically run on
33460 ** embedded systems, and when it does the developers normally have bigger
33461 ** problems to worry about than running out of memory.  So there is not
33462 ** a compelling need to use the wrappers.
33463 **
33464 ** But there is a good reason to not use the wrappers.  If we use the
33465 ** wrappers then we will get simulated malloc() failures within this
33466 ** driver.  And that causes all kinds of problems for our tests.  We
33467 ** could enhance SQLite to deal with simulated malloc failures within
33468 ** the OS driver, but the code to deal with those failure would not
33469 ** be exercised on Linux (which does not need to malloc() in the driver)
33470 ** and so we would have difficulty writing coverage tests for that
33471 ** code.  Better to leave the code out, we think.
33472 **
33473 ** The point of this discussion is as follows:  When creating a new
33474 ** OS layer for an embedded system, if you use this file as an example,
33475 ** avoid the use of malloc()/free().  Those routines work ok on windows
33476 ** desktops but not so well in embedded systems.
33477 */
33478
33479 #include <winbase.h>
33480
33481 #ifdef __CYGWIN__
33482 # include <sys/cygwin.h>
33483 #endif
33484
33485 /*
33486 ** Macros used to determine whether or not to use threads.
33487 */
33488 #if defined(THREADSAFE) && THREADSAFE
33489 # define SQLCIPHER_W32_THREADS 1
33490 #endif
33491
33492 /*
33493 ** Include code that is common to all os_*.c files
33494 */
33495 /************** Include os_common.h in the middle of os_win.c ****************/
33496 /************** Begin file os_common.h ***************************************/
33497 /*
33498 ** 2004 May 22
33499 **
33500 ** The author disclaims copyright to this source code.  In place of
33501 ** a legal notice, here is a blessing:
33502 **
33503 **    May you do good and not evil.
33504 **    May you find forgiveness for yourself and forgive others.
33505 **    May you share freely, never taking more than you give.
33506 **
33507 ******************************************************************************
33508 **
33509 ** This file contains macros and a little bit of code that is common to
33510 ** all of the platform-specific files (os_*.c) and is #included into those
33511 ** files.
33512 **
33513 ** This file should be #included by the os_*.c files only.  It is not a
33514 ** general purpose header file.
33515 */
33516 #ifndef _OS_COMMON_H_
33517 #define _OS_COMMON_H_
33518
33519 /*
33520 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
33521 ** macro to SQLCIPHER_DEBUG and some older makefiles have not yet made the
33522 ** switch.  The following code should catch this problem at compile-time.
33523 */
33524 #ifdef MEMORY_DEBUG
33525 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLCIPHER_DEBUG instead."
33526 #endif
33527
33528 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
33529 # ifndef SQLCIPHER_DEBUG_OS_TRACE
33530 #   define SQLCIPHER_DEBUG_OS_TRACE 0
33531 # endif
33532   int sqlcipher3OSTrace = SQLCIPHER_DEBUG_OS_TRACE;
33533 # define OSTRACE(X)          if( sqlcipher3OSTrace ) sqlcipher3DebugPrintf X
33534 #else
33535 # define OSTRACE(X)
33536 #endif
33537
33538 /*
33539 ** Macros for performance tracing.  Normally turned off.  Only works
33540 ** on i486 hardware.
33541 */
33542 #ifdef SQLCIPHER_PERFORMANCE_TRACE
33543
33544 /* 
33545 ** hwtime.h contains inline assembler code for implementing 
33546 ** high-performance timing routines.
33547 */
33548 /************** Include hwtime.h in the middle of os_common.h ****************/
33549 /************** Begin file hwtime.h ******************************************/
33550 /*
33551 ** 2008 May 27
33552 **
33553 ** The author disclaims copyright to this source code.  In place of
33554 ** a legal notice, here is a blessing:
33555 **
33556 **    May you do good and not evil.
33557 **    May you find forgiveness for yourself and forgive others.
33558 **    May you share freely, never taking more than you give.
33559 **
33560 ******************************************************************************
33561 **
33562 ** This file contains inline asm code for retrieving "high-performance"
33563 ** counters for x86 class CPUs.
33564 */
33565 #ifndef _HWTIME_H_
33566 #define _HWTIME_H_
33567
33568 /*
33569 ** The following routine only works on pentium-class (or newer) processors.
33570 ** It uses the RDTSC opcode to read the cycle count value out of the
33571 ** processor and returns that value.  This can be used for high-res
33572 ** profiling.
33573 */
33574 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
33575       (defined(i386) || defined(__i386__) || defined(_M_IX86))
33576
33577   #if defined(__GNUC__)
33578
33579   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
33580      unsigned int lo, hi;
33581      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
33582      return (sqlcipher_uint64)hi << 32 | lo;
33583   }
33584
33585   #elif defined(_MSC_VER)
33586
33587   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
33588      __asm {
33589         rdtsc
33590         ret       ; return value at EDX:EAX
33591      }
33592   }
33593
33594   #endif
33595
33596 #elif (defined(__GNUC__) && defined(__x86_64__))
33597
33598   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
33599       unsigned long val;
33600       __asm__ __volatile__ ("rdtsc" : "=A" (val));
33601       return val;
33602   }
33603  
33604 #elif (defined(__GNUC__) && defined(__ppc__))
33605
33606   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
33607       unsigned long long retval;
33608       unsigned long junk;
33609       __asm__ __volatile__ ("\n\
33610           1:      mftbu   %1\n\
33611                   mftb    %L0\n\
33612                   mftbu   %0\n\
33613                   cmpw    %0,%1\n\
33614                   bne     1b"
33615                   : "=r" (retval), "=r" (junk));
33616       return retval;
33617   }
33618
33619 #else
33620
33621   #error Need implementation of sqlcipher3Hwtime() for your platform.
33622
33623   /*
33624   ** To compile without implementing sqlcipher3Hwtime() for your platform,
33625   ** you can remove the above #error and use the following
33626   ** stub function.  You will lose timing support for many
33627   ** of the debugging and testing utilities, but it should at
33628   ** least compile and run.
33629   */
33630 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
33631
33632 #endif
33633
33634 #endif /* !defined(_HWTIME_H_) */
33635
33636 /************** End of hwtime.h **********************************************/
33637 /************** Continuing where we left off in os_common.h ******************/
33638
33639 static sqlcipher_uint64 g_start;
33640 static sqlcipher_uint64 g_elapsed;
33641 #define TIMER_START       g_start=sqlcipher3Hwtime()
33642 #define TIMER_END         g_elapsed=sqlcipher3Hwtime()-g_start
33643 #define TIMER_ELAPSED     g_elapsed
33644 #else
33645 #define TIMER_START
33646 #define TIMER_END
33647 #define TIMER_ELAPSED     ((sqlcipher_uint64)0)
33648 #endif
33649
33650 /*
33651 ** If we compile with the SQLCIPHER_TEST macro set, then the following block
33652 ** of code will give us the ability to simulate a disk I/O error.  This
33653 ** is used for testing the I/O recovery logic.
33654 */
33655 #ifdef SQLCIPHER_TEST
33656 SQLCIPHER_API int sqlcipher3_io_error_hit = 0;            /* Total number of I/O Errors */
33657 SQLCIPHER_API int sqlcipher3_io_error_hardhit = 0;        /* Number of non-benign errors */
33658 SQLCIPHER_API int sqlcipher3_io_error_pending = 0;        /* Count down to first I/O error */
33659 SQLCIPHER_API int sqlcipher3_io_error_persist = 0;        /* True if I/O errors persist */
33660 SQLCIPHER_API int sqlcipher3_io_error_benign = 0;         /* True if errors are benign */
33661 SQLCIPHER_API int sqlcipher3_diskfull_pending = 0;
33662 SQLCIPHER_API int sqlcipher3_diskfull = 0;
33663 #define SimulateIOErrorBenign(X) sqlcipher3_io_error_benign=(X)
33664 #define SimulateIOError(CODE)  \
33665   if( (sqlcipher3_io_error_persist && sqlcipher3_io_error_hit) \
33666        || sqlcipher3_io_error_pending-- == 1 )  \
33667               { local_ioerr(); CODE; }
33668 static void local_ioerr(){
33669   IOTRACE(("IOERR\n"));
33670   sqlcipher3_io_error_hit++;
33671   if( !sqlcipher3_io_error_benign ) sqlcipher3_io_error_hardhit++;
33672 }
33673 #define SimulateDiskfullError(CODE) \
33674    if( sqlcipher3_diskfull_pending ){ \
33675      if( sqlcipher3_diskfull_pending == 1 ){ \
33676        local_ioerr(); \
33677        sqlcipher3_diskfull = 1; \
33678        sqlcipher3_io_error_hit = 1; \
33679        CODE; \
33680      }else{ \
33681        sqlcipher3_diskfull_pending--; \
33682      } \
33683    }
33684 #else
33685 #define SimulateIOErrorBenign(X)
33686 #define SimulateIOError(A)
33687 #define SimulateDiskfullError(A)
33688 #endif
33689
33690 /*
33691 ** When testing, keep a count of the number of open files.
33692 */
33693 #ifdef SQLCIPHER_TEST
33694 SQLCIPHER_API int sqlcipher3_open_file_count = 0;
33695 #define OpenCounter(X)  sqlcipher3_open_file_count+=(X)
33696 #else
33697 #define OpenCounter(X)
33698 #endif
33699
33700 #endif /* !defined(_OS_COMMON_H_) */
33701
33702 /************** End of os_common.h *******************************************/
33703 /************** Continuing where we left off in os_win.c *********************/
33704
33705 /*
33706 ** Some microsoft compilers lack this definition.
33707 */
33708 #ifndef INVALID_FILE_ATTRIBUTES
33709 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
33710 #endif
33711
33712 /*
33713 ** Determine if we are dealing with WindowsCE - which has a much
33714 ** reduced API.
33715 */
33716 #if SQLCIPHER_OS_WINCE
33717 # define AreFileApisANSI() 1
33718 # define FormatMessageW(a,b,c,d,e,f,g) 0
33719 #endif
33720
33721 /* Forward references */
33722 typedef struct winShm winShm;           /* A connection to shared-memory */
33723 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
33724
33725 /*
33726 ** WinCE lacks native support for file locking so we have to fake it
33727 ** with some code of our own.
33728 */
33729 #if SQLCIPHER_OS_WINCE
33730 typedef struct winceLock {
33731   int nReaders;       /* Number of reader locks obtained */
33732   BOOL bPending;      /* Indicates a pending lock has been obtained */
33733   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
33734   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
33735 } winceLock;
33736 #endif
33737
33738 /*
33739 ** The winFile structure is a subclass of sqlcipher3_file* specific to the win32
33740 ** portability layer.
33741 */
33742 typedef struct winFile winFile;
33743 struct winFile {
33744   const sqlcipher3_io_methods *pMethod; /*** Must be first ***/
33745   sqlcipher3_vfs *pVfs;      /* The VFS used to open this file */
33746   HANDLE h;               /* Handle for accessing the file */
33747   u8 locktype;            /* Type of lock currently held on this file */
33748   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
33749   u8 bPersistWal;         /* True to persist WAL files */
33750   DWORD lastErrno;        /* The Windows errno from the last I/O error */
33751   DWORD sectorSize;       /* Sector size of the device file is on */
33752   winShm *pShm;           /* Instance of shared memory on this file */
33753   const char *zPath;      /* Full pathname of this file */
33754   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
33755 #if SQLCIPHER_OS_WINCE
33756   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
33757   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
33758   HANDLE hShared;         /* Shared memory segment used for locking */
33759   winceLock local;        /* Locks obtained by this instance of winFile */
33760   winceLock *shared;      /* Global shared lock memory for the file  */
33761 #endif
33762 };
33763
33764 /*
33765  * If compiled with SQLCIPHER_WIN32_MALLOC on Windows, we will use the
33766  * various Win32 API heap functions instead of our own.
33767  */
33768 #ifdef SQLCIPHER_WIN32_MALLOC
33769 /*
33770  * The initial size of the Win32-specific heap.  This value may be zero.
33771  */
33772 #ifndef SQLCIPHER_WIN32_HEAP_INIT_SIZE
33773 #  define SQLCIPHER_WIN32_HEAP_INIT_SIZE ((SQLCIPHER_DEFAULT_CACHE_SIZE) * \
33774                                        (SQLCIPHER_DEFAULT_PAGE_SIZE) + 4194304)
33775 #endif
33776
33777 /*
33778  * The maximum size of the Win32-specific heap.  This value may be zero.
33779  */
33780 #ifndef SQLCIPHER_WIN32_HEAP_MAX_SIZE
33781 #  define SQLCIPHER_WIN32_HEAP_MAX_SIZE  (0)
33782 #endif
33783
33784 /*
33785  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
33786  * zero for the default behavior.
33787  */
33788 #ifndef SQLCIPHER_WIN32_HEAP_FLAGS
33789 #  define SQLCIPHER_WIN32_HEAP_FLAGS     (0)
33790 #endif
33791
33792 /*
33793 ** The winMemData structure stores information required by the Win32-specific
33794 ** sqlcipher3_mem_methods implementation.
33795 */
33796 typedef struct winMemData winMemData;
33797 struct winMemData {
33798 #ifndef NDEBUG
33799   u32 magic;    /* Magic number to detect structure corruption. */
33800 #endif
33801   HANDLE hHeap; /* The handle to our heap. */
33802   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
33803 };
33804
33805 #ifndef NDEBUG
33806 #define WINMEM_MAGIC     0x42b2830b
33807 #endif
33808
33809 static struct winMemData win_mem_data = {
33810 #ifndef NDEBUG
33811   WINMEM_MAGIC,
33812 #endif
33813   NULL, FALSE
33814 };
33815
33816 #ifndef NDEBUG
33817 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
33818 #else
33819 #define winMemAssertMagic()
33820 #endif
33821
33822 #define winMemGetHeap() win_mem_data.hHeap
33823
33824 static void *winMemMalloc(int nBytes);
33825 static void winMemFree(void *pPrior);
33826 static void *winMemRealloc(void *pPrior, int nBytes);
33827 static int winMemSize(void *p);
33828 static int winMemRoundup(int n);
33829 static int winMemInit(void *pAppData);
33830 static void winMemShutdown(void *pAppData);
33831
33832 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetWin32(void);
33833 #endif /* SQLCIPHER_WIN32_MALLOC */
33834
33835 /*
33836 ** Forward prototypes.
33837 */
33838 static int getSectorSize(
33839     sqlcipher3_vfs *pVfs,
33840     const char *zRelative     /* UTF-8 file name */
33841 );
33842
33843 /*
33844 ** The following variable is (normally) set once and never changes
33845 ** thereafter.  It records whether the operating system is Win95
33846 ** or WinNT.
33847 **
33848 ** 0:   Operating system unknown.
33849 ** 1:   Operating system is Win95.
33850 ** 2:   Operating system is WinNT.
33851 **
33852 ** In order to facilitate testing on a WinNT system, the test fixture
33853 ** can manually set this value to 1 to emulate Win98 behavior.
33854 */
33855 #ifdef SQLCIPHER_TEST
33856 SQLCIPHER_API int sqlcipher3_os_type = 0;
33857 #else
33858 static int sqlcipher3_os_type = 0;
33859 #endif
33860
33861 /*
33862 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33863 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
33864 **
33865 ** Here is an interesting observation:  Win95, Win98, and WinME lack
33866 ** the LockFileEx() API.  But we can still statically link against that
33867 ** API as long as we don't call it when running Win95/98/ME.  A call to
33868 ** this routine is used to determine if the host is Win95/98/ME or
33869 ** WinNT/2K/XP so that we will know whether or not we can safely call
33870 ** the LockFileEx() API.
33871 */
33872 #if SQLCIPHER_OS_WINCE
33873 # define isNT()  (1)
33874 #else
33875   static int isNT(void){
33876     if( sqlcipher3_os_type==0 ){
33877       OSVERSIONINFO sInfo;
33878       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33879       GetVersionEx(&sInfo);
33880       sqlcipher3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
33881     }
33882     return sqlcipher3_os_type==2;
33883   }
33884 #endif /* SQLCIPHER_OS_WINCE */
33885
33886 #ifdef SQLCIPHER_WIN32_MALLOC
33887 /*
33888 ** Allocate nBytes of memory.
33889 */
33890 static void *winMemMalloc(int nBytes){
33891   HANDLE hHeap;
33892   void *p;
33893
33894   winMemAssertMagic();
33895   hHeap = winMemGetHeap();
33896   assert( hHeap!=0 );
33897   assert( hHeap!=INVALID_HANDLE_VALUE );
33898 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33899   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
33900 #endif
33901   assert( nBytes>=0 );
33902   p = HeapAlloc(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33903   if( !p ){
33904     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
33905         nBytes, GetLastError(), (void*)hHeap);
33906   }
33907   return p;
33908 }
33909
33910 /*
33911 ** Free memory.
33912 */
33913 static void winMemFree(void *pPrior){
33914   HANDLE hHeap;
33915
33916   winMemAssertMagic();
33917   hHeap = winMemGetHeap();
33918   assert( hHeap!=0 );
33919   assert( hHeap!=INVALID_HANDLE_VALUE );
33920 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33921   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior) );
33922 #endif
33923   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
33924   if( !HeapFree(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior) ){
33925     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
33926         pPrior, GetLastError(), (void*)hHeap);
33927   }
33928 }
33929
33930 /*
33931 ** Change the size of an existing memory allocation
33932 */
33933 static void *winMemRealloc(void *pPrior, int nBytes){
33934   HANDLE hHeap;
33935   void *p;
33936
33937   winMemAssertMagic();
33938   hHeap = winMemGetHeap();
33939   assert( hHeap!=0 );
33940   assert( hHeap!=INVALID_HANDLE_VALUE );
33941 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33942   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior) );
33943 #endif
33944   assert( nBytes>=0 );
33945   if( !pPrior ){
33946     p = HeapAlloc(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33947   }else{
33948     p = HeapReAlloc(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
33949   }
33950   if( !p ){
33951     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to %s %u bytes (%d), heap=%p",
33952         pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, GetLastError(),
33953         (void*)hHeap);
33954   }
33955   return p;
33956 }
33957
33958 /*
33959 ** Return the size of an outstanding allocation, in bytes.
33960 */
33961 static int winMemSize(void *p){
33962   HANDLE hHeap;
33963   SIZE_T n;
33964
33965   winMemAssertMagic();
33966   hHeap = winMemGetHeap();
33967   assert( hHeap!=0 );
33968   assert( hHeap!=INVALID_HANDLE_VALUE );
33969 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
33970   assert ( HeapValidate(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
33971 #endif
33972   if( !p ) return 0;
33973   n = HeapSize(hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, p);
33974   if( n==(SIZE_T)-1 ){
33975     sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
33976         p, GetLastError(), (void*)hHeap);
33977     return 0;
33978   }
33979   return (int)n;
33980 }
33981
33982 /*
33983 ** Round up a request size to the next valid allocation size.
33984 */
33985 static int winMemRoundup(int n){
33986   return n;
33987 }
33988
33989 /*
33990 ** Initialize this module.
33991 */
33992 static int winMemInit(void *pAppData){
33993   winMemData *pWinMemData = (winMemData *)pAppData;
33994
33995   if( !pWinMemData ) return SQLCIPHER_ERROR;
33996   assert( pWinMemData->magic==WINMEM_MAGIC );
33997   if( !pWinMemData->hHeap ){
33998     pWinMemData->hHeap = HeapCreate(SQLCIPHER_WIN32_HEAP_FLAGS,
33999                                     SQLCIPHER_WIN32_HEAP_INIT_SIZE,
34000                                     SQLCIPHER_WIN32_HEAP_MAX_SIZE);
34001     if( !pWinMemData->hHeap ){
34002       sqlcipher3_log(SQLCIPHER_NOMEM,
34003           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
34004           GetLastError(), SQLCIPHER_WIN32_HEAP_FLAGS, SQLCIPHER_WIN32_HEAP_INIT_SIZE,
34005           SQLCIPHER_WIN32_HEAP_MAX_SIZE);
34006       return SQLCIPHER_NOMEM;
34007     }
34008     pWinMemData->bOwned = TRUE;
34009   }
34010   assert( pWinMemData->hHeap!=0 );
34011   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34012 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
34013   assert( HeapValidate(pWinMemData->hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
34014 #endif
34015   return SQLCIPHER_OK;
34016 }
34017
34018 /*
34019 ** Deinitialize this module.
34020 */
34021 static void winMemShutdown(void *pAppData){
34022   winMemData *pWinMemData = (winMemData *)pAppData;
34023
34024   if( !pWinMemData ) return;
34025   if( pWinMemData->hHeap ){
34026     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34027 #ifdef SQLCIPHER_WIN32_MALLOC_VALIDATE
34028     assert( HeapValidate(pWinMemData->hHeap, SQLCIPHER_WIN32_HEAP_FLAGS, NULL) );
34029 #endif
34030     if( pWinMemData->bOwned ){
34031       if( !HeapDestroy(pWinMemData->hHeap) ){
34032         sqlcipher3_log(SQLCIPHER_NOMEM, "failed to HeapDestroy (%d), heap=%p",
34033             GetLastError(), (void*)pWinMemData->hHeap);
34034       }
34035       pWinMemData->bOwned = FALSE;
34036     }
34037     pWinMemData->hHeap = NULL;
34038   }
34039 }
34040
34041 /*
34042 ** Populate the low-level memory allocation function pointers in
34043 ** sqlcipher3GlobalConfig.m with pointers to the routines in this file. The
34044 ** arguments specify the block of memory to manage.
34045 **
34046 ** This routine is only called by sqlcipher3_config(), and therefore
34047 ** is not required to be threadsafe (it is not).
34048 */
34049 SQLCIPHER_PRIVATE const sqlcipher3_mem_methods *sqlcipher3MemGetWin32(void){
34050   static const sqlcipher3_mem_methods winMemMethods = {
34051     winMemMalloc,
34052     winMemFree,
34053     winMemRealloc,
34054     winMemSize,
34055     winMemRoundup,
34056     winMemInit,
34057     winMemShutdown,
34058     &win_mem_data
34059   };
34060   return &winMemMethods;
34061 }
34062
34063 SQLCIPHER_PRIVATE void sqlcipher3MemSetDefault(void){
34064   sqlcipher3_config(SQLCIPHER_CONFIG_MALLOC, sqlcipher3MemGetWin32());
34065 }
34066 #endif /* SQLCIPHER_WIN32_MALLOC */
34067
34068 /*
34069 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
34070 **
34071 ** Space to hold the returned string is obtained from malloc.
34072 */
34073 static WCHAR *utf8ToUnicode(const char *zFilename){
34074   int nChar;
34075   WCHAR *zWideFilename;
34076
34077   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34078   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
34079   if( zWideFilename==0 ){
34080     return 0;
34081   }
34082   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
34083   if( nChar==0 ){
34084     free(zWideFilename);
34085     zWideFilename = 0;
34086   }
34087   return zWideFilename;
34088 }
34089
34090 /*
34091 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
34092 ** obtained from malloc().
34093 */
34094 static char *unicodeToUtf8(const WCHAR *zWideFilename){
34095   int nByte;
34096   char *zFilename;
34097
34098   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34099   zFilename = malloc( nByte );
34100   if( zFilename==0 ){
34101     return 0;
34102   }
34103   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34104                               0, 0);
34105   if( nByte == 0 ){
34106     free(zFilename);
34107     zFilename = 0;
34108   }
34109   return zFilename;
34110 }
34111
34112 /*
34113 ** Convert an ansi string to microsoft unicode, based on the
34114 ** current codepage settings for file apis.
34115 ** 
34116 ** Space to hold the returned string is obtained
34117 ** from malloc.
34118 */
34119 static WCHAR *mbcsToUnicode(const char *zFilename){
34120   int nByte;
34121   WCHAR *zMbcsFilename;
34122   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
34123
34124   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
34125   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
34126   if( zMbcsFilename==0 ){
34127     return 0;
34128   }
34129   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
34130   if( nByte==0 ){
34131     free(zMbcsFilename);
34132     zMbcsFilename = 0;
34133   }
34134   return zMbcsFilename;
34135 }
34136
34137 /*
34138 ** Convert microsoft unicode to multibyte character string, based on the
34139 ** user's Ansi codepage.
34140 **
34141 ** Space to hold the returned string is obtained from
34142 ** malloc().
34143 */
34144 static char *unicodeToMbcs(const WCHAR *zWideFilename){
34145   int nByte;
34146   char *zFilename;
34147   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
34148
34149   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34150   zFilename = malloc( nByte );
34151   if( zFilename==0 ){
34152     return 0;
34153   }
34154   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
34155                               0, 0);
34156   if( nByte == 0 ){
34157     free(zFilename);
34158     zFilename = 0;
34159   }
34160   return zFilename;
34161 }
34162
34163 /*
34164 ** Convert multibyte character string to UTF-8.  Space to hold the
34165 ** returned string is obtained from malloc().
34166 */
34167 SQLCIPHER_API char *sqlcipher3_win32_mbcs_to_utf8(const char *zFilename){
34168   char *zFilenameUtf8;
34169   WCHAR *zTmpWide;
34170
34171   zTmpWide = mbcsToUnicode(zFilename);
34172   if( zTmpWide==0 ){
34173     return 0;
34174   }
34175   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
34176   free(zTmpWide);
34177   return zFilenameUtf8;
34178 }
34179
34180 /*
34181 ** Convert UTF-8 to multibyte character string.  Space to hold the 
34182 ** returned string is obtained from malloc().
34183 */
34184 SQLCIPHER_API char *sqlcipher3_win32_utf8_to_mbcs(const char *zFilename){
34185   char *zFilenameMbcs;
34186   WCHAR *zTmpWide;
34187
34188   zTmpWide = utf8ToUnicode(zFilename);
34189   if( zTmpWide==0 ){
34190     return 0;
34191   }
34192   zFilenameMbcs = unicodeToMbcs(zTmpWide);
34193   free(zTmpWide);
34194   return zFilenameMbcs;
34195 }
34196
34197
34198 /*
34199 ** The return value of getLastErrorMsg
34200 ** is zero if the error message fits in the buffer, or non-zero
34201 ** otherwise (if the message was truncated).
34202 */
34203 static int getLastErrorMsg(int nBuf, char *zBuf){
34204   /* FormatMessage returns 0 on failure.  Otherwise it
34205   ** returns the number of TCHARs written to the output
34206   ** buffer, excluding the terminating null char.
34207   */
34208   DWORD error = GetLastError();
34209   DWORD dwLen = 0;
34210   char *zOut = 0;
34211
34212   if( isNT() ){
34213     WCHAR *zTempWide = NULL;
34214     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
34215                            NULL,
34216                            error,
34217                            0,
34218                            (LPWSTR) &zTempWide,
34219                            0,
34220                            0);
34221     if( dwLen > 0 ){
34222       /* allocate a buffer and convert to UTF8 */
34223       zOut = unicodeToUtf8(zTempWide);
34224       /* free the system buffer allocated by FormatMessage */
34225       LocalFree(zTempWide);
34226     }
34227 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
34228 ** Since the ASCII version of these Windows API do not exist for WINCE,
34229 ** it's important to not reference them for WINCE builds.
34230 */
34231 #if SQLCIPHER_OS_WINCE==0
34232   }else{
34233     char *zTemp = NULL;
34234     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
34235                            NULL,
34236                            error,
34237                            0,
34238                            (LPSTR) &zTemp,
34239                            0,
34240                            0);
34241     if( dwLen > 0 ){
34242       /* allocate a buffer and convert to UTF8 */
34243       zOut = sqlcipher3_win32_mbcs_to_utf8(zTemp);
34244       /* free the system buffer allocated by FormatMessage */
34245       LocalFree(zTemp);
34246     }
34247 #endif
34248   }
34249   if( 0 == dwLen ){
34250     sqlcipher3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
34251   }else{
34252     /* copy a maximum of nBuf chars to output buffer */
34253     sqlcipher3_snprintf(nBuf, zBuf, "%s", zOut);
34254     /* free the UTF8 buffer */
34255     free(zOut);
34256   }
34257   return 0;
34258 }
34259
34260 /*
34261 **
34262 ** This function - winLogErrorAtLine() - is only ever called via the macro
34263 ** winLogError().
34264 **
34265 ** This routine is invoked after an error occurs in an OS function.
34266 ** It logs a message using sqlcipher3_log() containing the current value of
34267 ** error code and, if possible, the human-readable equivalent from 
34268 ** FormatMessage.
34269 **
34270 ** The first argument passed to the macro should be the error code that
34271 ** will be returned to SQLite (e.g. SQLCIPHER_IOERR_DELETE, SQLCIPHER_CANTOPEN). 
34272 ** The two subsequent arguments should be the name of the OS function that
34273 ** failed and the the associated file-system path, if any.
34274 */
34275 #define winLogError(a,b,c)     winLogErrorAtLine(a,b,c,__LINE__)
34276 static int winLogErrorAtLine(
34277   int errcode,                    /* SQLite error code */
34278   const char *zFunc,              /* Name of OS function that failed */
34279   const char *zPath,              /* File path associated with error */
34280   int iLine                       /* Source line number where error occurred */
34281 ){
34282   char zMsg[500];                 /* Human readable error text */
34283   int i;                          /* Loop counter */
34284   DWORD iErrno = GetLastError();  /* Error code */
34285
34286   zMsg[0] = 0;
34287   getLastErrorMsg(sizeof(zMsg), zMsg);
34288   assert( errcode!=SQLCIPHER_OK );
34289   if( zPath==0 ) zPath = "";
34290   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
34291   zMsg[i] = 0;
34292   sqlcipher3_log(errcode,
34293       "os_win.c:%d: (%d) %s(%s) - %s",
34294       iLine, iErrno, zFunc, zPath, zMsg
34295   );
34296
34297   return errcode;
34298 }
34299
34300 /*
34301 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
34302 ** will be retried following a locking error - probably caused by 
34303 ** antivirus software.  Also the initial delay before the first retry.
34304 ** The delay increases linearly with each retry.
34305 */
34306 #ifndef SQLCIPHER_WIN32_IOERR_RETRY
34307 # define SQLCIPHER_WIN32_IOERR_RETRY 10
34308 #endif
34309 #ifndef SQLCIPHER_WIN32_IOERR_RETRY_DELAY
34310 # define SQLCIPHER_WIN32_IOERR_RETRY_DELAY 25
34311 #endif
34312 static int win32IoerrRetry = SQLCIPHER_WIN32_IOERR_RETRY;
34313 static int win32IoerrRetryDelay = SQLCIPHER_WIN32_IOERR_RETRY_DELAY;
34314
34315 /*
34316 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
34317 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
34318 ** to give up with an error.
34319 */
34320 static int retryIoerr(int *pnRetry){
34321   DWORD e;
34322   if( *pnRetry>=win32IoerrRetry ){
34323     return 0;
34324   }
34325   e = GetLastError();
34326   if( e==ERROR_ACCESS_DENIED ||
34327       e==ERROR_LOCK_VIOLATION ||
34328       e==ERROR_SHARING_VIOLATION ){
34329     Sleep(win32IoerrRetryDelay*(1+*pnRetry));
34330     ++*pnRetry;
34331     return 1;
34332   }
34333   return 0;
34334 }
34335
34336 /*
34337 ** Log a I/O error retry episode.
34338 */
34339 static void logIoerr(int nRetry){
34340   if( nRetry ){
34341     sqlcipher3_log(SQLCIPHER_IOERR, 
34342       "delayed %dms for lock/sharing conflict",
34343       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
34344     );
34345   }
34346 }
34347
34348 #if SQLCIPHER_OS_WINCE
34349 /*************************************************************************
34350 ** This section contains code for WinCE only.
34351 */
34352 /*
34353 ** WindowsCE does not have a localtime() function.  So create a
34354 ** substitute.
34355 */
34356 /* #include <time.h> */
34357 struct tm *__cdecl localtime(const time_t *t)
34358 {
34359   static struct tm y;
34360   FILETIME uTm, lTm;
34361   SYSTEMTIME pTm;
34362   sqlcipher3_int64 t64;
34363   t64 = *t;
34364   t64 = (t64 + 11644473600)*10000000;
34365   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
34366   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
34367   FileTimeToLocalFileTime(&uTm,&lTm);
34368   FileTimeToSystemTime(&lTm,&pTm);
34369   y.tm_year = pTm.wYear - 1900;
34370   y.tm_mon = pTm.wMonth - 1;
34371   y.tm_wday = pTm.wDayOfWeek;
34372   y.tm_mday = pTm.wDay;
34373   y.tm_hour = pTm.wHour;
34374   y.tm_min = pTm.wMinute;
34375   y.tm_sec = pTm.wSecond;
34376   return &y;
34377 }
34378
34379 /* This will never be called, but defined to make the code compile */
34380 #define GetTempPathA(a,b)
34381
34382 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
34383 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
34384 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
34385
34386 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
34387
34388 /*
34389 ** Acquire a lock on the handle h
34390 */
34391 static void winceMutexAcquire(HANDLE h){
34392    DWORD dwErr;
34393    do {
34394      dwErr = WaitForSingleObject(h, INFINITE);
34395    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
34396 }
34397 /*
34398 ** Release a lock acquired by winceMutexAcquire()
34399 */
34400 #define winceMutexRelease(h) ReleaseMutex(h)
34401
34402 /*
34403 ** Create the mutex and shared memory used for locking in the file
34404 ** descriptor pFile
34405 */
34406 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
34407   WCHAR *zTok;
34408   WCHAR *zName = utf8ToUnicode(zFilename);
34409   BOOL bInit = TRUE;
34410
34411   /* Initialize the local lockdata */
34412   ZeroMemory(&pFile->local, sizeof(pFile->local));
34413
34414   /* Replace the backslashes from the filename and lowercase it
34415   ** to derive a mutex name. */
34416   zTok = CharLowerW(zName);
34417   for (;*zTok;zTok++){
34418     if (*zTok == '\\') *zTok = '_';
34419   }
34420
34421   /* Create/open the named mutex */
34422   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
34423   if (!pFile->hMutex){
34424     pFile->lastErrno = GetLastError();
34425     winLogError(SQLCIPHER_ERROR, "winceCreateLock1", zFilename);
34426     free(zName);
34427     return FALSE;
34428   }
34429
34430   /* Acquire the mutex before continuing */
34431   winceMutexAcquire(pFile->hMutex);
34432   
34433   /* Since the names of named mutexes, semaphores, file mappings etc are 
34434   ** case-sensitive, take advantage of that by uppercasing the mutex name
34435   ** and using that as the shared filemapping name.
34436   */
34437   CharUpperW(zName);
34438   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
34439                                        PAGE_READWRITE, 0, sizeof(winceLock),
34440                                        zName);  
34441
34442   /* Set a flag that indicates we're the first to create the memory so it 
34443   ** must be zero-initialized */
34444   if (GetLastError() == ERROR_ALREADY_EXISTS){
34445     bInit = FALSE;
34446   }
34447
34448   free(zName);
34449
34450   /* If we succeeded in making the shared memory handle, map it. */
34451   if (pFile->hShared){
34452     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
34453              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
34454     /* If mapping failed, close the shared memory handle and erase it */
34455     if (!pFile->shared){
34456       pFile->lastErrno = GetLastError();
34457       winLogError(SQLCIPHER_ERROR, "winceCreateLock2", zFilename);
34458       CloseHandle(pFile->hShared);
34459       pFile->hShared = NULL;
34460     }
34461   }
34462
34463   /* If shared memory could not be created, then close the mutex and fail */
34464   if (pFile->hShared == NULL){
34465     winceMutexRelease(pFile->hMutex);
34466     CloseHandle(pFile->hMutex);
34467     pFile->hMutex = NULL;
34468     return FALSE;
34469   }
34470   
34471   /* Initialize the shared memory if we're supposed to */
34472   if (bInit) {
34473     ZeroMemory(pFile->shared, sizeof(winceLock));
34474   }
34475
34476   winceMutexRelease(pFile->hMutex);
34477   return TRUE;
34478 }
34479
34480 /*
34481 ** Destroy the part of winFile that deals with wince locks
34482 */
34483 static void winceDestroyLock(winFile *pFile){
34484   if (pFile->hMutex){
34485     /* Acquire the mutex */
34486     winceMutexAcquire(pFile->hMutex);
34487
34488     /* The following blocks should probably assert in debug mode, but they
34489        are to cleanup in case any locks remained open */
34490     if (pFile->local.nReaders){
34491       pFile->shared->nReaders --;
34492     }
34493     if (pFile->local.bReserved){
34494       pFile->shared->bReserved = FALSE;
34495     }
34496     if (pFile->local.bPending){
34497       pFile->shared->bPending = FALSE;
34498     }
34499     if (pFile->local.bExclusive){
34500       pFile->shared->bExclusive = FALSE;
34501     }
34502
34503     /* De-reference and close our copy of the shared memory handle */
34504     UnmapViewOfFile(pFile->shared);
34505     CloseHandle(pFile->hShared);
34506
34507     /* Done with the mutex */
34508     winceMutexRelease(pFile->hMutex);    
34509     CloseHandle(pFile->hMutex);
34510     pFile->hMutex = NULL;
34511   }
34512 }
34513
34514 /* 
34515 ** An implementation of the LockFile() API of windows for wince
34516 */
34517 static BOOL winceLockFile(
34518   HANDLE *phFile,
34519   DWORD dwFileOffsetLow,
34520   DWORD dwFileOffsetHigh,
34521   DWORD nNumberOfBytesToLockLow,
34522   DWORD nNumberOfBytesToLockHigh
34523 ){
34524   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34525   BOOL bReturn = FALSE;
34526
34527   UNUSED_PARAMETER(dwFileOffsetHigh);
34528   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34529
34530   if (!pFile->hMutex) return TRUE;
34531   winceMutexAcquire(pFile->hMutex);
34532
34533   /* Wanting an exclusive lock? */
34534   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
34535        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34536     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
34537        pFile->shared->bExclusive = TRUE;
34538        pFile->local.bExclusive = TRUE;
34539        bReturn = TRUE;
34540     }
34541   }
34542
34543   /* Want a read-only lock? */
34544   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
34545            nNumberOfBytesToLockLow == 1){
34546     if (pFile->shared->bExclusive == 0){
34547       pFile->local.nReaders ++;
34548       if (pFile->local.nReaders == 1){
34549         pFile->shared->nReaders ++;
34550       }
34551       bReturn = TRUE;
34552     }
34553   }
34554
34555   /* Want a pending lock? */
34556   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
34557     /* If no pending lock has been acquired, then acquire it */
34558     if (pFile->shared->bPending == 0) {
34559       pFile->shared->bPending = TRUE;
34560       pFile->local.bPending = TRUE;
34561       bReturn = TRUE;
34562     }
34563   }
34564
34565   /* Want a reserved lock? */
34566   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
34567     if (pFile->shared->bReserved == 0) {
34568       pFile->shared->bReserved = TRUE;
34569       pFile->local.bReserved = TRUE;
34570       bReturn = TRUE;
34571     }
34572   }
34573
34574   winceMutexRelease(pFile->hMutex);
34575   return bReturn;
34576 }
34577
34578 /*
34579 ** An implementation of the UnlockFile API of windows for wince
34580 */
34581 static BOOL winceUnlockFile(
34582   HANDLE *phFile,
34583   DWORD dwFileOffsetLow,
34584   DWORD dwFileOffsetHigh,
34585   DWORD nNumberOfBytesToUnlockLow,
34586   DWORD nNumberOfBytesToUnlockHigh
34587 ){
34588   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34589   BOOL bReturn = FALSE;
34590
34591   UNUSED_PARAMETER(dwFileOffsetHigh);
34592   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
34593
34594   if (!pFile->hMutex) return TRUE;
34595   winceMutexAcquire(pFile->hMutex);
34596
34597   /* Releasing a reader lock or an exclusive lock */
34598   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
34599     /* Did we have an exclusive lock? */
34600     if (pFile->local.bExclusive){
34601       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
34602       pFile->local.bExclusive = FALSE;
34603       pFile->shared->bExclusive = FALSE;
34604       bReturn = TRUE;
34605     }
34606
34607     /* Did we just have a reader lock? */
34608     else if (pFile->local.nReaders){
34609       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
34610       pFile->local.nReaders --;
34611       if (pFile->local.nReaders == 0)
34612       {
34613         pFile->shared->nReaders --;
34614       }
34615       bReturn = TRUE;
34616     }
34617   }
34618
34619   /* Releasing a pending lock */
34620   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
34621     if (pFile->local.bPending){
34622       pFile->local.bPending = FALSE;
34623       pFile->shared->bPending = FALSE;
34624       bReturn = TRUE;
34625     }
34626   }
34627   /* Releasing a reserved lock */
34628   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
34629     if (pFile->local.bReserved) {
34630       pFile->local.bReserved = FALSE;
34631       pFile->shared->bReserved = FALSE;
34632       bReturn = TRUE;
34633     }
34634   }
34635
34636   winceMutexRelease(pFile->hMutex);
34637   return bReturn;
34638 }
34639
34640 /*
34641 ** An implementation of the LockFileEx() API of windows for wince
34642 */
34643 static BOOL winceLockFileEx(
34644   HANDLE *phFile,
34645   DWORD dwFlags,
34646   DWORD dwReserved,
34647   DWORD nNumberOfBytesToLockLow,
34648   DWORD nNumberOfBytesToLockHigh,
34649   LPOVERLAPPED lpOverlapped
34650 ){
34651   UNUSED_PARAMETER(dwReserved);
34652   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34653
34654   /* If the caller wants a shared read lock, forward this call
34655   ** to winceLockFile */
34656   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
34657       dwFlags == 1 &&
34658       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34659     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
34660   }
34661   return FALSE;
34662 }
34663 /*
34664 ** End of the special code for wince
34665 *****************************************************************************/
34666 #endif /* SQLCIPHER_OS_WINCE */
34667
34668 /*****************************************************************************
34669 ** The next group of routines implement the I/O methods specified
34670 ** by the sqlcipher3_io_methods object.
34671 ******************************************************************************/
34672
34673 /*
34674 ** Some microsoft compilers lack this definition.
34675 */
34676 #ifndef INVALID_SET_FILE_POINTER
34677 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
34678 #endif
34679
34680 /*
34681 ** Move the current position of the file handle passed as the first 
34682 ** argument to offset iOffset within the file. If successful, return 0. 
34683 ** Otherwise, set pFile->lastErrno and return non-zero.
34684 */
34685 static int seekWinFile(winFile *pFile, sqlcipher3_int64 iOffset){
34686   LONG upperBits;                 /* Most sig. 32 bits of new offset */
34687   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
34688   DWORD dwRet;                    /* Value returned by SetFilePointer() */
34689
34690   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
34691   lowerBits = (LONG)(iOffset & 0xffffffff);
34692
34693   /* API oddity: If successful, SetFilePointer() returns a dword 
34694   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
34695   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
34696   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
34697   ** whether an error has actually occured, it is also necessary to call 
34698   ** GetLastError().
34699   */
34700   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
34701   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
34702     pFile->lastErrno = GetLastError();
34703     winLogError(SQLCIPHER_IOERR_SEEK, "seekWinFile", pFile->zPath);
34704     return 1;
34705   }
34706
34707   return 0;
34708 }
34709
34710 /*
34711 ** Close a file.
34712 **
34713 ** It is reported that an attempt to close a handle might sometimes
34714 ** fail.  This is a very unreasonable result, but windows is notorious
34715 ** for being unreasonable so I do not doubt that it might happen.  If
34716 ** the close fails, we pause for 100 milliseconds and try again.  As
34717 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
34718 ** giving up and returning an error.
34719 */
34720 #define MX_CLOSE_ATTEMPT 3
34721 static int winClose(sqlcipher3_file *id){
34722   int rc, cnt = 0;
34723   winFile *pFile = (winFile*)id;
34724
34725   assert( id!=0 );
34726   assert( pFile->pShm==0 );
34727   OSTRACE(("CLOSE %d\n", pFile->h));
34728   do{
34729     rc = CloseHandle(pFile->h);
34730     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
34731   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
34732 #if SQLCIPHER_OS_WINCE
34733 #define WINCE_DELETION_ATTEMPTS 3
34734   winceDestroyLock(pFile);
34735   if( pFile->zDeleteOnClose ){
34736     int cnt = 0;
34737     while(
34738            DeleteFileW(pFile->zDeleteOnClose)==0
34739         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
34740         && cnt++ < WINCE_DELETION_ATTEMPTS
34741     ){
34742        Sleep(100);  /* Wait a little before trying again */
34743     }
34744     free(pFile->zDeleteOnClose);
34745   }
34746 #endif
34747   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
34748   OpenCounter(-1);
34749   return rc ? SQLCIPHER_OK
34750             : winLogError(SQLCIPHER_IOERR_CLOSE, "winClose", pFile->zPath);
34751 }
34752
34753 /*
34754 ** Read data from a file into a buffer.  Return SQLCIPHER_OK if all
34755 ** bytes were read successfully and SQLCIPHER_IOERR if anything goes
34756 ** wrong.
34757 */
34758 static int winRead(
34759   sqlcipher3_file *id,          /* File to read from */
34760   void *pBuf,                /* Write content into this buffer */
34761   int amt,                   /* Number of bytes to read */
34762   sqlcipher3_int64 offset       /* Begin reading at this offset */
34763 ){
34764   winFile *pFile = (winFile*)id;  /* file handle */
34765   DWORD nRead;                    /* Number of bytes actually read from file */
34766   int nRetry = 0;                 /* Number of retrys */
34767
34768   assert( id!=0 );
34769   SimulateIOError(return SQLCIPHER_IOERR_READ);
34770   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
34771
34772   if( seekWinFile(pFile, offset) ){
34773     return SQLCIPHER_FULL;
34774   }
34775   while( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
34776     if( retryIoerr(&nRetry) ) continue;
34777     pFile->lastErrno = GetLastError();
34778     return winLogError(SQLCIPHER_IOERR_READ, "winRead", pFile->zPath);
34779   }
34780   logIoerr(nRetry);
34781   if( nRead<(DWORD)amt ){
34782     /* Unread parts of the buffer must be zero-filled */
34783     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
34784     return SQLCIPHER_IOERR_SHORT_READ;
34785   }
34786
34787   return SQLCIPHER_OK;
34788 }
34789
34790 /*
34791 ** Write data from a buffer into a file.  Return SQLCIPHER_OK on success
34792 ** or some other error code on failure.
34793 */
34794 static int winWrite(
34795   sqlcipher3_file *id,               /* File to write into */
34796   const void *pBuf,               /* The bytes to be written */
34797   int amt,                        /* Number of bytes to write */
34798   sqlcipher3_int64 offset            /* Offset into the file to begin writing at */
34799 ){
34800   int rc;                         /* True if error has occured, else false */
34801   winFile *pFile = (winFile*)id;  /* File handle */
34802   int nRetry = 0;                 /* Number of retries */
34803
34804   assert( amt>0 );
34805   assert( pFile );
34806   SimulateIOError(return SQLCIPHER_IOERR_WRITE);
34807   SimulateDiskfullError(return SQLCIPHER_FULL);
34808
34809   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
34810
34811   rc = seekWinFile(pFile, offset);
34812   if( rc==0 ){
34813     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
34814     int nRem = amt;               /* Number of bytes yet to be written */
34815     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
34816
34817     while( nRem>0 ){
34818       if( !WriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
34819         if( retryIoerr(&nRetry) ) continue;
34820         break;
34821       }
34822       if( nWrite<=0 ) break;
34823       aRem += nWrite;
34824       nRem -= nWrite;
34825     }
34826     if( nRem>0 ){
34827       pFile->lastErrno = GetLastError();
34828       rc = 1;
34829     }
34830   }
34831
34832   if( rc ){
34833     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
34834        || ( pFile->lastErrno==ERROR_DISK_FULL )){
34835       return SQLCIPHER_FULL;
34836     }
34837     return winLogError(SQLCIPHER_IOERR_WRITE, "winWrite", pFile->zPath);
34838   }else{
34839     logIoerr(nRetry);
34840   }
34841   return SQLCIPHER_OK;
34842 }
34843
34844 /*
34845 ** Truncate an open file to a specified size
34846 */
34847 static int winTruncate(sqlcipher3_file *id, sqlcipher3_int64 nByte){
34848   winFile *pFile = (winFile*)id;  /* File handle object */
34849   int rc = SQLCIPHER_OK;             /* Return code for this function */
34850
34851   assert( pFile );
34852
34853   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
34854   SimulateIOError(return SQLCIPHER_IOERR_TRUNCATE);
34855
34856   /* If the user has configured a chunk-size for this file, truncate the
34857   ** file so that it consists of an integer number of chunks (i.e. the
34858   ** actual file size after the operation may be larger than the requested
34859   ** size).
34860   */
34861   if( pFile->szChunk>0 ){
34862     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34863   }
34864
34865   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
34866   if( seekWinFile(pFile, nByte) ){
34867     rc = winLogError(SQLCIPHER_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
34868   }else if( 0==SetEndOfFile(pFile->h) ){
34869     pFile->lastErrno = GetLastError();
34870     rc = winLogError(SQLCIPHER_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
34871   }
34872
34873   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
34874   return rc;
34875 }
34876
34877 #ifdef SQLCIPHER_TEST
34878 /*
34879 ** Count the number of fullsyncs and normal syncs.  This is used to test
34880 ** that syncs and fullsyncs are occuring at the right times.
34881 */
34882 SQLCIPHER_API int sqlcipher3_sync_count = 0;
34883 SQLCIPHER_API int sqlcipher3_fullsync_count = 0;
34884 #endif
34885
34886 /*
34887 ** Make sure all writes to a particular file are committed to disk.
34888 */
34889 static int winSync(sqlcipher3_file *id, int flags){
34890 #ifndef SQLCIPHER_NO_SYNC
34891   /*
34892   ** Used only when SQLCIPHER_NO_SYNC is not defined.
34893    */
34894   BOOL rc;
34895 #endif
34896 #if !defined(NDEBUG) || !defined(SQLCIPHER_NO_SYNC) || \
34897     (defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG))
34898   /*
34899   ** Used when SQLCIPHER_NO_SYNC is not defined and by the assert() and/or
34900   ** OSTRACE() macros.
34901    */
34902   winFile *pFile = (winFile*)id;
34903 #else
34904   UNUSED_PARAMETER(id);
34905 #endif
34906
34907   assert( pFile );
34908   /* Check that one of SQLCIPHER_SYNC_NORMAL or FULL was passed */
34909   assert((flags&0x0F)==SQLCIPHER_SYNC_NORMAL
34910       || (flags&0x0F)==SQLCIPHER_SYNC_FULL
34911   );
34912
34913   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
34914
34915   /* Unix cannot, but some systems may return SQLCIPHER_FULL from here. This
34916   ** line is to test that doing so does not cause any problems.
34917   */
34918   SimulateDiskfullError( return SQLCIPHER_FULL );
34919
34920 #ifndef SQLCIPHER_TEST
34921   UNUSED_PARAMETER(flags);
34922 #else
34923   if( (flags&0x0F)==SQLCIPHER_SYNC_FULL ){
34924     sqlcipher3_fullsync_count++;
34925   }
34926   sqlcipher3_sync_count++;
34927 #endif
34928
34929   /* If we compiled with the SQLCIPHER_NO_SYNC flag, then syncing is a
34930   ** no-op
34931   */
34932 #ifdef SQLCIPHER_NO_SYNC
34933   return SQLCIPHER_OK;
34934 #else
34935   rc = FlushFileBuffers(pFile->h);
34936   SimulateIOError( rc=FALSE );
34937   if( rc ){
34938     return SQLCIPHER_OK;
34939   }else{
34940     pFile->lastErrno = GetLastError();
34941     return winLogError(SQLCIPHER_IOERR_FSYNC, "winSync", pFile->zPath);
34942   }
34943 #endif
34944 }
34945
34946 /*
34947 ** Determine the current size of a file in bytes
34948 */
34949 static int winFileSize(sqlcipher3_file *id, sqlcipher3_int64 *pSize){
34950   DWORD upperBits;
34951   DWORD lowerBits;
34952   winFile *pFile = (winFile*)id;
34953   DWORD error;
34954
34955   assert( id!=0 );
34956   SimulateIOError(return SQLCIPHER_IOERR_FSTAT);
34957   lowerBits = GetFileSize(pFile->h, &upperBits);
34958   if(   (lowerBits == INVALID_FILE_SIZE)
34959      && ((error = GetLastError()) != NO_ERROR) )
34960   {
34961     pFile->lastErrno = error;
34962     return winLogError(SQLCIPHER_IOERR_FSTAT, "winFileSize", pFile->zPath);
34963   }
34964   *pSize = (((sqlcipher3_int64)upperBits)<<32) + lowerBits;
34965   return SQLCIPHER_OK;
34966 }
34967
34968 /*
34969 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
34970 */
34971 #ifndef LOCKFILE_FAIL_IMMEDIATELY
34972 # define LOCKFILE_FAIL_IMMEDIATELY 1
34973 #endif
34974
34975 /*
34976 ** Acquire a reader lock.
34977 ** Different API routines are called depending on whether or not this
34978 ** is Win95 or WinNT.
34979 */
34980 static int getReadLock(winFile *pFile){
34981   int res;
34982   if( isNT() ){
34983     OVERLAPPED ovlp;
34984     ovlp.Offset = SHARED_FIRST;
34985     ovlp.OffsetHigh = 0;
34986     ovlp.hEvent = 0;
34987     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
34988                      0, SHARED_SIZE, 0, &ovlp);
34989 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
34990 */
34991 #if SQLCIPHER_OS_WINCE==0
34992   }else{
34993     int lk;
34994     sqlcipher3_randomness(sizeof(lk), &lk);
34995     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34996     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34997 #endif
34998   }
34999   if( res == 0 ){
35000     pFile->lastErrno = GetLastError();
35001     /* No need to log a failure to lock */
35002   }
35003   return res;
35004 }
35005
35006 /*
35007 ** Undo a readlock
35008 */
35009 static int unlockReadLock(winFile *pFile){
35010   int res;
35011   if( isNT() ){
35012     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35013 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
35014 */
35015 #if SQLCIPHER_OS_WINCE==0
35016   }else{
35017     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
35018 #endif
35019   }
35020   if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
35021     pFile->lastErrno = GetLastError();
35022     winLogError(SQLCIPHER_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
35023   }
35024   return res;
35025 }
35026
35027 /*
35028 ** Lock the file with the lock specified by parameter locktype - one
35029 ** of the following:
35030 **
35031 **     (1) SHARED_LOCK
35032 **     (2) RESERVED_LOCK
35033 **     (3) PENDING_LOCK
35034 **     (4) EXCLUSIVE_LOCK
35035 **
35036 ** Sometimes when requesting one lock state, additional lock states
35037 ** are inserted in between.  The locking might fail on one of the later
35038 ** transitions leaving the lock state different from what it started but
35039 ** still short of its goal.  The following chart shows the allowed
35040 ** transitions and the inserted intermediate states:
35041 **
35042 **    UNLOCKED -> SHARED
35043 **    SHARED -> RESERVED
35044 **    SHARED -> (PENDING) -> EXCLUSIVE
35045 **    RESERVED -> (PENDING) -> EXCLUSIVE
35046 **    PENDING -> EXCLUSIVE
35047 **
35048 ** This routine will only increase a lock.  The winUnlock() routine
35049 ** erases all locks at once and returns us immediately to locking level 0.
35050 ** It is not possible to lower the locking level one step at a time.  You
35051 ** must go straight to locking level 0.
35052 */
35053 static int winLock(sqlcipher3_file *id, int locktype){
35054   int rc = SQLCIPHER_OK;    /* Return code from subroutines */
35055   int res = 1;           /* Result of a windows lock call */
35056   int newLocktype;       /* Set pFile->locktype to this value before exiting */
35057   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
35058   winFile *pFile = (winFile*)id;
35059   DWORD error = NO_ERROR;
35060
35061   assert( id!=0 );
35062   OSTRACE(("LOCK %d %d was %d(%d)\n",
35063            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
35064
35065   /* If there is already a lock of this type or more restrictive on the
35066   ** OsFile, do nothing. Don't use the end_lock: exit path, as
35067   ** sqlcipher3OsEnterMutex() hasn't been called yet.
35068   */
35069   if( pFile->locktype>=locktype ){
35070     return SQLCIPHER_OK;
35071   }
35072
35073   /* Make sure the locking sequence is correct
35074   */
35075   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
35076   assert( locktype!=PENDING_LOCK );
35077   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
35078
35079   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
35080   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
35081   ** the PENDING_LOCK byte is temporary.
35082   */
35083   newLocktype = pFile->locktype;
35084   if(   (pFile->locktype==NO_LOCK)
35085      || (   (locktype==EXCLUSIVE_LOCK)
35086          && (pFile->locktype==RESERVED_LOCK))
35087   ){
35088     int cnt = 3;
35089     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
35090       /* Try 3 times to get the pending lock.  The pending lock might be
35091       ** held by another reader process who will release it momentarily.
35092       */
35093       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
35094       Sleep(1);
35095     }
35096     gotPendingLock = res;
35097     if( !res ){
35098       error = GetLastError();
35099     }
35100   }
35101
35102   /* Acquire a shared lock
35103   */
35104   if( locktype==SHARED_LOCK && res ){
35105     assert( pFile->locktype==NO_LOCK );
35106     res = getReadLock(pFile);
35107     if( res ){
35108       newLocktype = SHARED_LOCK;
35109     }else{
35110       error = GetLastError();
35111     }
35112   }
35113
35114   /* Acquire a RESERVED lock
35115   */
35116   if( locktype==RESERVED_LOCK && res ){
35117     assert( pFile->locktype==SHARED_LOCK );
35118     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35119     if( res ){
35120       newLocktype = RESERVED_LOCK;
35121     }else{
35122       error = GetLastError();
35123     }
35124   }
35125
35126   /* Acquire a PENDING lock
35127   */
35128   if( locktype==EXCLUSIVE_LOCK && res ){
35129     newLocktype = PENDING_LOCK;
35130     gotPendingLock = 0;
35131   }
35132
35133   /* Acquire an EXCLUSIVE lock
35134   */
35135   if( locktype==EXCLUSIVE_LOCK && res ){
35136     assert( pFile->locktype>=SHARED_LOCK );
35137     res = unlockReadLock(pFile);
35138     OSTRACE(("unreadlock = %d\n", res));
35139     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35140     if( res ){
35141       newLocktype = EXCLUSIVE_LOCK;
35142     }else{
35143       error = GetLastError();
35144       OSTRACE(("error-code = %d\n", error));
35145       getReadLock(pFile);
35146     }
35147   }
35148
35149   /* If we are holding a PENDING lock that ought to be released, then
35150   ** release it now.
35151   */
35152   if( gotPendingLock && locktype==SHARED_LOCK ){
35153     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
35154   }
35155
35156   /* Update the state of the lock has held in the file descriptor then
35157   ** return the appropriate result code.
35158   */
35159   if( res ){
35160     rc = SQLCIPHER_OK;
35161   }else{
35162     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
35163            locktype, newLocktype));
35164     pFile->lastErrno = error;
35165     rc = SQLCIPHER_BUSY;
35166   }
35167   pFile->locktype = (u8)newLocktype;
35168   return rc;
35169 }
35170
35171 /*
35172 ** This routine checks if there is a RESERVED lock held on the specified
35173 ** file by this or any other process. If such a lock is held, return
35174 ** non-zero, otherwise zero.
35175 */
35176 static int winCheckReservedLock(sqlcipher3_file *id, int *pResOut){
35177   int rc;
35178   winFile *pFile = (winFile*)id;
35179
35180   SimulateIOError( return SQLCIPHER_IOERR_CHECKRESERVEDLOCK; );
35181
35182   assert( id!=0 );
35183   if( pFile->locktype>=RESERVED_LOCK ){
35184     rc = 1;
35185     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
35186   }else{
35187     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35188     if( rc ){
35189       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35190     }
35191     rc = !rc;
35192     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
35193   }
35194   *pResOut = rc;
35195   return SQLCIPHER_OK;
35196 }
35197
35198 /*
35199 ** Lower the locking level on file descriptor id to locktype.  locktype
35200 ** must be either NO_LOCK or SHARED_LOCK.
35201 **
35202 ** If the locking level of the file descriptor is already at or below
35203 ** the requested locking level, this routine is a no-op.
35204 **
35205 ** It is not possible for this routine to fail if the second argument
35206 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
35207 ** might return SQLCIPHER_IOERR;
35208 */
35209 static int winUnlock(sqlcipher3_file *id, int locktype){
35210   int type;
35211   winFile *pFile = (winFile*)id;
35212   int rc = SQLCIPHER_OK;
35213   assert( pFile!=0 );
35214   assert( locktype<=SHARED_LOCK );
35215   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
35216           pFile->locktype, pFile->sharedLockByte));
35217   type = pFile->locktype;
35218   if( type>=EXCLUSIVE_LOCK ){
35219     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35220     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
35221       /* This should never happen.  We should always be able to
35222       ** reacquire the read lock */
35223       rc = winLogError(SQLCIPHER_IOERR_UNLOCK, "winUnlock", pFile->zPath);
35224     }
35225   }
35226   if( type>=RESERVED_LOCK ){
35227     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
35228   }
35229   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
35230     unlockReadLock(pFile);
35231   }
35232   if( type>=PENDING_LOCK ){
35233     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
35234   }
35235   pFile->locktype = (u8)locktype;
35236   return rc;
35237 }
35238
35239 /*
35240 ** Control and query of the open file handle.
35241 */
35242 static int winFileControl(sqlcipher3_file *id, int op, void *pArg){
35243   winFile *pFile = (winFile*)id;
35244   switch( op ){
35245     case SQLCIPHER_FCNTL_LOCKSTATE: {
35246       *(int*)pArg = pFile->locktype;
35247       return SQLCIPHER_OK;
35248     }
35249     case SQLCIPHER_LAST_ERRNO: {
35250       *(int*)pArg = (int)pFile->lastErrno;
35251       return SQLCIPHER_OK;
35252     }
35253     case SQLCIPHER_FCNTL_CHUNK_SIZE: {
35254       pFile->szChunk = *(int *)pArg;
35255       return SQLCIPHER_OK;
35256     }
35257     case SQLCIPHER_FCNTL_SIZE_HINT: {
35258       if( pFile->szChunk>0 ){
35259         sqlcipher3_int64 oldSz;
35260         int rc = winFileSize(id, &oldSz);
35261         if( rc==SQLCIPHER_OK ){
35262           sqlcipher3_int64 newSz = *(sqlcipher3_int64*)pArg;
35263           if( newSz>oldSz ){
35264             SimulateIOErrorBenign(1);
35265             rc = winTruncate(id, newSz);
35266             SimulateIOErrorBenign(0);
35267           }
35268         }
35269         return rc;
35270       }
35271       return SQLCIPHER_OK;
35272     }
35273     case SQLCIPHER_FCNTL_PERSIST_WAL: {
35274       int bPersist = *(int*)pArg;
35275       if( bPersist<0 ){
35276         *(int*)pArg = pFile->bPersistWal;
35277       }else{
35278         pFile->bPersistWal = bPersist!=0;
35279       }
35280       return SQLCIPHER_OK;
35281     }
35282     case SQLCIPHER_FCNTL_SYNC_OMITTED: {
35283       return SQLCIPHER_OK;
35284     }
35285     case SQLCIPHER_FCNTL_WIN32_AV_RETRY: {
35286       int *a = (int*)pArg;
35287       if( a[0]>0 ){
35288         win32IoerrRetry = a[0];
35289       }else{
35290         a[0] = win32IoerrRetry;
35291       }
35292       if( a[1]>0 ){
35293         win32IoerrRetryDelay = a[1];
35294       }else{
35295         a[1] = win32IoerrRetryDelay;
35296       }
35297       return SQLCIPHER_OK;
35298     }
35299   }
35300   return SQLCIPHER_NOTFOUND;
35301 }
35302
35303 /*
35304 ** Return the sector size in bytes of the underlying block device for
35305 ** the specified file. This is almost always 512 bytes, but may be
35306 ** larger for some devices.
35307 **
35308 ** SQLite code assumes this function cannot fail. It also assumes that
35309 ** if two files are created in the same file-system directory (i.e.
35310 ** a database and its journal file) that the sector size will be the
35311 ** same for both.
35312 */
35313 static int winSectorSize(sqlcipher3_file *id){
35314   assert( id!=0 );
35315   return (int)(((winFile*)id)->sectorSize);
35316 }
35317
35318 /*
35319 ** Return a vector of device characteristics.
35320 */
35321 static int winDeviceCharacteristics(sqlcipher3_file *id){
35322   UNUSED_PARAMETER(id);
35323   return SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN;
35324 }
35325
35326 #ifndef SQLCIPHER_OMIT_WAL
35327
35328 /* 
35329 ** Windows will only let you create file view mappings
35330 ** on allocation size granularity boundaries.
35331 ** During sqlcipher3_os_init() we do a GetSystemInfo()
35332 ** to get the granularity size.
35333 */
35334 SYSTEM_INFO winSysInfo;
35335
35336 /*
35337 ** Helper functions to obtain and relinquish the global mutex. The
35338 ** global mutex is used to protect the winLockInfo objects used by 
35339 ** this file, all of which may be shared by multiple threads.
35340 **
35341 ** Function winShmMutexHeld() is used to assert() that the global mutex 
35342 ** is held when required. This function is only used as part of assert() 
35343 ** statements. e.g.
35344 **
35345 **   winShmEnterMutex()
35346 **     assert( winShmMutexHeld() );
35347 **   winShmLeaveMutex()
35348 */
35349 static void winShmEnterMutex(void){
35350   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
35351 }
35352 static void winShmLeaveMutex(void){
35353   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
35354 }
35355 #ifdef SQLCIPHER_DEBUG
35356 static int winShmMutexHeld(void) {
35357   return sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
35358 }
35359 #endif
35360
35361 /*
35362 ** Object used to represent a single file opened and mmapped to provide
35363 ** shared memory.  When multiple threads all reference the same
35364 ** log-summary, each thread has its own winFile object, but they all
35365 ** point to a single instance of this object.  In other words, each
35366 ** log-summary is opened only once per process.
35367 **
35368 ** winShmMutexHeld() must be true when creating or destroying
35369 ** this object or while reading or writing the following fields:
35370 **
35371 **      nRef
35372 **      pNext 
35373 **
35374 ** The following fields are read-only after the object is created:
35375 ** 
35376 **      fid
35377 **      zFilename
35378 **
35379 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
35380 ** winShmMutexHeld() is true when reading or writing any other field
35381 ** in this structure.
35382 **
35383 */
35384 struct winShmNode {
35385   sqlcipher3_mutex *mutex;      /* Mutex to access this object */
35386   char *zFilename;           /* Name of the file */
35387   winFile hFile;             /* File handle from winOpen */
35388
35389   int szRegion;              /* Size of shared-memory regions */
35390   int nRegion;               /* Size of array apRegion */
35391   struct ShmRegion {
35392     HANDLE hMap;             /* File handle from CreateFileMapping */
35393     void *pMap;
35394   } *aRegion;
35395   DWORD lastErrno;           /* The Windows errno from the last I/O error */
35396
35397   int nRef;                  /* Number of winShm objects pointing to this */
35398   winShm *pFirst;            /* All winShm objects pointing to this */
35399   winShmNode *pNext;         /* Next in list of all winShmNode objects */
35400 #ifdef SQLCIPHER_DEBUG
35401   u8 nextShmId;              /* Next available winShm.id value */
35402 #endif
35403 };
35404
35405 /*
35406 ** A global array of all winShmNode objects.
35407 **
35408 ** The winShmMutexHeld() must be true while reading or writing this list.
35409 */
35410 static winShmNode *winShmNodeList = 0;
35411
35412 /*
35413 ** Structure used internally by this VFS to record the state of an
35414 ** open shared memory connection.
35415 **
35416 ** The following fields are initialized when this object is created and
35417 ** are read-only thereafter:
35418 **
35419 **    winShm.pShmNode
35420 **    winShm.id
35421 **
35422 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
35423 ** while accessing any read/write fields.
35424 */
35425 struct winShm {
35426   winShmNode *pShmNode;      /* The underlying winShmNode object */
35427   winShm *pNext;             /* Next winShm with the same winShmNode */
35428   u8 hasMutex;               /* True if holding the winShmNode mutex */
35429   u16 sharedMask;            /* Mask of shared locks held */
35430   u16 exclMask;              /* Mask of exclusive locks held */
35431 #ifdef SQLCIPHER_DEBUG
35432   u8 id;                     /* Id of this connection with its winShmNode */
35433 #endif
35434 };
35435
35436 /*
35437 ** Constants used for locking
35438 */
35439 #define WIN_SHM_BASE   ((22+SQLCIPHER_SHM_NLOCK)*4)        /* first lock byte */
35440 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLCIPHER_SHM_NLOCK)  /* deadman switch */
35441
35442 /*
35443 ** Apply advisory locks for all n bytes beginning at ofst.
35444 */
35445 #define _SHM_UNLCK  1
35446 #define _SHM_RDLCK  2
35447 #define _SHM_WRLCK  3
35448 static int winShmSystemLock(
35449   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
35450   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
35451   int ofst,             /* Offset to first byte to be locked/unlocked */
35452   int nByte             /* Number of bytes to lock or unlock */
35453 ){
35454   OVERLAPPED ovlp;
35455   DWORD dwFlags;
35456   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
35457
35458   /* Access to the winShmNode object is serialized by the caller */
35459   assert( sqlcipher3_mutex_held(pFile->mutex) || pFile->nRef==0 );
35460
35461   /* Initialize the locking parameters */
35462   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
35463   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
35464
35465   memset(&ovlp, 0, sizeof(OVERLAPPED));
35466   ovlp.Offset = ofst;
35467
35468   /* Release/Acquire the system-level lock */
35469   if( lockType==_SHM_UNLCK ){
35470     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
35471   }else{
35472     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
35473   }
35474   
35475   if( rc!= 0 ){
35476     rc = SQLCIPHER_OK;
35477   }else{
35478     pFile->lastErrno =  GetLastError();
35479     rc = SQLCIPHER_BUSY;
35480   }
35481
35482   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
35483            pFile->hFile.h,
35484            rc==SQLCIPHER_OK ? "ok" : "failed",
35485            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
35486            pFile->lastErrno));
35487
35488   return rc;
35489 }
35490
35491 /* Forward references to VFS methods */
35492 static int winOpen(sqlcipher3_vfs*,const char*,sqlcipher3_file*,int,int*);
35493 static int winDelete(sqlcipher3_vfs *,const char*,int);
35494
35495 /*
35496 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
35497 **
35498 ** This is not a VFS shared-memory method; it is a utility function called
35499 ** by VFS shared-memory methods.
35500 */
35501 static void winShmPurge(sqlcipher3_vfs *pVfs, int deleteFlag){
35502   winShmNode **pp;
35503   winShmNode *p;
35504   BOOL bRc;
35505   assert( winShmMutexHeld() );
35506   pp = &winShmNodeList;
35507   while( (p = *pp)!=0 ){
35508     if( p->nRef==0 ){
35509       int i;
35510       if( p->mutex ) sqlcipher3_mutex_free(p->mutex);
35511       for(i=0; i<p->nRegion; i++){
35512         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
35513         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
35514                  (int)GetCurrentProcessId(), i,
35515                  bRc ? "ok" : "failed"));
35516         bRc = CloseHandle(p->aRegion[i].hMap);
35517         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
35518                  (int)GetCurrentProcessId(), i,
35519                  bRc ? "ok" : "failed"));
35520       }
35521       if( p->hFile.h != INVALID_HANDLE_VALUE ){
35522         SimulateIOErrorBenign(1);
35523         winClose((sqlcipher3_file *)&p->hFile);
35524         SimulateIOErrorBenign(0);
35525       }
35526       if( deleteFlag ){
35527         SimulateIOErrorBenign(1);
35528         winDelete(pVfs, p->zFilename, 0);
35529         SimulateIOErrorBenign(0);
35530       }
35531       *pp = p->pNext;
35532       sqlcipher3_free(p->aRegion);
35533       sqlcipher3_free(p);
35534     }else{
35535       pp = &p->pNext;
35536     }
35537   }
35538 }
35539
35540 /*
35541 ** Open the shared-memory area associated with database file pDbFd.
35542 **
35543 ** When opening a new shared-memory file, if no other instances of that
35544 ** file are currently open, in this process or in other processes, then
35545 ** the file must be truncated to zero length or have its header cleared.
35546 */
35547 static int winOpenSharedMemory(winFile *pDbFd){
35548   struct winShm *p;                  /* The connection to be opened */
35549   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
35550   int rc;                            /* Result code */
35551   struct winShmNode *pNew;           /* Newly allocated winShmNode */
35552   int nName;                         /* Size of zName in bytes */
35553
35554   assert( pDbFd->pShm==0 );    /* Not previously opened */
35555
35556   /* Allocate space for the new sqlcipher3_shm object.  Also speculatively
35557   ** allocate space for a new winShmNode and filename.
35558   */
35559   p = sqlcipher3_malloc( sizeof(*p) );
35560   if( p==0 ) return SQLCIPHER_NOMEM;
35561   memset(p, 0, sizeof(*p));
35562   nName = sqlcipher3Strlen30(pDbFd->zPath);
35563   pNew = sqlcipher3_malloc( sizeof(*pShmNode) + nName + 15 );
35564   if( pNew==0 ){
35565     sqlcipher3_free(p);
35566     return SQLCIPHER_NOMEM;
35567   }
35568   memset(pNew, 0, sizeof(*pNew));
35569   pNew->zFilename = (char*)&pNew[1];
35570   sqlcipher3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
35571   sqlcipher3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
35572
35573   /* Look to see if there is an existing winShmNode that can be used.
35574   ** If no matching winShmNode currently exists, create a new one.
35575   */
35576   winShmEnterMutex();
35577   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
35578     /* TBD need to come up with better match here.  Perhaps
35579     ** use FILE_ID_BOTH_DIR_INFO Structure.
35580     */
35581     if( sqlcipher3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
35582   }
35583   if( pShmNode ){
35584     sqlcipher3_free(pNew);
35585   }else{
35586     pShmNode = pNew;
35587     pNew = 0;
35588     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
35589     pShmNode->pNext = winShmNodeList;
35590     winShmNodeList = pShmNode;
35591
35592     pShmNode->mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_FAST);
35593     if( pShmNode->mutex==0 ){
35594       rc = SQLCIPHER_NOMEM;
35595       goto shm_open_err;
35596     }
35597
35598     rc = winOpen(pDbFd->pVfs,
35599                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
35600                  (sqlcipher3_file*)&pShmNode->hFile,  /* File handle here */
35601                  SQLCIPHER_OPEN_WAL | SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE, /* Mode flags */
35602                  0);
35603     if( SQLCIPHER_OK!=rc ){
35604       rc = SQLCIPHER_CANTOPEN_BKPT;
35605       goto shm_open_err;
35606     }
35607
35608     /* Check to see if another process is holding the dead-man switch.
35609     ** If not, truncate the file to zero length. 
35610     */
35611     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLCIPHER_OK ){
35612       rc = winTruncate((sqlcipher3_file *)&pShmNode->hFile, 0);
35613       if( rc!=SQLCIPHER_OK ){
35614         rc = winLogError(SQLCIPHER_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
35615       }
35616     }
35617     if( rc==SQLCIPHER_OK ){
35618       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35619       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
35620     }
35621     if( rc ) goto shm_open_err;
35622   }
35623
35624   /* Make the new connection a child of the winShmNode */
35625   p->pShmNode = pShmNode;
35626 #ifdef SQLCIPHER_DEBUG
35627   p->id = pShmNode->nextShmId++;
35628 #endif
35629   pShmNode->nRef++;
35630   pDbFd->pShm = p;
35631   winShmLeaveMutex();
35632
35633   /* The reference count on pShmNode has already been incremented under
35634   ** the cover of the winShmEnterMutex() mutex and the pointer from the
35635   ** new (struct winShm) object to the pShmNode has been set. All that is
35636   ** left to do is to link the new object into the linked list starting
35637   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
35638   ** mutex.
35639   */
35640   sqlcipher3_mutex_enter(pShmNode->mutex);
35641   p->pNext = pShmNode->pFirst;
35642   pShmNode->pFirst = p;
35643   sqlcipher3_mutex_leave(pShmNode->mutex);
35644   return SQLCIPHER_OK;
35645
35646   /* Jump here on any error */
35647 shm_open_err:
35648   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35649   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
35650   sqlcipher3_free(p);
35651   sqlcipher3_free(pNew);
35652   winShmLeaveMutex();
35653   return rc;
35654 }
35655
35656 /*
35657 ** Close a connection to shared-memory.  Delete the underlying 
35658 ** storage if deleteFlag is true.
35659 */
35660 static int winShmUnmap(
35661   sqlcipher3_file *fd,          /* Database holding shared memory */
35662   int deleteFlag             /* Delete after closing if true */
35663 ){
35664   winFile *pDbFd;       /* Database holding shared-memory */
35665   winShm *p;            /* The connection to be closed */
35666   winShmNode *pShmNode; /* The underlying shared-memory file */
35667   winShm **pp;          /* For looping over sibling connections */
35668
35669   pDbFd = (winFile*)fd;
35670   p = pDbFd->pShm;
35671   if( p==0 ) return SQLCIPHER_OK;
35672   pShmNode = p->pShmNode;
35673
35674   /* Remove connection p from the set of connections associated
35675   ** with pShmNode */
35676   sqlcipher3_mutex_enter(pShmNode->mutex);
35677   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35678   *pp = p->pNext;
35679
35680   /* Free the connection p */
35681   sqlcipher3_free(p);
35682   pDbFd->pShm = 0;
35683   sqlcipher3_mutex_leave(pShmNode->mutex);
35684
35685   /* If pShmNode->nRef has reached 0, then close the underlying
35686   ** shared-memory file, too */
35687   winShmEnterMutex();
35688   assert( pShmNode->nRef>0 );
35689   pShmNode->nRef--;
35690   if( pShmNode->nRef==0 ){
35691     winShmPurge(pDbFd->pVfs, deleteFlag);
35692   }
35693   winShmLeaveMutex();
35694
35695   return SQLCIPHER_OK;
35696 }
35697
35698 /*
35699 ** Change the lock state for a shared-memory segment.
35700 */
35701 static int winShmLock(
35702   sqlcipher3_file *fd,          /* Database file holding the shared memory */
35703   int ofst,                  /* First lock to acquire or release */
35704   int n,                     /* Number of locks to acquire or release */
35705   int flags                  /* What to do with the lock */
35706 ){
35707   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
35708   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
35709   winShm *pX;                           /* For looping over all siblings */
35710   winShmNode *pShmNode = p->pShmNode;
35711   int rc = SQLCIPHER_OK;                   /* Result code */
35712   u16 mask;                             /* Mask of locks to take or release */
35713
35714   assert( ofst>=0 && ofst+n<=SQLCIPHER_SHM_NLOCK );
35715   assert( n>=1 );
35716   assert( flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED)
35717        || flags==(SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE)
35718        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED)
35719        || flags==(SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE) );
35720   assert( n==1 || (flags & SQLCIPHER_SHM_EXCLUSIVE)!=0 );
35721
35722   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
35723   assert( n>1 || mask==(1<<ofst) );
35724   sqlcipher3_mutex_enter(pShmNode->mutex);
35725   if( flags & SQLCIPHER_SHM_UNLOCK ){
35726     u16 allMask = 0; /* Mask of locks held by siblings */
35727
35728     /* See if any siblings hold this same lock */
35729     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35730       if( pX==p ) continue;
35731       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
35732       allMask |= pX->sharedMask;
35733     }
35734
35735     /* Unlock the system-level locks */
35736     if( (mask & allMask)==0 ){
35737       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
35738     }else{
35739       rc = SQLCIPHER_OK;
35740     }
35741
35742     /* Undo the local locks */
35743     if( rc==SQLCIPHER_OK ){
35744       p->exclMask &= ~mask;
35745       p->sharedMask &= ~mask;
35746     } 
35747   }else if( flags & SQLCIPHER_SHM_SHARED ){
35748     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
35749
35750     /* Find out which shared locks are already held by sibling connections.
35751     ** If any sibling already holds an exclusive lock, go ahead and return
35752     ** SQLCIPHER_BUSY.
35753     */
35754     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35755       if( (pX->exclMask & mask)!=0 ){
35756         rc = SQLCIPHER_BUSY;
35757         break;
35758       }
35759       allShared |= pX->sharedMask;
35760     }
35761
35762     /* Get shared locks at the system level, if necessary */
35763     if( rc==SQLCIPHER_OK ){
35764       if( (allShared & mask)==0 ){
35765         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
35766       }else{
35767         rc = SQLCIPHER_OK;
35768       }
35769     }
35770
35771     /* Get the local shared locks */
35772     if( rc==SQLCIPHER_OK ){
35773       p->sharedMask |= mask;
35774     }
35775   }else{
35776     /* Make sure no sibling connections hold locks that will block this
35777     ** lock.  If any do, return SQLCIPHER_BUSY right away.
35778     */
35779     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35780       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35781         rc = SQLCIPHER_BUSY;
35782         break;
35783       }
35784     }
35785   
35786     /* Get the exclusive locks at the system level.  Then if successful
35787     ** also mark the local connection as being locked.
35788     */
35789     if( rc==SQLCIPHER_OK ){
35790       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
35791       if( rc==SQLCIPHER_OK ){
35792         assert( (p->sharedMask & mask)==0 );
35793         p->exclMask |= mask;
35794       }
35795     }
35796   }
35797   sqlcipher3_mutex_leave(pShmNode->mutex);
35798   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
35799            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
35800            rc ? "failed" : "ok"));
35801   return rc;
35802 }
35803
35804 /*
35805 ** Implement a memory barrier or memory fence on shared memory.  
35806 **
35807 ** All loads and stores begun before the barrier must complete before
35808 ** any load or store begun after the barrier.
35809 */
35810 static void winShmBarrier(
35811   sqlcipher3_file *fd          /* Database holding the shared memory */
35812 ){
35813   UNUSED_PARAMETER(fd);
35814   /* MemoryBarrier(); // does not work -- do not know why not */
35815   winShmEnterMutex();
35816   winShmLeaveMutex();
35817 }
35818
35819 /*
35820 ** This function is called to obtain a pointer to region iRegion of the 
35821 ** shared-memory associated with the database file fd. Shared-memory regions 
35822 ** are numbered starting from zero. Each shared-memory region is szRegion 
35823 ** bytes in size.
35824 **
35825 ** If an error occurs, an error code is returned and *pp is set to NULL.
35826 **
35827 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
35828 ** region has not been allocated (by any client, including one running in a
35829 ** separate process), then *pp is set to NULL and SQLCIPHER_OK returned. If 
35830 ** isWrite is non-zero and the requested shared-memory region has not yet 
35831 ** been allocated, it is allocated by this function.
35832 **
35833 ** If the shared-memory region has already been allocated or is allocated by
35834 ** this call as described above, then it is mapped into this processes 
35835 ** address space (if it is not already), *pp is set to point to the mapped 
35836 ** memory and SQLCIPHER_OK returned.
35837 */
35838 static int winShmMap(
35839   sqlcipher3_file *fd,               /* Handle open on database file */
35840   int iRegion,                    /* Region to retrieve */
35841   int szRegion,                   /* Size of regions */
35842   int isWrite,                    /* True to extend file if necessary */
35843   void volatile **pp              /* OUT: Mapped memory */
35844 ){
35845   winFile *pDbFd = (winFile*)fd;
35846   winShm *p = pDbFd->pShm;
35847   winShmNode *pShmNode;
35848   int rc = SQLCIPHER_OK;
35849
35850   if( !p ){
35851     rc = winOpenSharedMemory(pDbFd);
35852     if( rc!=SQLCIPHER_OK ) return rc;
35853     p = pDbFd->pShm;
35854   }
35855   pShmNode = p->pShmNode;
35856
35857   sqlcipher3_mutex_enter(pShmNode->mutex);
35858   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
35859
35860   if( pShmNode->nRegion<=iRegion ){
35861     struct ShmRegion *apNew;           /* New aRegion[] array */
35862     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
35863     sqlcipher3_int64 sz;                  /* Current size of wal-index file */
35864
35865     pShmNode->szRegion = szRegion;
35866
35867     /* The requested region is not mapped into this processes address space.
35868     ** Check to see if it has been allocated (i.e. if the wal-index file is
35869     ** large enough to contain the requested region).
35870     */
35871     rc = winFileSize((sqlcipher3_file *)&pShmNode->hFile, &sz);
35872     if( rc!=SQLCIPHER_OK ){
35873       rc = winLogError(SQLCIPHER_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
35874       goto shmpage_out;
35875     }
35876
35877     if( sz<nByte ){
35878       /* The requested memory region does not exist. If isWrite is set to
35879       ** zero, exit early. *pp will be set to NULL and SQLCIPHER_OK returned.
35880       **
35881       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
35882       ** the requested memory region.
35883       */
35884       if( !isWrite ) goto shmpage_out;
35885       rc = winTruncate((sqlcipher3_file *)&pShmNode->hFile, nByte);
35886       if( rc!=SQLCIPHER_OK ){
35887         rc = winLogError(SQLCIPHER_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
35888         goto shmpage_out;
35889       }
35890     }
35891
35892     /* Map the requested memory region into this processes address space. */
35893     apNew = (struct ShmRegion *)sqlcipher3_realloc(
35894         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
35895     );
35896     if( !apNew ){
35897       rc = SQLCIPHER_IOERR_NOMEM;
35898       goto shmpage_out;
35899     }
35900     pShmNode->aRegion = apNew;
35901
35902     while( pShmNode->nRegion<=iRegion ){
35903       HANDLE hMap;                /* file-mapping handle */
35904       void *pMap = 0;             /* Mapped memory region */
35905      
35906       hMap = CreateFileMapping(pShmNode->hFile.h, 
35907           NULL, PAGE_READWRITE, 0, nByte, NULL
35908       );
35909       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
35910                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
35911                hMap ? "ok" : "failed"));
35912       if( hMap ){
35913         int iOffset = pShmNode->nRegion*szRegion;
35914         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35915         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35916             0, iOffset - iOffsetShift, szRegion + iOffsetShift
35917         );
35918         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
35919                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
35920                  pMap ? "ok" : "failed"));
35921       }
35922       if( !pMap ){
35923         pShmNode->lastErrno = GetLastError();
35924         rc = winLogError(SQLCIPHER_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
35925         if( hMap ) CloseHandle(hMap);
35926         goto shmpage_out;
35927       }
35928
35929       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
35930       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
35931       pShmNode->nRegion++;
35932     }
35933   }
35934
35935 shmpage_out:
35936   if( pShmNode->nRegion>iRegion ){
35937     int iOffset = iRegion*szRegion;
35938     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35939     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
35940     *pp = (void *)&p[iOffsetShift];
35941   }else{
35942     *pp = 0;
35943   }
35944   sqlcipher3_mutex_leave(pShmNode->mutex);
35945   return rc;
35946 }
35947
35948 #else
35949 # define winShmMap     0
35950 # define winShmLock    0
35951 # define winShmBarrier 0
35952 # define winShmUnmap   0
35953 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
35954
35955 /*
35956 ** Here ends the implementation of all sqlcipher3_file methods.
35957 **
35958 ********************** End sqlcipher3_file Methods *******************************
35959 ******************************************************************************/
35960
35961 /*
35962 ** This vector defines all the methods that can operate on an
35963 ** sqlcipher3_file for win32.
35964 */
35965 static const sqlcipher3_io_methods winIoMethod = {
35966   2,                              /* iVersion */
35967   winClose,                       /* xClose */
35968   winRead,                        /* xRead */
35969   winWrite,                       /* xWrite */
35970   winTruncate,                    /* xTruncate */
35971   winSync,                        /* xSync */
35972   winFileSize,                    /* xFileSize */
35973   winLock,                        /* xLock */
35974   winUnlock,                      /* xUnlock */
35975   winCheckReservedLock,           /* xCheckReservedLock */
35976   winFileControl,                 /* xFileControl */
35977   winSectorSize,                  /* xSectorSize */
35978   winDeviceCharacteristics,       /* xDeviceCharacteristics */
35979   winShmMap,                      /* xShmMap */
35980   winShmLock,                     /* xShmLock */
35981   winShmBarrier,                  /* xShmBarrier */
35982   winShmUnmap                     /* xShmUnmap */
35983 };
35984
35985 /****************************************************************************
35986 **************************** sqlcipher3_vfs methods ****************************
35987 **
35988 ** This division contains the implementation of methods on the
35989 ** sqlcipher3_vfs object.
35990 */
35991
35992 /*
35993 ** Convert a UTF-8 filename into whatever form the underlying
35994 ** operating system wants filenames in.  Space to hold the result
35995 ** is obtained from malloc and must be freed by the calling
35996 ** function.
35997 */
35998 static void *convertUtf8Filename(const char *zFilename){
35999   void *zConverted = 0;
36000   if( isNT() ){
36001     zConverted = utf8ToUnicode(zFilename);
36002 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36003 */
36004 #if SQLCIPHER_OS_WINCE==0
36005   }else{
36006     zConverted = sqlcipher3_win32_utf8_to_mbcs(zFilename);
36007 #endif
36008   }
36009   /* caller will handle out of memory */
36010   return zConverted;
36011 }
36012
36013 /*
36014 ** Create a temporary file name in zBuf.  zBuf must be big enough to
36015 ** hold at pVfs->mxPathname characters.
36016 */
36017 static int getTempname(int nBuf, char *zBuf){
36018   static char zChars[] =
36019     "abcdefghijklmnopqrstuvwxyz"
36020     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
36021     "0123456789";
36022   size_t i, j;
36023   char zTempPath[MAX_PATH+1];
36024
36025   /* It's odd to simulate an io-error here, but really this is just
36026   ** using the io-error infrastructure to test that SQLite handles this
36027   ** function failing. 
36028   */
36029   SimulateIOError( return SQLCIPHER_IOERR );
36030
36031   if( sqlcipher3_temp_directory ){
36032     sqlcipher3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlcipher3_temp_directory);
36033   }else if( isNT() ){
36034     char *zMulti;
36035     WCHAR zWidePath[MAX_PATH];
36036     GetTempPathW(MAX_PATH-30, zWidePath);
36037     zMulti = unicodeToUtf8(zWidePath);
36038     if( zMulti ){
36039       sqlcipher3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
36040       free(zMulti);
36041     }else{
36042       return SQLCIPHER_NOMEM;
36043     }
36044 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36045 ** Since the ASCII version of these Windows API do not exist for WINCE,
36046 ** it's important to not reference them for WINCE builds.
36047 */
36048 #if SQLCIPHER_OS_WINCE==0
36049   }else{
36050     char *zUtf8;
36051     char zMbcsPath[MAX_PATH];
36052     GetTempPathA(MAX_PATH-30, zMbcsPath);
36053     zUtf8 = sqlcipher3_win32_mbcs_to_utf8(zMbcsPath);
36054     if( zUtf8 ){
36055       sqlcipher3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
36056       free(zUtf8);
36057     }else{
36058       return SQLCIPHER_NOMEM;
36059     }
36060 #endif
36061   }
36062
36063   /* Check that the output buffer is large enough for the temporary file 
36064   ** name. If it is not, return SQLCIPHER_ERROR.
36065   */
36066   if( (sqlcipher3Strlen30(zTempPath) + sqlcipher3Strlen30(SQLCIPHER_TEMP_FILE_PREFIX) + 17) >= nBuf ){
36067     return SQLCIPHER_ERROR;
36068   }
36069
36070   for(i=sqlcipher3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
36071   zTempPath[i] = 0;
36072
36073   sqlcipher3_snprintf(nBuf-17, zBuf,
36074                    "%s\\"SQLCIPHER_TEMP_FILE_PREFIX, zTempPath);
36075   j = sqlcipher3Strlen30(zBuf);
36076   sqlcipher3_randomness(15, &zBuf[j]);
36077   for(i=0; i<15; i++, j++){
36078     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
36079   }
36080   zBuf[j] = 0;
36081
36082   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
36083   return SQLCIPHER_OK; 
36084 }
36085
36086 /*
36087 ** Open a file.
36088 */
36089 static int winOpen(
36090   sqlcipher3_vfs *pVfs,        /* Not used */
36091   const char *zName,        /* Name of the file (UTF-8) */
36092   sqlcipher3_file *id,         /* Write the SQLite file handle here */
36093   int flags,                /* Open mode flags */
36094   int *pOutFlags            /* Status return flags */
36095 ){
36096   HANDLE h;
36097   DWORD dwDesiredAccess;
36098   DWORD dwShareMode;
36099   DWORD dwCreationDisposition;
36100   DWORD dwFlagsAndAttributes = 0;
36101 #if SQLCIPHER_OS_WINCE
36102   int isTemp = 0;
36103 #endif
36104   winFile *pFile = (winFile*)id;
36105   void *zConverted;              /* Filename in OS encoding */
36106   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
36107   int cnt = 0;
36108
36109   /* If argument zPath is a NULL pointer, this function is required to open
36110   ** a temporary file. Use this buffer to store the file name in.
36111   */
36112   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
36113
36114   int rc = SQLCIPHER_OK;            /* Function Return Code */
36115 #if !defined(NDEBUG) || SQLCIPHER_OS_WINCE
36116   int eType = flags&0xFFFFFF00;  /* Type of file to open */
36117 #endif
36118
36119   int isExclusive  = (flags & SQLCIPHER_OPEN_EXCLUSIVE);
36120   int isDelete     = (flags & SQLCIPHER_OPEN_DELETEONCLOSE);
36121   int isCreate     = (flags & SQLCIPHER_OPEN_CREATE);
36122 #ifndef NDEBUG
36123   int isReadonly   = (flags & SQLCIPHER_OPEN_READONLY);
36124 #endif
36125   int isReadWrite  = (flags & SQLCIPHER_OPEN_READWRITE);
36126
36127 #ifndef NDEBUG
36128   int isOpenJournal = (isCreate && (
36129         eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
36130      || eType==SQLCIPHER_OPEN_MAIN_JOURNAL 
36131      || eType==SQLCIPHER_OPEN_WAL
36132   ));
36133 #endif
36134
36135   /* Check the following statements are true: 
36136   **
36137   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
36138   **   (b) if CREATE is set, then READWRITE must also be set, and
36139   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
36140   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
36141   */
36142   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
36143   assert(isCreate==0 || isReadWrite);
36144   assert(isExclusive==0 || isCreate);
36145   assert(isDelete==0 || isCreate);
36146
36147   /* The main DB, main journal, WAL file and master journal are never 
36148   ** automatically deleted. Nor are they ever temporary files.  */
36149   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_DB );
36150   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MAIN_JOURNAL );
36151   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_MASTER_JOURNAL );
36152   assert( (!isDelete && zName) || eType!=SQLCIPHER_OPEN_WAL );
36153
36154   /* Assert that the upper layer has set one of the "file-type" flags. */
36155   assert( eType==SQLCIPHER_OPEN_MAIN_DB      || eType==SQLCIPHER_OPEN_TEMP_DB 
36156        || eType==SQLCIPHER_OPEN_MAIN_JOURNAL || eType==SQLCIPHER_OPEN_TEMP_JOURNAL 
36157        || eType==SQLCIPHER_OPEN_SUBJOURNAL   || eType==SQLCIPHER_OPEN_MASTER_JOURNAL 
36158        || eType==SQLCIPHER_OPEN_TRANSIENT_DB || eType==SQLCIPHER_OPEN_WAL
36159   );
36160
36161   assert( id!=0 );
36162   UNUSED_PARAMETER(pVfs);
36163
36164   pFile->h = INVALID_HANDLE_VALUE;
36165
36166   /* If the second argument to this function is NULL, generate a 
36167   ** temporary file name to use 
36168   */
36169   if( !zUtf8Name ){
36170     assert(isDelete && !isOpenJournal);
36171     rc = getTempname(MAX_PATH+1, zTmpname);
36172     if( rc!=SQLCIPHER_OK ){
36173       return rc;
36174     }
36175     zUtf8Name = zTmpname;
36176   }
36177
36178   /* Convert the filename to the system encoding. */
36179   zConverted = convertUtf8Filename(zUtf8Name);
36180   if( zConverted==0 ){
36181     return SQLCIPHER_NOMEM;
36182   }
36183
36184   if( isReadWrite ){
36185     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
36186   }else{
36187     dwDesiredAccess = GENERIC_READ;
36188   }
36189
36190   /* SQLCIPHER_OPEN_EXCLUSIVE is used to make sure that a new file is 
36191   ** created. SQLite doesn't use it to indicate "exclusive access" 
36192   ** as it is usually understood.
36193   */
36194   if( isExclusive ){
36195     /* Creates a new file, only if it does not already exist. */
36196     /* If the file exists, it fails. */
36197     dwCreationDisposition = CREATE_NEW;
36198   }else if( isCreate ){
36199     /* Open existing file, or create if it doesn't exist */
36200     dwCreationDisposition = OPEN_ALWAYS;
36201   }else{
36202     /* Opens a file, only if it exists. */
36203     dwCreationDisposition = OPEN_EXISTING;
36204   }
36205
36206   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
36207
36208   if( isDelete ){
36209 #if SQLCIPHER_OS_WINCE
36210     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
36211     isTemp = 1;
36212 #else
36213     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
36214                                | FILE_ATTRIBUTE_HIDDEN
36215                                | FILE_FLAG_DELETE_ON_CLOSE;
36216 #endif
36217   }else{
36218     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
36219   }
36220   /* Reports from the internet are that performance is always
36221   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
36222 #if SQLCIPHER_OS_WINCE
36223   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
36224 #endif
36225
36226   if( isNT() ){
36227     while( (h = CreateFileW((WCHAR*)zConverted,
36228                             dwDesiredAccess,
36229                             dwShareMode, NULL,
36230                             dwCreationDisposition,
36231                             dwFlagsAndAttributes,
36232                             NULL))==INVALID_HANDLE_VALUE &&
36233                             retryIoerr(&cnt) ){}
36234 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36235 ** Since the ASCII version of these Windows API do not exist for WINCE,
36236 ** it's important to not reference them for WINCE builds.
36237 */
36238 #if SQLCIPHER_OS_WINCE==0
36239   }else{
36240     while( (h = CreateFileA((char*)zConverted,
36241                             dwDesiredAccess,
36242                             dwShareMode, NULL,
36243                             dwCreationDisposition,
36244                             dwFlagsAndAttributes,
36245                             NULL))==INVALID_HANDLE_VALUE &&
36246                             retryIoerr(&cnt) ){}
36247 #endif
36248   }
36249
36250   logIoerr(cnt);
36251
36252   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
36253            h, zName, dwDesiredAccess, 
36254            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
36255
36256   if( h==INVALID_HANDLE_VALUE ){
36257     pFile->lastErrno = GetLastError();
36258     winLogError(SQLCIPHER_CANTOPEN, "winOpen", zUtf8Name);
36259     free(zConverted);
36260     if( isReadWrite && !isExclusive ){
36261       return winOpen(pVfs, zName, id, 
36262              ((flags|SQLCIPHER_OPEN_READONLY)&~(SQLCIPHER_OPEN_CREATE|SQLCIPHER_OPEN_READWRITE)), pOutFlags);
36263     }else{
36264       return SQLCIPHER_CANTOPEN_BKPT;
36265     }
36266   }
36267
36268   if( pOutFlags ){
36269     if( isReadWrite ){
36270       *pOutFlags = SQLCIPHER_OPEN_READWRITE;
36271     }else{
36272       *pOutFlags = SQLCIPHER_OPEN_READONLY;
36273     }
36274   }
36275
36276   memset(pFile, 0, sizeof(*pFile));
36277   pFile->pMethod = &winIoMethod;
36278   pFile->h = h;
36279   pFile->lastErrno = NO_ERROR;
36280   pFile->pVfs = pVfs;
36281   pFile->pShm = 0;
36282   pFile->zPath = zName;
36283   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
36284
36285 #if SQLCIPHER_OS_WINCE
36286   if( isReadWrite && eType==SQLCIPHER_OPEN_MAIN_DB
36287        && !winceCreateLock(zName, pFile)
36288   ){
36289     CloseHandle(h);
36290     free(zConverted);
36291     return SQLCIPHER_CANTOPEN_BKPT;
36292   }
36293   if( isTemp ){
36294     pFile->zDeleteOnClose = zConverted;
36295   }else
36296 #endif
36297   {
36298     free(zConverted);
36299   }
36300
36301   OpenCounter(+1);
36302   return rc;
36303 }
36304
36305 /*
36306 ** Delete the named file.
36307 **
36308 ** Note that windows does not allow a file to be deleted if some other
36309 ** process has it open.  Sometimes a virus scanner or indexing program
36310 ** will open a journal file shortly after it is created in order to do
36311 ** whatever it does.  While this other process is holding the
36312 ** file open, we will be unable to delete it.  To work around this
36313 ** problem, we delay 100 milliseconds and try to delete again.  Up
36314 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
36315 ** up and returning an error.
36316 */
36317 static int winDelete(
36318   sqlcipher3_vfs *pVfs,          /* Not used on win32 */
36319   const char *zFilename,      /* Name of file to delete */
36320   int syncDir                 /* Not used on win32 */
36321 ){
36322   int cnt = 0;
36323   int rc;
36324   void *zConverted;
36325   UNUSED_PARAMETER(pVfs);
36326   UNUSED_PARAMETER(syncDir);
36327
36328   SimulateIOError(return SQLCIPHER_IOERR_DELETE);
36329   zConverted = convertUtf8Filename(zFilename);
36330   if( zConverted==0 ){
36331     return SQLCIPHER_NOMEM;
36332   }
36333   if( isNT() ){
36334     rc = 1;
36335     while( GetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
36336            (rc = DeleteFileW(zConverted))==0 && retryIoerr(&cnt) ){}
36337     rc = rc ? SQLCIPHER_OK : SQLCIPHER_ERROR;
36338 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36339 ** Since the ASCII version of these Windows API do not exist for WINCE,
36340 ** it's important to not reference them for WINCE builds.
36341 */
36342 #if SQLCIPHER_OS_WINCE==0
36343   }else{
36344     rc = 1;
36345     while( GetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
36346            (rc = DeleteFileA(zConverted))==0 && retryIoerr(&cnt) ){}
36347     rc = rc ? SQLCIPHER_OK : SQLCIPHER_ERROR;
36348 #endif
36349   }
36350   if( rc ){
36351     rc = winLogError(SQLCIPHER_IOERR_DELETE, "winDelete", zFilename);
36352   }else{
36353     logIoerr(cnt);
36354   }
36355   free(zConverted);
36356   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
36357   return rc;
36358 }
36359
36360 /*
36361 ** Check the existance and status of a file.
36362 */
36363 static int winAccess(
36364   sqlcipher3_vfs *pVfs,         /* Not used on win32 */
36365   const char *zFilename,     /* Name of file to check */
36366   int flags,                 /* Type of test to make on this file */
36367   int *pResOut               /* OUT: Result */
36368 ){
36369   DWORD attr;
36370   int rc = 0;
36371   void *zConverted;
36372   UNUSED_PARAMETER(pVfs);
36373
36374   SimulateIOError( return SQLCIPHER_IOERR_ACCESS; );
36375   zConverted = convertUtf8Filename(zFilename);
36376   if( zConverted==0 ){
36377     return SQLCIPHER_NOMEM;
36378   }
36379   if( isNT() ){
36380     int cnt = 0;
36381     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36382     memset(&sAttrData, 0, sizeof(sAttrData));
36383     while( !(rc = GetFileAttributesExW((WCHAR*)zConverted,
36384                              GetFileExInfoStandard, 
36385                              &sAttrData)) && retryIoerr(&cnt) ){}
36386     if( rc ){
36387       /* For an SQLCIPHER_ACCESS_EXISTS query, treat a zero-length file
36388       ** as if it does not exist.
36389       */
36390       if(    flags==SQLCIPHER_ACCESS_EXISTS
36391           && sAttrData.nFileSizeHigh==0 
36392           && sAttrData.nFileSizeLow==0 ){
36393         attr = INVALID_FILE_ATTRIBUTES;
36394       }else{
36395         attr = sAttrData.dwFileAttributes;
36396       }
36397     }else{
36398       logIoerr(cnt);
36399       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
36400         winLogError(SQLCIPHER_IOERR_ACCESS, "winAccess", zFilename);
36401         free(zConverted);
36402         return SQLCIPHER_IOERR_ACCESS;
36403       }else{
36404         attr = INVALID_FILE_ATTRIBUTES;
36405       }
36406     }
36407 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36408 ** Since the ASCII version of these Windows API do not exist for WINCE,
36409 ** it's important to not reference them for WINCE builds.
36410 */
36411 #if SQLCIPHER_OS_WINCE==0
36412   }else{
36413     attr = GetFileAttributesA((char*)zConverted);
36414 #endif
36415   }
36416   free(zConverted);
36417   switch( flags ){
36418     case SQLCIPHER_ACCESS_READ:
36419     case SQLCIPHER_ACCESS_EXISTS:
36420       rc = attr!=INVALID_FILE_ATTRIBUTES;
36421       break;
36422     case SQLCIPHER_ACCESS_READWRITE:
36423       rc = attr!=INVALID_FILE_ATTRIBUTES &&
36424              (attr & FILE_ATTRIBUTE_READONLY)==0;
36425       break;
36426     default:
36427       assert(!"Invalid flags argument");
36428   }
36429   *pResOut = rc;
36430   return SQLCIPHER_OK;
36431 }
36432
36433
36434 /*
36435 ** Turn a relative pathname into a full pathname.  Write the full
36436 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
36437 ** bytes in size.
36438 */
36439 static int winFullPathname(
36440   sqlcipher3_vfs *pVfs,            /* Pointer to vfs object */
36441   const char *zRelative,        /* Possibly relative input path */
36442   int nFull,                    /* Size of output buffer in bytes */
36443   char *zFull                   /* Output buffer */
36444 ){
36445   
36446 #if defined(__CYGWIN__)
36447   SimulateIOError( return SQLCIPHER_ERROR );
36448   UNUSED_PARAMETER(nFull);
36449   cygwin_conv_to_full_win32_path(zRelative, zFull);
36450   return SQLCIPHER_OK;
36451 #endif
36452
36453 #if SQLCIPHER_OS_WINCE
36454   SimulateIOError( return SQLCIPHER_ERROR );
36455   UNUSED_PARAMETER(nFull);
36456   /* WinCE has no concept of a relative pathname, or so I am told. */
36457   sqlcipher3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
36458   return SQLCIPHER_OK;
36459 #endif
36460
36461 #if !SQLCIPHER_OS_WINCE && !defined(__CYGWIN__)
36462   int nByte;
36463   void *zConverted;
36464   char *zOut;
36465
36466   /* If this path name begins with "/X:", where "X" is any alphabetic
36467   ** character, discard the initial "/" from the pathname.
36468   */
36469   if( zRelative[0]=='/' && sqlcipher3Isalpha(zRelative[1]) && zRelative[2]==':' ){
36470     zRelative++;
36471   }
36472
36473   /* It's odd to simulate an io-error here, but really this is just
36474   ** using the io-error infrastructure to test that SQLite handles this
36475   ** function failing. This function could fail if, for example, the
36476   ** current working directory has been unlinked.
36477   */
36478   SimulateIOError( return SQLCIPHER_ERROR );
36479   UNUSED_PARAMETER(nFull);
36480   zConverted = convertUtf8Filename(zRelative);
36481   if( isNT() ){
36482     WCHAR *zTemp;
36483     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
36484     zTemp = malloc( nByte*sizeof(zTemp[0]) );
36485     if( zTemp==0 ){
36486       free(zConverted);
36487       return SQLCIPHER_NOMEM;
36488     }
36489     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
36490     free(zConverted);
36491     zOut = unicodeToUtf8(zTemp);
36492     free(zTemp);
36493 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36494 ** Since the ASCII version of these Windows API do not exist for WINCE,
36495 ** it's important to not reference them for WINCE builds.
36496 */
36497 #if SQLCIPHER_OS_WINCE==0
36498   }else{
36499     char *zTemp;
36500     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
36501     zTemp = malloc( nByte*sizeof(zTemp[0]) );
36502     if( zTemp==0 ){
36503       free(zConverted);
36504       return SQLCIPHER_NOMEM;
36505     }
36506     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36507     free(zConverted);
36508     zOut = sqlcipher3_win32_mbcs_to_utf8(zTemp);
36509     free(zTemp);
36510 #endif
36511   }
36512   if( zOut ){
36513     sqlcipher3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
36514     free(zOut);
36515     return SQLCIPHER_OK;
36516   }else{
36517     return SQLCIPHER_NOMEM;
36518   }
36519 #endif
36520 }
36521
36522 /*
36523 ** Get the sector size of the device used to store
36524 ** file.
36525 */
36526 static int getSectorSize(
36527     sqlcipher3_vfs *pVfs,
36528     const char *zRelative     /* UTF-8 file name */
36529 ){
36530   DWORD bytesPerSector = SQLCIPHER_DEFAULT_SECTOR_SIZE;
36531   /* GetDiskFreeSpace is not supported under WINCE */
36532 #if SQLCIPHER_OS_WINCE
36533   UNUSED_PARAMETER(pVfs);
36534   UNUSED_PARAMETER(zRelative);
36535 #else
36536   char zFullpath[MAX_PATH+1];
36537   int rc;
36538   DWORD dwRet = 0;
36539   DWORD dwDummy;
36540
36541   /*
36542   ** We need to get the full path name of the file
36543   ** to get the drive letter to look up the sector
36544   ** size.
36545   */
36546   SimulateIOErrorBenign(1);
36547   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
36548   SimulateIOErrorBenign(0);
36549   if( rc == SQLCIPHER_OK )
36550   {
36551     void *zConverted = convertUtf8Filename(zFullpath);
36552     if( zConverted ){
36553       if( isNT() ){
36554         /* trim path to just drive reference */
36555         WCHAR *p = zConverted;
36556         for(;*p;p++){
36557           if( *p == '\\' ){
36558             *p = '\0';
36559             break;
36560           }
36561         }
36562         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
36563                                   &dwDummy,
36564                                   &bytesPerSector,
36565                                   &dwDummy,
36566                                   &dwDummy);
36567       }else{
36568         /* trim path to just drive reference */
36569         char *p = (char *)zConverted;
36570         for(;*p;p++){
36571           if( *p == '\\' ){
36572             *p = '\0';
36573             break;
36574           }
36575         }
36576         dwRet = GetDiskFreeSpaceA((char*)zConverted,
36577                                   &dwDummy,
36578                                   &bytesPerSector,
36579                                   &dwDummy,
36580                                   &dwDummy);
36581       }
36582       free(zConverted);
36583     }
36584     if( !dwRet ){
36585       bytesPerSector = SQLCIPHER_DEFAULT_SECTOR_SIZE;
36586     }
36587   }
36588 #endif
36589   return (int) bytesPerSector; 
36590 }
36591
36592 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
36593 /*
36594 ** Interfaces for opening a shared library, finding entry points
36595 ** within the shared library, and closing the shared library.
36596 */
36597 /*
36598 ** Interfaces for opening a shared library, finding entry points
36599 ** within the shared library, and closing the shared library.
36600 */
36601 static void *winDlOpen(sqlcipher3_vfs *pVfs, const char *zFilename){
36602   HANDLE h;
36603   void *zConverted = convertUtf8Filename(zFilename);
36604   UNUSED_PARAMETER(pVfs);
36605   if( zConverted==0 ){
36606     return 0;
36607   }
36608   if( isNT() ){
36609     h = LoadLibraryW((WCHAR*)zConverted);
36610 /* isNT() is 1 if SQLCIPHER_OS_WINCE==1, so this else is never executed. 
36611 ** Since the ASCII version of these Windows API do not exist for WINCE,
36612 ** it's important to not reference them for WINCE builds.
36613 */
36614 #if SQLCIPHER_OS_WINCE==0
36615   }else{
36616     h = LoadLibraryA((char*)zConverted);
36617 #endif
36618   }
36619   free(zConverted);
36620   return (void*)h;
36621 }
36622 static void winDlError(sqlcipher3_vfs *pVfs, int nBuf, char *zBufOut){
36623   UNUSED_PARAMETER(pVfs);
36624   getLastErrorMsg(nBuf, zBufOut);
36625 }
36626 static void (*winDlSym(sqlcipher3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
36627   UNUSED_PARAMETER(pVfs);
36628 #if SQLCIPHER_OS_WINCE
36629   /* The GetProcAddressA() routine is only available on wince. */
36630   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
36631 #else
36632   /* All other windows platforms expect GetProcAddress() to take
36633   ** an Ansi string regardless of the _UNICODE setting */
36634   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
36635 #endif
36636 }
36637 static void winDlClose(sqlcipher3_vfs *pVfs, void *pHandle){
36638   UNUSED_PARAMETER(pVfs);
36639   FreeLibrary((HANDLE)pHandle);
36640 }
36641 #else /* if SQLCIPHER_OMIT_LOAD_EXTENSION is defined: */
36642   #define winDlOpen  0
36643   #define winDlError 0
36644   #define winDlSym   0
36645   #define winDlClose 0
36646 #endif
36647
36648
36649 /*
36650 ** Write up to nBuf bytes of randomness into zBuf.
36651 */
36652 static int winRandomness(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
36653   int n = 0;
36654   UNUSED_PARAMETER(pVfs);
36655 #if defined(SQLCIPHER_TEST)
36656   n = nBuf;
36657   memset(zBuf, 0, nBuf);
36658 #else
36659   if( sizeof(SYSTEMTIME)<=nBuf-n ){
36660     SYSTEMTIME x;
36661     GetSystemTime(&x);
36662     memcpy(&zBuf[n], &x, sizeof(x));
36663     n += sizeof(x);
36664   }
36665   if( sizeof(DWORD)<=nBuf-n ){
36666     DWORD pid = GetCurrentProcessId();
36667     memcpy(&zBuf[n], &pid, sizeof(pid));
36668     n += sizeof(pid);
36669   }
36670   if( sizeof(DWORD)<=nBuf-n ){
36671     DWORD cnt = GetTickCount();
36672     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36673     n += sizeof(cnt);
36674   }
36675   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36676     LARGE_INTEGER i;
36677     QueryPerformanceCounter(&i);
36678     memcpy(&zBuf[n], &i, sizeof(i));
36679     n += sizeof(i);
36680   }
36681 #endif
36682   return n;
36683 }
36684
36685
36686 /*
36687 ** Sleep for a little while.  Return the amount of time slept.
36688 */
36689 static int winSleep(sqlcipher3_vfs *pVfs, int microsec){
36690   Sleep((microsec+999)/1000);
36691   UNUSED_PARAMETER(pVfs);
36692   return ((microsec+999)/1000)*1000;
36693 }
36694
36695 /*
36696 ** The following variable, if set to a non-zero value, is interpreted as
36697 ** the number of seconds since 1970 and is used to set the result of
36698 ** sqlcipher3OsCurrentTime() during testing.
36699 */
36700 #ifdef SQLCIPHER_TEST
36701 SQLCIPHER_API int sqlcipher3_current_time = 0;  /* Fake system time in seconds since 1970. */
36702 #endif
36703
36704 /*
36705 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
36706 ** the current time and date as a Julian Day number times 86_400_000.  In
36707 ** other words, write into *piNow the number of milliseconds since the Julian
36708 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36709 ** proleptic Gregorian calendar.
36710 **
36711 ** On success, return SQLCIPHER_OK.  Return SQLCIPHER_ERROR if the time and date 
36712 ** cannot be found.
36713 */
36714 static int winCurrentTimeInt64(sqlcipher3_vfs *pVfs, sqlcipher3_int64 *piNow){
36715   /* FILETIME structure is a 64-bit value representing the number of 
36716      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
36717   */
36718   FILETIME ft;
36719   static const sqlcipher3_int64 winFiletimeEpoch = 23058135*(sqlcipher3_int64)8640000;
36720 #ifdef SQLCIPHER_TEST
36721   static const sqlcipher3_int64 unixEpoch = 24405875*(sqlcipher3_int64)8640000;
36722 #endif
36723   /* 2^32 - to avoid use of LL and warnings in gcc */
36724   static const sqlcipher3_int64 max32BitValue = 
36725       (sqlcipher3_int64)2000000000 + (sqlcipher3_int64)2000000000 + (sqlcipher3_int64)294967296;
36726
36727 #if SQLCIPHER_OS_WINCE
36728   SYSTEMTIME time;
36729   GetSystemTime(&time);
36730   /* if SystemTimeToFileTime() fails, it returns zero. */
36731   if (!SystemTimeToFileTime(&time,&ft)){
36732     return SQLCIPHER_ERROR;
36733   }
36734 #else
36735   GetSystemTimeAsFileTime( &ft );
36736 #endif
36737
36738   *piNow = winFiletimeEpoch +
36739             ((((sqlcipher3_int64)ft.dwHighDateTime)*max32BitValue) + 
36740                (sqlcipher3_int64)ft.dwLowDateTime)/(sqlcipher3_int64)10000;
36741
36742 #ifdef SQLCIPHER_TEST
36743   if( sqlcipher3_current_time ){
36744     *piNow = 1000*(sqlcipher3_int64)sqlcipher3_current_time + unixEpoch;
36745   }
36746 #endif
36747   UNUSED_PARAMETER(pVfs);
36748   return SQLCIPHER_OK;
36749 }
36750
36751 /*
36752 ** Find the current time (in Universal Coordinated Time).  Write the
36753 ** current time and date as a Julian Day number into *prNow and
36754 ** return 0.  Return 1 if the time and date cannot be found.
36755 */
36756 static int winCurrentTime(sqlcipher3_vfs *pVfs, double *prNow){
36757   int rc;
36758   sqlcipher3_int64 i;
36759   rc = winCurrentTimeInt64(pVfs, &i);
36760   if( !rc ){
36761     *prNow = i/86400000.0;
36762   }
36763   return rc;
36764 }
36765
36766 /*
36767 ** The idea is that this function works like a combination of
36768 ** GetLastError() and FormatMessage() on windows (or errno and
36769 ** strerror_r() on unix). After an error is returned by an OS
36770 ** function, SQLite calls this function with zBuf pointing to
36771 ** a buffer of nBuf bytes. The OS layer should populate the
36772 ** buffer with a nul-terminated UTF-8 encoded error message
36773 ** describing the last IO error to have occurred within the calling
36774 ** thread.
36775 **
36776 ** If the error message is too large for the supplied buffer,
36777 ** it should be truncated. The return value of xGetLastError
36778 ** is zero if the error message fits in the buffer, or non-zero
36779 ** otherwise (if the message was truncated). If non-zero is returned,
36780 ** then it is not necessary to include the nul-terminator character
36781 ** in the output buffer.
36782 **
36783 ** Not supplying an error message will have no adverse effect
36784 ** on SQLite. It is fine to have an implementation that never
36785 ** returns an error message:
36786 **
36787 **   int xGetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
36788 **     assert(zBuf[0]=='\0');
36789 **     return 0;
36790 **   }
36791 **
36792 ** However if an error message is supplied, it will be incorporated
36793 ** by sqlcipher into the error message available to the user using
36794 ** sqlcipher3_errmsg(), possibly making IO errors easier to debug.
36795 */
36796 static int winGetLastError(sqlcipher3_vfs *pVfs, int nBuf, char *zBuf){
36797   UNUSED_PARAMETER(pVfs);
36798   return getLastErrorMsg(nBuf, zBuf);
36799 }
36800
36801
36802
36803 /*
36804 ** Initialize and deinitialize the operating system interface.
36805 */
36806 SQLCIPHER_API int sqlcipher3_os_init(void){
36807   static sqlcipher3_vfs winVfs = {
36808     3,                   /* iVersion */
36809     sizeof(winFile),     /* szOsFile */
36810     MAX_PATH,            /* mxPathname */
36811     0,                   /* pNext */
36812     "win32",             /* zName */
36813     0,                   /* pAppData */
36814     winOpen,             /* xOpen */
36815     winDelete,           /* xDelete */
36816     winAccess,           /* xAccess */
36817     winFullPathname,     /* xFullPathname */
36818     winDlOpen,           /* xDlOpen */
36819     winDlError,          /* xDlError */
36820     winDlSym,            /* xDlSym */
36821     winDlClose,          /* xDlClose */
36822     winRandomness,       /* xRandomness */
36823     winSleep,            /* xSleep */
36824     winCurrentTime,      /* xCurrentTime */
36825     winGetLastError,     /* xGetLastError */
36826     winCurrentTimeInt64, /* xCurrentTimeInt64 */
36827     0,                   /* xSetSystemCall */
36828     0,                   /* xGetSystemCall */
36829     0,                   /* xNextSystemCall */
36830   };
36831
36832 #ifndef SQLCIPHER_OMIT_WAL
36833   /* get memory map allocation granularity */
36834   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
36835   GetSystemInfo(&winSysInfo);
36836   assert(winSysInfo.dwAllocationGranularity > 0);
36837 #endif
36838
36839   sqlcipher3_vfs_register(&winVfs, 1);
36840   return SQLCIPHER_OK; 
36841 }
36842 SQLCIPHER_API int sqlcipher3_os_end(void){ 
36843   return SQLCIPHER_OK;
36844 }
36845
36846 #endif /* SQLCIPHER_OS_WIN */
36847
36848 /************** End of os_win.c **********************************************/
36849 /************** Begin file bitvec.c ******************************************/
36850 /*
36851 ** 2008 February 16
36852 **
36853 ** The author disclaims copyright to this source code.  In place of
36854 ** a legal notice, here is a blessing:
36855 **
36856 **    May you do good and not evil.
36857 **    May you find forgiveness for yourself and forgive others.
36858 **    May you share freely, never taking more than you give.
36859 **
36860 *************************************************************************
36861 ** This file implements an object that represents a fixed-length
36862 ** bitmap.  Bits are numbered starting with 1.
36863 **
36864 ** A bitmap is used to record which pages of a database file have been
36865 ** journalled during a transaction, or which pages have the "dont-write"
36866 ** property.  Usually only a few pages are meet either condition.
36867 ** So the bitmap is usually sparse and has low cardinality.
36868 ** But sometimes (for example when during a DROP of a large table) most
36869 ** or all of the pages in a database can get journalled.  In those cases, 
36870 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
36871 ** to handle both cases well.
36872 **
36873 ** The size of the bitmap is fixed when the object is created.
36874 **
36875 ** All bits are clear when the bitmap is created.  Individual bits
36876 ** may be set or cleared one at a time.
36877 **
36878 ** Test operations are about 100 times more common that set operations.
36879 ** Clear operations are exceedingly rare.  There are usually between
36880 ** 5 and 500 set operations per Bitvec object, though the number of sets can
36881 ** sometimes grow into tens of thousands or larger.  The size of the
36882 ** Bitvec object is the number of pages in the database file at the
36883 ** start of a transaction, and is thus usually less than a few thousand,
36884 ** but can be as large as 2 billion for a really big database.
36885 */
36886
36887 /* Size of the Bitvec structure in bytes. */
36888 #define BITVEC_SZ        512
36889
36890 /* Round the union size down to the nearest pointer boundary, since that's how 
36891 ** it will be aligned within the Bitvec struct. */
36892 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
36893
36894 /* Type of the array "element" for the bitmap representation. 
36895 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
36896 ** Setting this to the "natural word" size of your CPU may improve
36897 ** performance. */
36898 #define BITVEC_TELEM     u8
36899 /* Size, in bits, of the bitmap element. */
36900 #define BITVEC_SZELEM    8
36901 /* Number of elements in a bitmap array. */
36902 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
36903 /* Number of bits in the bitmap array. */
36904 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
36905
36906 /* Number of u32 values in hash table. */
36907 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
36908 /* Maximum number of entries in hash table before 
36909 ** sub-dividing and re-hashing. */
36910 #define BITVEC_MXHASH    (BITVEC_NINT/2)
36911 /* Hashing function for the aHash representation.
36912 ** Empirical testing showed that the *37 multiplier 
36913 ** (an arbitrary prime)in the hash function provided 
36914 ** no fewer collisions than the no-op *1. */
36915 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
36916
36917 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
36918
36919
36920 /*
36921 ** A bitmap is an instance of the following structure.
36922 **
36923 ** This bitmap records the existance of zero or more bits
36924 ** with values between 1 and iSize, inclusive.
36925 **
36926 ** There are three possible representations of the bitmap.
36927 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
36928 ** bitmap.  The least significant bit is bit 1.
36929 **
36930 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
36931 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
36932 **
36933 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
36934 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
36935 ** handles up to iDivisor separate values of i.  apSub[0] holds
36936 ** values between 1 and iDivisor.  apSub[1] holds values between
36937 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
36938 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
36939 ** to hold deal with values between 1 and iDivisor.
36940 */
36941 struct Bitvec {
36942   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
36943   u32 nSet;       /* Number of bits that are set - only valid for aHash
36944                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
36945                   ** this would be 125. */
36946   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
36947                   /* Should >=0 for apSub element. */
36948                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
36949                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
36950   union {
36951     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
36952     u32 aHash[BITVEC_NINT];      /* Hash table representation */
36953     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
36954   } u;
36955 };
36956
36957 /*
36958 ** Create a new bitmap object able to handle bits between 0 and iSize,
36959 ** inclusive.  Return a pointer to the new object.  Return NULL if 
36960 ** malloc fails.
36961 */
36962 SQLCIPHER_PRIVATE Bitvec *sqlcipher3BitvecCreate(u32 iSize){
36963   Bitvec *p;
36964   assert( sizeof(*p)==BITVEC_SZ );
36965   p = sqlcipher3MallocZero( sizeof(*p) );
36966   if( p ){
36967     p->iSize = iSize;
36968   }
36969   return p;
36970 }
36971
36972 /*
36973 ** Check to see if the i-th bit is set.  Return true or false.
36974 ** If p is NULL (if the bitmap has not been created) or if
36975 ** i is out of range, then return false.
36976 */
36977 SQLCIPHER_PRIVATE int sqlcipher3BitvecTest(Bitvec *p, u32 i){
36978   if( p==0 ) return 0;
36979   if( i>p->iSize || i==0 ) return 0;
36980   i--;
36981   while( p->iDivisor ){
36982     u32 bin = i/p->iDivisor;
36983     i = i%p->iDivisor;
36984     p = p->u.apSub[bin];
36985     if (!p) {
36986       return 0;
36987     }
36988   }
36989   if( p->iSize<=BITVEC_NBIT ){
36990     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
36991   } else{
36992     u32 h = BITVEC_HASH(i++);
36993     while( p->u.aHash[h] ){
36994       if( p->u.aHash[h]==i ) return 1;
36995       h = (h+1) % BITVEC_NINT;
36996     }
36997     return 0;
36998   }
36999 }
37000
37001 /*
37002 ** Set the i-th bit.  Return 0 on success and an error code if
37003 ** anything goes wrong.
37004 **
37005 ** This routine might cause sub-bitmaps to be allocated.  Failing
37006 ** to get the memory needed to hold the sub-bitmap is the only
37007 ** that can go wrong with an insert, assuming p and i are valid.
37008 **
37009 ** The calling function must ensure that p is a valid Bitvec object
37010 ** and that the value for "i" is within range of the Bitvec object.
37011 ** Otherwise the behavior is undefined.
37012 */
37013 SQLCIPHER_PRIVATE int sqlcipher3BitvecSet(Bitvec *p, u32 i){
37014   u32 h;
37015   if( p==0 ) return SQLCIPHER_OK;
37016   assert( i>0 );
37017   assert( i<=p->iSize );
37018   i--;
37019   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
37020     u32 bin = i/p->iDivisor;
37021     i = i%p->iDivisor;
37022     if( p->u.apSub[bin]==0 ){
37023       p->u.apSub[bin] = sqlcipher3BitvecCreate( p->iDivisor );
37024       if( p->u.apSub[bin]==0 ) return SQLCIPHER_NOMEM;
37025     }
37026     p = p->u.apSub[bin];
37027   }
37028   if( p->iSize<=BITVEC_NBIT ){
37029     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
37030     return SQLCIPHER_OK;
37031   }
37032   h = BITVEC_HASH(i++);
37033   /* if there wasn't a hash collision, and this doesn't */
37034   /* completely fill the hash, then just add it without */
37035   /* worring about sub-dividing and re-hashing. */
37036   if( !p->u.aHash[h] ){
37037     if (p->nSet<(BITVEC_NINT-1)) {
37038       goto bitvec_set_end;
37039     } else {
37040       goto bitvec_set_rehash;
37041     }
37042   }
37043   /* there was a collision, check to see if it's already */
37044   /* in hash, if not, try to find a spot for it */
37045   do {
37046     if( p->u.aHash[h]==i ) return SQLCIPHER_OK;
37047     h++;
37048     if( h>=BITVEC_NINT ) h = 0;
37049   } while( p->u.aHash[h] );
37050   /* we didn't find it in the hash.  h points to the first */
37051   /* available free spot. check to see if this is going to */
37052   /* make our hash too "full".  */
37053 bitvec_set_rehash:
37054   if( p->nSet>=BITVEC_MXHASH ){
37055     unsigned int j;
37056     int rc;
37057     u32 *aiValues = sqlcipher3StackAllocRaw(0, sizeof(p->u.aHash));
37058     if( aiValues==0 ){
37059       return SQLCIPHER_NOMEM;
37060     }else{
37061       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37062       memset(p->u.apSub, 0, sizeof(p->u.apSub));
37063       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
37064       rc = sqlcipher3BitvecSet(p, i);
37065       for(j=0; j<BITVEC_NINT; j++){
37066         if( aiValues[j] ) rc |= sqlcipher3BitvecSet(p, aiValues[j]);
37067       }
37068       sqlcipher3StackFree(0, aiValues);
37069       return rc;
37070     }
37071   }
37072 bitvec_set_end:
37073   p->nSet++;
37074   p->u.aHash[h] = i;
37075   return SQLCIPHER_OK;
37076 }
37077
37078 /*
37079 ** Clear the i-th bit.
37080 **
37081 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
37082 ** that BitvecClear can use to rebuilt its hash table.
37083 */
37084 SQLCIPHER_PRIVATE void sqlcipher3BitvecClear(Bitvec *p, u32 i, void *pBuf){
37085   if( p==0 ) return;
37086   assert( i>0 );
37087   i--;
37088   while( p->iDivisor ){
37089     u32 bin = i/p->iDivisor;
37090     i = i%p->iDivisor;
37091     p = p->u.apSub[bin];
37092     if (!p) {
37093       return;
37094     }
37095   }
37096   if( p->iSize<=BITVEC_NBIT ){
37097     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
37098   }else{
37099     unsigned int j;
37100     u32 *aiValues = pBuf;
37101     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37102     memset(p->u.aHash, 0, sizeof(p->u.aHash));
37103     p->nSet = 0;
37104     for(j=0; j<BITVEC_NINT; j++){
37105       if( aiValues[j] && aiValues[j]!=(i+1) ){
37106         u32 h = BITVEC_HASH(aiValues[j]-1);
37107         p->nSet++;
37108         while( p->u.aHash[h] ){
37109           h++;
37110           if( h>=BITVEC_NINT ) h = 0;
37111         }
37112         p->u.aHash[h] = aiValues[j];
37113       }
37114     }
37115   }
37116 }
37117
37118 /*
37119 ** Destroy a bitmap object.  Reclaim all memory used.
37120 */
37121 SQLCIPHER_PRIVATE void sqlcipher3BitvecDestroy(Bitvec *p){
37122   if( p==0 ) return;
37123   if( p->iDivisor ){
37124     unsigned int i;
37125     for(i=0; i<BITVEC_NPTR; i++){
37126       sqlcipher3BitvecDestroy(p->u.apSub[i]);
37127     }
37128   }
37129   sqlcipher3_free(p);
37130 }
37131
37132 /*
37133 ** Return the value of the iSize parameter specified when Bitvec *p
37134 ** was created.
37135 */
37136 SQLCIPHER_PRIVATE u32 sqlcipher3BitvecSize(Bitvec *p){
37137   return p->iSize;
37138 }
37139
37140 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
37141 /*
37142 ** Let V[] be an array of unsigned characters sufficient to hold
37143 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
37144 ** Then the following macros can be used to set, clear, or test
37145 ** individual bits within V.
37146 */
37147 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
37148 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
37149 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
37150
37151 /*
37152 ** This routine runs an extensive test of the Bitvec code.
37153 **
37154 ** The input is an array of integers that acts as a program
37155 ** to test the Bitvec.  The integers are opcodes followed
37156 ** by 0, 1, or 3 operands, depending on the opcode.  Another
37157 ** opcode follows immediately after the last operand.
37158 **
37159 ** There are 6 opcodes numbered from 0 through 5.  0 is the
37160 ** "halt" opcode and causes the test to end.
37161 **
37162 **    0          Halt and return the number of errors
37163 **    1 N S X    Set N bits beginning with S and incrementing by X
37164 **    2 N S X    Clear N bits beginning with S and incrementing by X
37165 **    3 N        Set N randomly chosen bits
37166 **    4 N        Clear N randomly chosen bits
37167 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
37168 **
37169 ** The opcodes 1 through 4 perform set and clear operations are performed
37170 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
37171 ** Opcode 5 works on the linear array only, not on the Bitvec.
37172 ** Opcode 5 is used to deliberately induce a fault in order to
37173 ** confirm that error detection works.
37174 **
37175 ** At the conclusion of the test the linear array is compared
37176 ** against the Bitvec object.  If there are any differences,
37177 ** an error is returned.  If they are the same, zero is returned.
37178 **
37179 ** If a memory allocation error occurs, return -1.
37180 */
37181 SQLCIPHER_PRIVATE int sqlcipher3BitvecBuiltinTest(int sz, int *aOp){
37182   Bitvec *pBitvec = 0;
37183   unsigned char *pV = 0;
37184   int rc = -1;
37185   int i, nx, pc, op;
37186   void *pTmpSpace;
37187
37188   /* Allocate the Bitvec to be tested and a linear array of
37189   ** bits to act as the reference */
37190   pBitvec = sqlcipher3BitvecCreate( sz );
37191   pV = sqlcipher3_malloc( (sz+7)/8 + 1 );
37192   pTmpSpace = sqlcipher3_malloc(BITVEC_SZ);
37193   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
37194   memset(pV, 0, (sz+7)/8 + 1);
37195
37196   /* NULL pBitvec tests */
37197   sqlcipher3BitvecSet(0, 1);
37198   sqlcipher3BitvecClear(0, 1, pTmpSpace);
37199
37200   /* Run the program */
37201   pc = 0;
37202   while( (op = aOp[pc])!=0 ){
37203     switch( op ){
37204       case 1:
37205       case 2:
37206       case 5: {
37207         nx = 4;
37208         i = aOp[pc+2] - 1;
37209         aOp[pc+2] += aOp[pc+3];
37210         break;
37211       }
37212       case 3:
37213       case 4: 
37214       default: {
37215         nx = 2;
37216         sqlcipher3_randomness(sizeof(i), &i);
37217         break;
37218       }
37219     }
37220     if( (--aOp[pc+1]) > 0 ) nx = 0;
37221     pc += nx;
37222     i = (i & 0x7fffffff)%sz;
37223     if( (op & 1)!=0 ){
37224       SETBIT(pV, (i+1));
37225       if( op!=5 ){
37226         if( sqlcipher3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
37227       }
37228     }else{
37229       CLEARBIT(pV, (i+1));
37230       sqlcipher3BitvecClear(pBitvec, i+1, pTmpSpace);
37231     }
37232   }
37233
37234   /* Test to make sure the linear array exactly matches the
37235   ** Bitvec object.  Start with the assumption that they do
37236   ** match (rc==0).  Change rc to non-zero if a discrepancy
37237   ** is found.
37238   */
37239   rc = sqlcipher3BitvecTest(0,0) + sqlcipher3BitvecTest(pBitvec, sz+1)
37240           + sqlcipher3BitvecTest(pBitvec, 0)
37241           + (sqlcipher3BitvecSize(pBitvec) - sz);
37242   for(i=1; i<=sz; i++){
37243     if(  (TESTBIT(pV,i))!=sqlcipher3BitvecTest(pBitvec,i) ){
37244       rc = i;
37245       break;
37246     }
37247   }
37248
37249   /* Free allocated structure */
37250 bitvec_end:
37251   sqlcipher3_free(pTmpSpace);
37252   sqlcipher3_free(pV);
37253   sqlcipher3BitvecDestroy(pBitvec);
37254   return rc;
37255 }
37256 #endif /* SQLCIPHER_OMIT_BUILTIN_TEST */
37257
37258 /************** End of bitvec.c **********************************************/
37259 /************** Begin file pcache.c ******************************************/
37260 /*
37261 ** 2008 August 05
37262 **
37263 ** The author disclaims copyright to this source code.  In place of
37264 ** a legal notice, here is a blessing:
37265 **
37266 **    May you do good and not evil.
37267 **    May you find forgiveness for yourself and forgive others.
37268 **    May you share freely, never taking more than you give.
37269 **
37270 *************************************************************************
37271 ** This file implements that page cache.
37272 */
37273
37274 /*
37275 ** A complete page cache is an instance of this structure.
37276 */
37277 struct PCache {
37278   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
37279   PgHdr *pSynced;                     /* Last synced page in dirty page list */
37280   int nRef;                           /* Number of referenced pages */
37281   int nMax;                           /* Configured cache size */
37282   int szPage;                         /* Size of every page in this cache */
37283   int szExtra;                        /* Size of extra space for each page */
37284   int bPurgeable;                     /* True if pages are on backing store */
37285   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
37286   void *pStress;                      /* Argument to xStress */
37287   sqlcipher3_pcache *pCache;             /* Pluggable cache module */
37288   PgHdr *pPage1;                      /* Reference to page 1 */
37289 };
37290
37291 /*
37292 ** Some of the assert() macros in this code are too expensive to run
37293 ** even during normal debugging.  Use them only rarely on long-running
37294 ** tests.  Enable the expensive asserts using the
37295 ** -DSQLCIPHER_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
37296 */
37297 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
37298 # define expensive_assert(X)  assert(X)
37299 #else
37300 # define expensive_assert(X)
37301 #endif
37302
37303 /********************************** Linked List Management ********************/
37304
37305 #if !defined(NDEBUG) && defined(SQLCIPHER_ENABLE_EXPENSIVE_ASSERT)
37306 /*
37307 ** Check that the pCache->pSynced variable is set correctly. If it
37308 ** is not, either fail an assert or return zero. Otherwise, return
37309 ** non-zero. This is only used in debugging builds, as follows:
37310 **
37311 **   expensive_assert( pcacheCheckSynced(pCache) );
37312 */
37313 static int pcacheCheckSynced(PCache *pCache){
37314   PgHdr *p;
37315   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
37316     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
37317   }
37318   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
37319 }
37320 #endif /* !NDEBUG && SQLCIPHER_ENABLE_EXPENSIVE_ASSERT */
37321
37322 /*
37323 ** Remove page pPage from the list of dirty pages.
37324 */
37325 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
37326   PCache *p = pPage->pCache;
37327
37328   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
37329   assert( pPage->pDirtyPrev || pPage==p->pDirty );
37330
37331   /* Update the PCache1.pSynced variable if necessary. */
37332   if( p->pSynced==pPage ){
37333     PgHdr *pSynced = pPage->pDirtyPrev;
37334     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
37335       pSynced = pSynced->pDirtyPrev;
37336     }
37337     p->pSynced = pSynced;
37338   }
37339
37340   if( pPage->pDirtyNext ){
37341     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
37342   }else{
37343     assert( pPage==p->pDirtyTail );
37344     p->pDirtyTail = pPage->pDirtyPrev;
37345   }
37346   if( pPage->pDirtyPrev ){
37347     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
37348   }else{
37349     assert( pPage==p->pDirty );
37350     p->pDirty = pPage->pDirtyNext;
37351   }
37352   pPage->pDirtyNext = 0;
37353   pPage->pDirtyPrev = 0;
37354
37355   expensive_assert( pcacheCheckSynced(p) );
37356 }
37357
37358 /*
37359 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
37360 ** pPage).
37361 */
37362 static void pcacheAddToDirtyList(PgHdr *pPage){
37363   PCache *p = pPage->pCache;
37364
37365   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
37366
37367   pPage->pDirtyNext = p->pDirty;
37368   if( pPage->pDirtyNext ){
37369     assert( pPage->pDirtyNext->pDirtyPrev==0 );
37370     pPage->pDirtyNext->pDirtyPrev = pPage;
37371   }
37372   p->pDirty = pPage;
37373   if( !p->pDirtyTail ){
37374     p->pDirtyTail = pPage;
37375   }
37376   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
37377     p->pSynced = pPage;
37378   }
37379   expensive_assert( pcacheCheckSynced(p) );
37380 }
37381
37382 /*
37383 ** Wrapper around the pluggable caches xUnpin method. If the cache is
37384 ** being used for an in-memory database, this function is a no-op.
37385 */
37386 static void pcacheUnpin(PgHdr *p){
37387   PCache *pCache = p->pCache;
37388   if( pCache->bPurgeable ){
37389     if( p->pgno==1 ){
37390       pCache->pPage1 = 0;
37391     }
37392     sqlcipher3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
37393   }
37394 }
37395
37396 /*************************************************** General Interfaces ******
37397 **
37398 ** Initialize and shutdown the page cache subsystem. Neither of these 
37399 ** functions are threadsafe.
37400 */
37401 SQLCIPHER_PRIVATE int sqlcipher3PcacheInitialize(void){
37402   if( sqlcipher3GlobalConfig.pcache.xInit==0 ){
37403     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
37404     ** built-in default page cache is used instead of the application defined
37405     ** page cache. */
37406     sqlcipher3PCacheSetDefault();
37407   }
37408   return sqlcipher3GlobalConfig.pcache.xInit(sqlcipher3GlobalConfig.pcache.pArg);
37409 }
37410 SQLCIPHER_PRIVATE void sqlcipher3PcacheShutdown(void){
37411   if( sqlcipher3GlobalConfig.pcache.xShutdown ){
37412     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
37413     sqlcipher3GlobalConfig.pcache.xShutdown(sqlcipher3GlobalConfig.pcache.pArg);
37414   }
37415 }
37416
37417 /*
37418 ** Return the size in bytes of a PCache object.
37419 */
37420 SQLCIPHER_PRIVATE int sqlcipher3PcacheSize(void){ return sizeof(PCache); }
37421
37422 /*
37423 ** Create a new PCache object. Storage space to hold the object
37424 ** has already been allocated and is passed in as the p pointer. 
37425 ** The caller discovers how much space needs to be allocated by 
37426 ** calling sqlcipher3PcacheSize().
37427 */
37428 SQLCIPHER_PRIVATE void sqlcipher3PcacheOpen(
37429   int szPage,                  /* Size of every page */
37430   int szExtra,                 /* Extra space associated with each page */
37431   int bPurgeable,              /* True if pages are on backing store */
37432   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
37433   void *pStress,               /* Argument to xStress */
37434   PCache *p                    /* Preallocated space for the PCache */
37435 ){
37436   memset(p, 0, sizeof(PCache));
37437   p->szPage = szPage;
37438   p->szExtra = szExtra;
37439   p->bPurgeable = bPurgeable;
37440   p->xStress = xStress;
37441   p->pStress = pStress;
37442   p->nMax = 100;
37443 }
37444
37445 /*
37446 ** Change the page size for PCache object. The caller must ensure that there
37447 ** are no outstanding page references when this function is called.
37448 */
37449 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetPageSize(PCache *pCache, int szPage){
37450   assert( pCache->nRef==0 && pCache->pDirty==0 );
37451   if( pCache->pCache ){
37452     sqlcipher3GlobalConfig.pcache.xDestroy(pCache->pCache);
37453     pCache->pCache = 0;
37454     pCache->pPage1 = 0;
37455   }
37456   pCache->szPage = szPage;
37457 }
37458
37459 /*
37460 ** Try to obtain a page from the cache.
37461 */
37462 SQLCIPHER_PRIVATE int sqlcipher3PcacheFetch(
37463   PCache *pCache,       /* Obtain the page from this cache */
37464   Pgno pgno,            /* Page number to obtain */
37465   int createFlag,       /* If true, create page if it does not exist already */
37466   PgHdr **ppPage        /* Write the page here */
37467 ){
37468   PgHdr *pPage = 0;
37469   int eCreate;
37470
37471   assert( pCache!=0 );
37472   assert( createFlag==1 || createFlag==0 );
37473   assert( pgno>0 );
37474
37475   /* If the pluggable cache (sqlcipher3_pcache*) has not been allocated,
37476   ** allocate it now.
37477   */
37478   if( !pCache->pCache && createFlag ){
37479     sqlcipher3_pcache *p;
37480     int nByte;
37481     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
37482     p = sqlcipher3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
37483     if( !p ){
37484       return SQLCIPHER_NOMEM;
37485     }
37486     sqlcipher3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
37487     pCache->pCache = p;
37488   }
37489
37490   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
37491   if( pCache->pCache ){
37492     pPage = sqlcipher3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
37493   }
37494
37495   if( !pPage && eCreate==1 ){
37496     PgHdr *pPg;
37497
37498     /* Find a dirty page to write-out and recycle. First try to find a 
37499     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37500     ** cleared), but if that is not possible settle for any other 
37501     ** unreferenced dirty page.
37502     */
37503     expensive_assert( pcacheCheckSynced(pCache) );
37504     for(pPg=pCache->pSynced; 
37505         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
37506         pPg=pPg->pDirtyPrev
37507     );
37508     pCache->pSynced = pPg;
37509     if( !pPg ){
37510       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37511     }
37512     if( pPg ){
37513       int rc;
37514 #ifdef SQLCIPHER_LOG_CACHE_SPILL
37515       sqlcipher3_log(SQLCIPHER_FULL, 
37516                   "spill page %d making room for %d - cache used: %d/%d",
37517                   pPg->pgno, pgno,
37518                   sqlcipher3GlobalConfig.pcache.xPagecount(pCache->pCache),
37519                   pCache->nMax);
37520 #endif
37521       rc = pCache->xStress(pCache->pStress, pPg);
37522       if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY ){
37523         return rc;
37524       }
37525     }
37526
37527     pPage = sqlcipher3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
37528   }
37529
37530   if( pPage ){
37531     if( !pPage->pData ){
37532       memset(pPage, 0, sizeof(PgHdr));
37533       pPage->pData = (void *)&pPage[1];
37534       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
37535       memset(pPage->pExtra, 0, pCache->szExtra);
37536       pPage->pCache = pCache;
37537       pPage->pgno = pgno;
37538     }
37539     assert( pPage->pCache==pCache );
37540     assert( pPage->pgno==pgno );
37541     assert( pPage->pData==(void *)&pPage[1] );
37542     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
37543
37544     if( 0==pPage->nRef ){
37545       pCache->nRef++;
37546     }
37547     pPage->nRef++;
37548     if( pgno==1 ){
37549       pCache->pPage1 = pPage;
37550     }
37551   }
37552   *ppPage = pPage;
37553   return (pPage==0 && eCreate) ? SQLCIPHER_NOMEM : SQLCIPHER_OK;
37554 }
37555
37556 /*
37557 ** Decrement the reference count on a page. If the page is clean and the
37558 ** reference count drops to 0, then it is made elible for recycling.
37559 */
37560 SQLCIPHER_PRIVATE void sqlcipher3PcacheRelease(PgHdr *p){
37561   assert( p->nRef>0 );
37562   p->nRef--;
37563   if( p->nRef==0 ){
37564     PCache *pCache = p->pCache;
37565     pCache->nRef--;
37566     if( (p->flags&PGHDR_DIRTY)==0 ){
37567       pcacheUnpin(p);
37568     }else{
37569       /* Move the page to the head of the dirty list. */
37570       pcacheRemoveFromDirtyList(p);
37571       pcacheAddToDirtyList(p);
37572     }
37573   }
37574 }
37575
37576 /*
37577 ** Increase the reference count of a supplied page by 1.
37578 */
37579 SQLCIPHER_PRIVATE void sqlcipher3PcacheRef(PgHdr *p){
37580   assert(p->nRef>0);
37581   p->nRef++;
37582 }
37583
37584 /*
37585 ** Drop a page from the cache. There must be exactly one reference to the
37586 ** page. This function deletes that reference, so after it returns the
37587 ** page pointed to by p is invalid.
37588 */
37589 SQLCIPHER_PRIVATE void sqlcipher3PcacheDrop(PgHdr *p){
37590   PCache *pCache;
37591   assert( p->nRef==1 );
37592   if( p->flags&PGHDR_DIRTY ){
37593     pcacheRemoveFromDirtyList(p);
37594   }
37595   pCache = p->pCache;
37596   pCache->nRef--;
37597   if( p->pgno==1 ){
37598     pCache->pPage1 = 0;
37599   }
37600   sqlcipher3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
37601 }
37602
37603 /*
37604 ** Make sure the page is marked as dirty. If it isn't dirty already,
37605 ** make it so.
37606 */
37607 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeDirty(PgHdr *p){
37608   p->flags &= ~PGHDR_DONT_WRITE;
37609   assert( p->nRef>0 );
37610   if( 0==(p->flags & PGHDR_DIRTY) ){
37611     p->flags |= PGHDR_DIRTY;
37612     pcacheAddToDirtyList( p);
37613   }
37614 }
37615
37616 /*
37617 ** Make sure the page is marked as clean. If it isn't clean already,
37618 ** make it so.
37619 */
37620 SQLCIPHER_PRIVATE void sqlcipher3PcacheMakeClean(PgHdr *p){
37621   if( (p->flags & PGHDR_DIRTY) ){
37622     pcacheRemoveFromDirtyList(p);
37623     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37624     if( p->nRef==0 ){
37625       pcacheUnpin(p);
37626     }
37627   }
37628 }
37629
37630 /*
37631 ** Make every page in the cache clean.
37632 */
37633 SQLCIPHER_PRIVATE void sqlcipher3PcacheCleanAll(PCache *pCache){
37634   PgHdr *p;
37635   while( (p = pCache->pDirty)!=0 ){
37636     sqlcipher3PcacheMakeClean(p);
37637   }
37638 }
37639
37640 /*
37641 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37642 */
37643 SQLCIPHER_PRIVATE void sqlcipher3PcacheClearSyncFlags(PCache *pCache){
37644   PgHdr *p;
37645   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37646     p->flags &= ~PGHDR_NEED_SYNC;
37647   }
37648   pCache->pSynced = pCache->pDirtyTail;
37649 }
37650
37651 /*
37652 ** Change the page number of page p to newPgno. 
37653 */
37654 SQLCIPHER_PRIVATE void sqlcipher3PcacheMove(PgHdr *p, Pgno newPgno){
37655   PCache *pCache = p->pCache;
37656   assert( p->nRef>0 );
37657   assert( newPgno>0 );
37658   sqlcipher3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
37659   p->pgno = newPgno;
37660   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37661     pcacheRemoveFromDirtyList(p);
37662     pcacheAddToDirtyList(p);
37663   }
37664 }
37665
37666 /*
37667 ** Drop every cache entry whose page number is greater than "pgno". The
37668 ** caller must ensure that there are no outstanding references to any pages
37669 ** other than page 1 with a page number greater than pgno.
37670 **
37671 ** If there is a reference to page 1 and the pgno parameter passed to this
37672 ** function is 0, then the data area associated with page 1 is zeroed, but
37673 ** the page object is not dropped.
37674 */
37675 SQLCIPHER_PRIVATE void sqlcipher3PcacheTruncate(PCache *pCache, Pgno pgno){
37676   if( pCache->pCache ){
37677     PgHdr *p;
37678     PgHdr *pNext;
37679     for(p=pCache->pDirty; p; p=pNext){
37680       pNext = p->pDirtyNext;
37681       /* This routine never gets call with a positive pgno except right
37682       ** after sqlcipher3PcacheCleanAll().  So if there are dirty pages,
37683       ** it must be that pgno==0.
37684       */
37685       assert( p->pgno>0 );
37686       if( ALWAYS(p->pgno>pgno) ){
37687         assert( p->flags&PGHDR_DIRTY );
37688         sqlcipher3PcacheMakeClean(p);
37689       }
37690     }
37691     if( pgno==0 && pCache->pPage1 ){
37692       memset(pCache->pPage1->pData, 0, pCache->szPage);
37693       pgno = 1;
37694     }
37695     sqlcipher3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
37696   }
37697 }
37698
37699 /*
37700 ** Close a cache.
37701 */
37702 SQLCIPHER_PRIVATE void sqlcipher3PcacheClose(PCache *pCache){
37703   if( pCache->pCache ){
37704     sqlcipher3GlobalConfig.pcache.xDestroy(pCache->pCache);
37705   }
37706 }
37707
37708 /* 
37709 ** Discard the contents of the cache.
37710 */
37711 SQLCIPHER_PRIVATE void sqlcipher3PcacheClear(PCache *pCache){
37712   sqlcipher3PcacheTruncate(pCache, 0);
37713 }
37714
37715 /*
37716 ** Merge two lists of pages connected by pDirty and in pgno order.
37717 ** Do not both fixing the pDirtyPrev pointers.
37718 */
37719 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
37720   PgHdr result, *pTail;
37721   pTail = &result;
37722   while( pA && pB ){
37723     if( pA->pgno<pB->pgno ){
37724       pTail->pDirty = pA;
37725       pTail = pA;
37726       pA = pA->pDirty;
37727     }else{
37728       pTail->pDirty = pB;
37729       pTail = pB;
37730       pB = pB->pDirty;
37731     }
37732   }
37733   if( pA ){
37734     pTail->pDirty = pA;
37735   }else if( pB ){
37736     pTail->pDirty = pB;
37737   }else{
37738     pTail->pDirty = 0;
37739   }
37740   return result.pDirty;
37741 }
37742
37743 /*
37744 ** Sort the list of pages in accending order by pgno.  Pages are
37745 ** connected by pDirty pointers.  The pDirtyPrev pointers are
37746 ** corrupted by this sort.
37747 **
37748 ** Since there cannot be more than 2^31 distinct pages in a database,
37749 ** there cannot be more than 31 buckets required by the merge sorter.
37750 ** One extra bucket is added to catch overflow in case something
37751 ** ever changes to make the previous sentence incorrect.
37752 */
37753 #define N_SORT_BUCKET  32
37754 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
37755   PgHdr *a[N_SORT_BUCKET], *p;
37756   int i;
37757   memset(a, 0, sizeof(a));
37758   while( pIn ){
37759     p = pIn;
37760     pIn = p->pDirty;
37761     p->pDirty = 0;
37762     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
37763       if( a[i]==0 ){
37764         a[i] = p;
37765         break;
37766       }else{
37767         p = pcacheMergeDirtyList(a[i], p);
37768         a[i] = 0;
37769       }
37770     }
37771     if( NEVER(i==N_SORT_BUCKET-1) ){
37772       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
37773       ** the input list.  But that is impossible.
37774       */
37775       a[i] = pcacheMergeDirtyList(a[i], p);
37776     }
37777   }
37778   p = a[0];
37779   for(i=1; i<N_SORT_BUCKET; i++){
37780     p = pcacheMergeDirtyList(p, a[i]);
37781   }
37782   return p;
37783 }
37784
37785 /*
37786 ** Return a list of all dirty pages in the cache, sorted by page number.
37787 */
37788 SQLCIPHER_PRIVATE PgHdr *sqlcipher3PcacheDirtyList(PCache *pCache){
37789   PgHdr *p;
37790   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37791     p->pDirty = p->pDirtyNext;
37792   }
37793   return pcacheSortDirtyList(pCache->pDirty);
37794 }
37795
37796 /* 
37797 ** Return the total number of referenced pages held by the cache.
37798 */
37799 SQLCIPHER_PRIVATE int sqlcipher3PcacheRefCount(PCache *pCache){
37800   return pCache->nRef;
37801 }
37802
37803 /*
37804 ** Return the number of references to the page supplied as an argument.
37805 */
37806 SQLCIPHER_PRIVATE int sqlcipher3PcachePageRefcount(PgHdr *p){
37807   return p->nRef;
37808 }
37809
37810 /* 
37811 ** Return the total number of pages in the cache.
37812 */
37813 SQLCIPHER_PRIVATE int sqlcipher3PcachePagecount(PCache *pCache){
37814   int nPage = 0;
37815   if( pCache->pCache ){
37816     nPage = sqlcipher3GlobalConfig.pcache.xPagecount(pCache->pCache);
37817   }
37818   return nPage;
37819 }
37820
37821 #ifdef SQLCIPHER_TEST
37822 /*
37823 ** Get the suggested cache-size value.
37824 */
37825 SQLCIPHER_PRIVATE int sqlcipher3PcacheGetCachesize(PCache *pCache){
37826   return pCache->nMax;
37827 }
37828 #endif
37829
37830 /*
37831 ** Set the suggested cache-size value.
37832 */
37833 SQLCIPHER_PRIVATE void sqlcipher3PcacheSetCachesize(PCache *pCache, int mxPage){
37834   pCache->nMax = mxPage;
37835   if( pCache->pCache ){
37836     sqlcipher3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
37837   }
37838 }
37839
37840 #if defined(SQLCIPHER_CHECK_PAGES) || defined(SQLCIPHER_DEBUG)
37841 /*
37842 ** For all dirty pages currently in the cache, invoke the specified
37843 ** callback. This is only used if the SQLCIPHER_CHECK_PAGES macro is
37844 ** defined.
37845 */
37846 SQLCIPHER_PRIVATE void sqlcipher3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
37847   PgHdr *pDirty;
37848   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
37849     xIter(pDirty);
37850   }
37851 }
37852 #endif
37853
37854 /************** End of pcache.c **********************************************/
37855 /************** Begin file pcache1.c *****************************************/
37856 /*
37857 ** 2008 November 05
37858 **
37859 ** The author disclaims copyright to this source code.  In place of
37860 ** a legal notice, here is a blessing:
37861 **
37862 **    May you do good and not evil.
37863 **    May you find forgiveness for yourself and forgive others.
37864 **    May you share freely, never taking more than you give.
37865 **
37866 *************************************************************************
37867 **
37868 ** This file implements the default page cache implementation (the
37869 ** sqlcipher3_pcache interface). It also contains part of the implementation
37870 ** of the SQLCIPHER_CONFIG_PAGECACHE and sqlcipher3_release_memory() features.
37871 ** If the default page cache implementation is overriden, then neither of
37872 ** these two features are available.
37873 */
37874
37875
37876 typedef struct PCache1 PCache1;
37877 typedef struct PgHdr1 PgHdr1;
37878 typedef struct PgFreeslot PgFreeslot;
37879 typedef struct PGroup PGroup;
37880
37881
37882 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
37883 ** of one or more PCaches that are able to recycle each others unpinned
37884 ** pages when they are under memory pressure.  A PGroup is an instance of
37885 ** the following object.
37886 **
37887 ** This page cache implementation works in one of two modes:
37888 **
37889 **   (1)  Every PCache is the sole member of its own PGroup.  There is
37890 **        one PGroup per PCache.
37891 **
37892 **   (2)  There is a single global PGroup that all PCaches are a member
37893 **        of.
37894 **
37895 ** Mode 1 uses more memory (since PCache instances are not able to rob
37896 ** unused pages from other PCaches) but it also operates without a mutex,
37897 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
37898 ** threadsafe, but is able recycle pages more efficient.
37899 **
37900 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
37901 ** PGroup which is the pcache1.grp global variable and its mutex is
37902 ** SQLCIPHER_MUTEX_STATIC_LRU.
37903 */
37904 struct PGroup {
37905   sqlcipher3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
37906   int nMaxPage;                  /* Sum of nMax for purgeable caches */
37907   int nMinPage;                  /* Sum of nMin for purgeable caches */
37908   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
37909   int nCurrentPage;              /* Number of purgeable pages allocated */
37910   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
37911 };
37912
37913 /* Each page cache is an instance of the following object.  Every
37914 ** open database file (including each in-memory database and each
37915 ** temporary or transient database) has a single page cache which
37916 ** is an instance of this object.
37917 **
37918 ** Pointers to structures of this type are cast and returned as 
37919 ** opaque sqlcipher3_pcache* handles.
37920 */
37921 struct PCache1 {
37922   /* Cache configuration parameters. Page size (szPage) and the purgeable
37923   ** flag (bPurgeable) are set when the cache is created. nMax may be 
37924   ** modified at any time by a call to the pcache1CacheSize() method.
37925   ** The PGroup mutex must be held when accessing nMax.
37926   */
37927   PGroup *pGroup;                     /* PGroup this cache belongs to */
37928   int szPage;                         /* Size of allocated pages in bytes */
37929   int bPurgeable;                     /* True if cache is purgeable */
37930   unsigned int nMin;                  /* Minimum number of pages reserved */
37931   unsigned int nMax;                  /* Configured "cache_size" value */
37932   unsigned int n90pct;                /* nMax*9/10 */
37933
37934   /* Hash table of all pages. The following variables may only be accessed
37935   ** when the accessor is holding the PGroup mutex.
37936   */
37937   unsigned int nRecyclable;           /* Number of pages in the LRU list */
37938   unsigned int nPage;                 /* Total number of pages in apHash */
37939   unsigned int nHash;                 /* Number of slots in apHash[] */
37940   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
37941
37942   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
37943 };
37944
37945 /*
37946 ** Each cache entry is represented by an instance of the following 
37947 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
37948 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
37949 ** macro below).
37950 */
37951 struct PgHdr1 {
37952   unsigned int iKey;             /* Key value (page number) */
37953   PgHdr1 *pNext;                 /* Next in hash table chain */
37954   PCache1 *pCache;               /* Cache that currently owns this page */
37955   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
37956   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
37957 };
37958
37959 /*
37960 ** Free slots in the allocator used to divide up the buffer provided using
37961 ** the SQLCIPHER_CONFIG_PAGECACHE mechanism.
37962 */
37963 struct PgFreeslot {
37964   PgFreeslot *pNext;  /* Next free slot */
37965 };
37966
37967 /*
37968 ** Global data used by this cache.
37969 */
37970 static SQLCIPHER_WSD struct PCacheGlobal {
37971   PGroup grp;                    /* The global PGroup for mode (2) */
37972
37973   /* Variables related to SQLCIPHER_CONFIG_PAGECACHE settings.  The
37974   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
37975   ** fixed at sqlcipher3_initialize() time and do not require mutex protection.
37976   ** The nFreeSlot and pFree values do require mutex protection.
37977   */
37978   int isInit;                    /* True if initialized */
37979   int szSlot;                    /* Size of each free slot */
37980   int nSlot;                     /* The number of pcache slots */
37981   int nReserve;                  /* Try to keep nFreeSlot above this */
37982   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
37983   /* Above requires no mutex.  Use mutex below for variable that follow. */
37984   sqlcipher3_mutex *mutex;          /* Mutex for accessing the following: */
37985   int nFreeSlot;                 /* Number of unused pcache slots */
37986   PgFreeslot *pFree;             /* Free page blocks */
37987   /* The following value requires a mutex to change.  We skip the mutex on
37988   ** reading because (1) most platforms read a 32-bit integer atomically and
37989   ** (2) even if an incorrect value is read, no great harm is done since this
37990   ** is really just an optimization. */
37991   int bUnderPressure;            /* True if low on PAGECACHE memory */
37992 } pcache1_g;
37993
37994 /*
37995 ** All code in this file should access the global structure above via the
37996 ** alias "pcache1". This ensures that the WSD emulation is used when
37997 ** compiling for systems that do not support real WSD.
37998 */
37999 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
38000
38001 /*
38002 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
38003 ** bytes of data are located directly before it in memory (i.e. the total
38004 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
38005 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
38006 ** an argument and returns a pointer to the associated block of szPage
38007 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
38008 ** a pointer to a block of szPage bytes of data and the return value is
38009 ** a pointer to the associated PgHdr1 structure.
38010 **
38011 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
38012 */
38013 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
38014 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
38015
38016 /*
38017 ** Macros to enter and leave the PCache LRU mutex.
38018 */
38019 #define pcache1EnterMutex(X) sqlcipher3_mutex_enter((X)->mutex)
38020 #define pcache1LeaveMutex(X) sqlcipher3_mutex_leave((X)->mutex)
38021
38022 /******************************************************************************/
38023 /******** Page Allocation/SQLCIPHER_CONFIG_PCACHE Related Functions **************/
38024
38025 /*
38026 ** This function is called during initialization if a static buffer is 
38027 ** supplied to use for the page-cache by passing the SQLCIPHER_CONFIG_PAGECACHE
38028 ** verb to sqlcipher3_config(). Parameter pBuf points to an allocation large
38029 ** enough to contain 'n' buffers of 'sz' bytes each.
38030 **
38031 ** This routine is called from sqlcipher3_initialize() and so it is guaranteed
38032 ** to be serialized already.  There is no need for further mutexing.
38033 */
38034 SQLCIPHER_PRIVATE void sqlcipher3PCacheBufferSetup(void *pBuf, int sz, int n){
38035   if( pcache1.isInit ){
38036     PgFreeslot *p;
38037     sz = ROUNDDOWN8(sz);
38038     pcache1.szSlot = sz;
38039     pcache1.nSlot = pcache1.nFreeSlot = n;
38040     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
38041     pcache1.pStart = pBuf;
38042     pcache1.pFree = 0;
38043     pcache1.bUnderPressure = 0;
38044     while( n-- ){
38045       p = (PgFreeslot*)pBuf;
38046       p->pNext = pcache1.pFree;
38047       pcache1.pFree = p;
38048       pBuf = (void*)&((char*)pBuf)[sz];
38049     }
38050     pcache1.pEnd = pBuf;
38051   }
38052 }
38053
38054 /*
38055 ** Malloc function used within this file to allocate space from the buffer
38056 ** configured using sqlcipher3_config(SQLCIPHER_CONFIG_PAGECACHE) option. If no 
38057 ** such buffer exists or there is no space left in it, this function falls 
38058 ** back to sqlcipher3Malloc().
38059 **
38060 ** Multiple threads can run this routine at the same time.  Global variables
38061 ** in pcache1 need to be protected via mutex.
38062 */
38063 static void *pcache1Alloc(int nByte){
38064   void *p = 0;
38065   assert( sqlcipher3_mutex_notheld(pcache1.grp.mutex) );
38066   sqlcipher3StatusSet(SQLCIPHER_STATUS_PAGECACHE_SIZE, nByte);
38067   if( nByte<=pcache1.szSlot ){
38068     sqlcipher3_mutex_enter(pcache1.mutex);
38069     p = (PgHdr1 *)pcache1.pFree;
38070     if( p ){
38071       pcache1.pFree = pcache1.pFree->pNext;
38072       pcache1.nFreeSlot--;
38073       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38074       assert( pcache1.nFreeSlot>=0 );
38075       sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_USED, 1);
38076     }
38077     sqlcipher3_mutex_leave(pcache1.mutex);
38078   }
38079   if( p==0 ){
38080     /* Memory is not available in the SQLCIPHER_CONFIG_PAGECACHE pool.  Get
38081     ** it from sqlcipher3Malloc instead.
38082     */
38083     p = sqlcipher3Malloc(nByte);
38084     if( p ){
38085       int sz = sqlcipher3MallocSize(p);
38086       sqlcipher3_mutex_enter(pcache1.mutex);
38087       sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_OVERFLOW, sz);
38088       sqlcipher3_mutex_leave(pcache1.mutex);
38089     }
38090     sqlcipher3MemdebugSetType(p, MEMTYPE_PCACHE);
38091   }
38092   return p;
38093 }
38094
38095 /*
38096 ** Free an allocated buffer obtained from pcache1Alloc().
38097 */
38098 static void pcache1Free(void *p){
38099   if( p==0 ) return;
38100   if( p>=pcache1.pStart && p<pcache1.pEnd ){
38101     PgFreeslot *pSlot;
38102     sqlcipher3_mutex_enter(pcache1.mutex);
38103     sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_USED, -1);
38104     pSlot = (PgFreeslot*)p;
38105     pSlot->pNext = pcache1.pFree;
38106     pcache1.pFree = pSlot;
38107     pcache1.nFreeSlot++;
38108     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38109     assert( pcache1.nFreeSlot<=pcache1.nSlot );
38110     sqlcipher3_mutex_leave(pcache1.mutex);
38111   }else{
38112     int iSize;
38113     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_PCACHE) );
38114     sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
38115     iSize = sqlcipher3MallocSize(p);
38116     sqlcipher3_mutex_enter(pcache1.mutex);
38117     sqlcipher3StatusAdd(SQLCIPHER_STATUS_PAGECACHE_OVERFLOW, -iSize);
38118     sqlcipher3_mutex_leave(pcache1.mutex);
38119     sqlcipher3_free(p);
38120   }
38121 }
38122
38123 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
38124 /*
38125 ** Return the size of a pcache allocation
38126 */
38127 static int pcache1MemSize(void *p){
38128   if( p>=pcache1.pStart && p<pcache1.pEnd ){
38129     return pcache1.szSlot;
38130   }else{
38131     int iSize;
38132     assert( sqlcipher3MemdebugHasType(p, MEMTYPE_PCACHE) );
38133     sqlcipher3MemdebugSetType(p, MEMTYPE_HEAP);
38134     iSize = sqlcipher3MallocSize(p);
38135     sqlcipher3MemdebugSetType(p, MEMTYPE_PCACHE);
38136     return iSize;
38137   }
38138 }
38139 #endif /* SQLCIPHER_ENABLE_MEMORY_MANAGEMENT */
38140
38141 /*
38142 ** Allocate a new page object initially associated with cache pCache.
38143 */
38144 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
38145   int nByte = sizeof(PgHdr1) + pCache->szPage;
38146   PgHdr1 *p = 0;
38147   void *pPg;
38148
38149   /* The group mutex must be released before pcache1Alloc() is called. This
38150   ** is because it may call sqlcipher3_release_memory(), which assumes that 
38151   ** this mutex is not held. */
38152   assert( sqlcipher3_mutex_held(pCache->pGroup->mutex) );
38153   pcache1LeaveMutex(pCache->pGroup);
38154   pPg = pcache1Alloc(nByte);
38155   pcache1EnterMutex(pCache->pGroup);
38156
38157   if( pPg ){
38158     p = PAGE_TO_PGHDR1(pCache, pPg);
38159     if( pCache->bPurgeable ){
38160       pCache->pGroup->nCurrentPage++;
38161     }
38162   }
38163   return p;
38164 }
38165
38166 /*
38167 ** Free a page object allocated by pcache1AllocPage().
38168 **
38169 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
38170 ** that the current implementation happens to never call this routine
38171 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
38172 */
38173 static void pcache1FreePage(PgHdr1 *p){
38174   if( ALWAYS(p) ){
38175     PCache1 *pCache = p->pCache;
38176     assert( sqlcipher3_mutex_held(p->pCache->pGroup->mutex) );
38177     pcache1Free(PGHDR1_TO_PAGE(p));
38178     if( pCache->bPurgeable ){
38179       pCache->pGroup->nCurrentPage--;
38180     }
38181   }
38182 }
38183
38184 /*
38185 ** Malloc function used by SQLite to obtain space from the buffer configured
38186 ** using sqlcipher3_config(SQLCIPHER_CONFIG_PAGECACHE) option. If no such buffer
38187 ** exists, this function falls back to sqlcipher3Malloc().
38188 */
38189 SQLCIPHER_PRIVATE void *sqlcipher3PageMalloc(int sz){
38190   return pcache1Alloc(sz);
38191 }
38192
38193 /*
38194 ** Free an allocated buffer obtained from sqlcipher3PageMalloc().
38195 */
38196 SQLCIPHER_PRIVATE void sqlcipher3PageFree(void *p){
38197   pcache1Free(p);
38198 }
38199
38200
38201 /*
38202 ** Return true if it desirable to avoid allocating a new page cache
38203 ** entry.
38204 **
38205 ** If memory was allocated specifically to the page cache using
38206 ** SQLCIPHER_CONFIG_PAGECACHE but that memory has all been used, then
38207 ** it is desirable to avoid allocating a new page cache entry because
38208 ** presumably SQLCIPHER_CONFIG_PAGECACHE was suppose to be sufficient
38209 ** for all page cache needs and we should not need to spill the
38210 ** allocation onto the heap.
38211 **
38212 ** Or, the heap is used for all page cache memory put the heap is
38213 ** under memory pressure, then again it is desirable to avoid
38214 ** allocating a new page cache entry in order to avoid stressing
38215 ** the heap even further.
38216 */
38217 static int pcache1UnderMemoryPressure(PCache1 *pCache){
38218   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
38219     return pcache1.bUnderPressure;
38220   }else{
38221     return sqlcipher3HeapNearlyFull();
38222   }
38223 }
38224
38225 /******************************************************************************/
38226 /******** General Implementation Functions ************************************/
38227
38228 /*
38229 ** This function is used to resize the hash table used by the cache passed
38230 ** as the first argument.
38231 **
38232 ** The PCache mutex must be held when this function is called.
38233 */
38234 static int pcache1ResizeHash(PCache1 *p){
38235   PgHdr1 **apNew;
38236   unsigned int nNew;
38237   unsigned int i;
38238
38239   assert( sqlcipher3_mutex_held(p->pGroup->mutex) );
38240
38241   nNew = p->nHash*2;
38242   if( nNew<256 ){
38243     nNew = 256;
38244   }
38245
38246   pcache1LeaveMutex(p->pGroup);
38247   if( p->nHash ){ sqlcipher3BeginBenignMalloc(); }
38248   apNew = (PgHdr1 **)sqlcipher3_malloc(sizeof(PgHdr1 *)*nNew);
38249   if( p->nHash ){ sqlcipher3EndBenignMalloc(); }
38250   pcache1EnterMutex(p->pGroup);
38251   if( apNew ){
38252     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
38253     for(i=0; i<p->nHash; i++){
38254       PgHdr1 *pPage;
38255       PgHdr1 *pNext = p->apHash[i];
38256       while( (pPage = pNext)!=0 ){
38257         unsigned int h = pPage->iKey % nNew;
38258         pNext = pPage->pNext;
38259         pPage->pNext = apNew[h];
38260         apNew[h] = pPage;
38261       }
38262     }
38263     sqlcipher3_free(p->apHash);
38264     p->apHash = apNew;
38265     p->nHash = nNew;
38266   }
38267
38268   return (p->apHash ? SQLCIPHER_OK : SQLCIPHER_NOMEM);
38269 }
38270
38271 /*
38272 ** This function is used internally to remove the page pPage from the 
38273 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
38274 ** LRU list, then this function is a no-op.
38275 **
38276 ** The PGroup mutex must be held when this function is called.
38277 **
38278 ** If pPage is NULL then this routine is a no-op.
38279 */
38280 static void pcache1PinPage(PgHdr1 *pPage){
38281   PCache1 *pCache;
38282   PGroup *pGroup;
38283
38284   if( pPage==0 ) return;
38285   pCache = pPage->pCache;
38286   pGroup = pCache->pGroup;
38287   assert( sqlcipher3_mutex_held(pGroup->mutex) );
38288   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
38289     if( pPage->pLruPrev ){
38290       pPage->pLruPrev->pLruNext = pPage->pLruNext;
38291     }
38292     if( pPage->pLruNext ){
38293       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
38294     }
38295     if( pGroup->pLruHead==pPage ){
38296       pGroup->pLruHead = pPage->pLruNext;
38297     }
38298     if( pGroup->pLruTail==pPage ){
38299       pGroup->pLruTail = pPage->pLruPrev;
38300     }
38301     pPage->pLruNext = 0;
38302     pPage->pLruPrev = 0;
38303     pPage->pCache->nRecyclable--;
38304   }
38305 }
38306
38307
38308 /*
38309 ** Remove the page supplied as an argument from the hash table 
38310 ** (PCache1.apHash structure) that it is currently stored in.
38311 **
38312 ** The PGroup mutex must be held when this function is called.
38313 */
38314 static void pcache1RemoveFromHash(PgHdr1 *pPage){
38315   unsigned int h;
38316   PCache1 *pCache = pPage->pCache;
38317   PgHdr1 **pp;
38318
38319   assert( sqlcipher3_mutex_held(pCache->pGroup->mutex) );
38320   h = pPage->iKey % pCache->nHash;
38321   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
38322   *pp = (*pp)->pNext;
38323
38324   pCache->nPage--;
38325 }
38326
38327 /*
38328 ** If there are currently more than nMaxPage pages allocated, try
38329 ** to recycle pages to reduce the number allocated to nMaxPage.
38330 */
38331 static void pcache1EnforceMaxPage(PGroup *pGroup){
38332   assert( sqlcipher3_mutex_held(pGroup->mutex) );
38333   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
38334     PgHdr1 *p = pGroup->pLruTail;
38335     assert( p->pCache->pGroup==pGroup );
38336     pcache1PinPage(p);
38337     pcache1RemoveFromHash(p);
38338     pcache1FreePage(p);
38339   }
38340 }
38341
38342 /*
38343 ** Discard all pages from cache pCache with a page number (key value) 
38344 ** greater than or equal to iLimit. Any pinned pages that meet this 
38345 ** criteria are unpinned before they are discarded.
38346 **
38347 ** The PCache mutex must be held when this function is called.
38348 */
38349 static void pcache1TruncateUnsafe(
38350   PCache1 *pCache,             /* The cache to truncate */
38351   unsigned int iLimit          /* Drop pages with this pgno or larger */
38352 ){
38353   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
38354   unsigned int h;
38355   assert( sqlcipher3_mutex_held(pCache->pGroup->mutex) );
38356   for(h=0; h<pCache->nHash; h++){
38357     PgHdr1 **pp = &pCache->apHash[h]; 
38358     PgHdr1 *pPage;
38359     while( (pPage = *pp)!=0 ){
38360       if( pPage->iKey>=iLimit ){
38361         pCache->nPage--;
38362         *pp = pPage->pNext;
38363         pcache1PinPage(pPage);
38364         pcache1FreePage(pPage);
38365       }else{
38366         pp = &pPage->pNext;
38367         TESTONLY( nPage++; )
38368       }
38369     }
38370   }
38371   assert( pCache->nPage==nPage );
38372 }
38373
38374 /******************************************************************************/
38375 /******** sqlcipher3_pcache Methods **********************************************/
38376
38377 /*
38378 ** Implementation of the sqlcipher3_pcache.xInit method.
38379 */
38380 static int pcache1Init(void *NotUsed){
38381   UNUSED_PARAMETER(NotUsed);
38382   assert( pcache1.isInit==0 );
38383   memset(&pcache1, 0, sizeof(pcache1));
38384   if( sqlcipher3GlobalConfig.bCoreMutex ){
38385     pcache1.grp.mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_STATIC_LRU);
38386     pcache1.mutex = sqlcipher3_mutex_alloc(SQLCIPHER_MUTEX_STATIC_PMEM);
38387   }
38388   pcache1.grp.mxPinned = 10;
38389   pcache1.isInit = 1;
38390   return SQLCIPHER_OK;
38391 }
38392
38393 /*
38394 ** Implementation of the sqlcipher3_pcache.xShutdown method.
38395 ** Note that the static mutex allocated in xInit does 
38396 ** not need to be freed.
38397 */
38398 static void pcache1Shutdown(void *NotUsed){
38399   UNUSED_PARAMETER(NotUsed);
38400   assert( pcache1.isInit!=0 );
38401   memset(&pcache1, 0, sizeof(pcache1));
38402 }
38403
38404 /*
38405 ** Implementation of the sqlcipher3_pcache.xCreate method.
38406 **
38407 ** Allocate a new cache.
38408 */
38409 static sqlcipher3_pcache *pcache1Create(int szPage, int bPurgeable){
38410   PCache1 *pCache;      /* The newly created page cache */
38411   PGroup *pGroup;       /* The group the new page cache will belong to */
38412   int sz;               /* Bytes of memory required to allocate the new cache */
38413
38414   /*
38415   ** The seperateCache variable is true if each PCache has its own private
38416   ** PGroup.  In other words, separateCache is true for mode (1) where no
38417   ** mutexing is required.
38418   **
38419   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
38420   **
38421   **   *  Always use a unified cache in single-threaded applications
38422   **
38423   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38424   **      use separate caches (mode-1)
38425   */
38426 #if defined(SQLCIPHER_ENABLE_MEMORY_MANAGEMENT) || SQLCIPHER_THREADSAFE==0
38427   const int separateCache = 0;
38428 #else
38429   int separateCache = sqlcipher3GlobalConfig.bCoreMutex>0;
38430 #endif
38431
38432   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38433   pCache = (PCache1 *)sqlcipher3_malloc(sz);
38434   if( pCache ){
38435     memset(pCache, 0, sz);
38436     if( separateCache ){
38437       pGroup = (PGroup*)&pCache[1];
38438       pGroup->mxPinned = 10;
38439     }else{
38440       pGroup = &pcache1.grp;
38441     }
38442     pCache->pGroup = pGroup;
38443     pCache->szPage = szPage;
38444     pCache->bPurgeable = (bPurgeable ? 1 : 0);
38445     if( bPurgeable ){
38446       pCache->nMin = 10;
38447       pcache1EnterMutex(pGroup);
38448       pGroup->nMinPage += pCache->nMin;
38449       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38450       pcache1LeaveMutex(pGroup);
38451     }
38452   }
38453   return (sqlcipher3_pcache *)pCache;
38454 }
38455
38456 /*
38457 ** Implementation of the sqlcipher3_pcache.xCachesize method. 
38458 **
38459 ** Configure the cache_size limit for a cache.
38460 */
38461 static void pcache1Cachesize(sqlcipher3_pcache *p, int nMax){
38462   PCache1 *pCache = (PCache1 *)p;
38463   if( pCache->bPurgeable ){
38464     PGroup *pGroup = pCache->pGroup;
38465     pcache1EnterMutex(pGroup);
38466     pGroup->nMaxPage += (nMax - pCache->nMax);
38467     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38468     pCache->nMax = nMax;
38469     pCache->n90pct = pCache->nMax*9/10;
38470     pcache1EnforceMaxPage(pGroup);
38471     pcache1LeaveMutex(pGroup);
38472   }
38473 }
38474
38475 /*
38476 ** Implementation of the sqlcipher3_pcache.xPagecount method. 
38477 */
38478 static int pcache1Pagecount(sqlcipher3_pcache *p){
38479   int n;
38480   PCache1 *pCache = (PCache1*)p;
38481   pcache1EnterMutex(pCache->pGroup);
38482   n = pCache->nPage;
38483   pcache1LeaveMutex(pCache->pGroup);
38484   return n;
38485 }
38486
38487 /*
38488 ** Implementation of the sqlcipher3_pcache.xFetch method. 
38489 **
38490 ** Fetch a page by key value.
38491 **
38492 ** Whether or not a new page may be allocated by this function depends on
38493 ** the value of the createFlag argument.  0 means do not allocate a new
38494 ** page.  1 means allocate a new page if space is easily available.  2 
38495 ** means to try really hard to allocate a new page.
38496 **
38497 ** For a non-purgeable cache (a cache used as the storage for an in-memory
38498 ** database) there is really no difference between createFlag 1 and 2.  So
38499 ** the calling function (pcache.c) will never have a createFlag of 1 on
38500 ** a non-purgable cache.
38501 **
38502 ** There are three different approaches to obtaining space for a page,
38503 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38504 **
38505 **   1. Regardless of the value of createFlag, the cache is searched for a 
38506 **      copy of the requested page. If one is found, it is returned.
38507 **
38508 **   2. If createFlag==0 and the page is not already in the cache, NULL is
38509 **      returned.
38510 **
38511 **   3. If createFlag is 1, and the page is not already in the cache, then
38512 **      return NULL (do not allocate a new page) if any of the following
38513 **      conditions are true:
38514 **
38515 **       (a) the number of pages pinned by the cache is greater than
38516 **           PCache1.nMax, or
38517 **
38518 **       (b) the number of pages pinned by the cache is greater than
38519 **           the sum of nMax for all purgeable caches, less the sum of 
38520 **           nMin for all other purgeable caches, or
38521 **
38522 **   4. If none of the first three conditions apply and the cache is marked
38523 **      as purgeable, and if one of the following is true:
38524 **
38525 **       (a) The number of pages allocated for the cache is already 
38526 **           PCache1.nMax, or
38527 **
38528 **       (b) The number of pages allocated for all purgeable caches is
38529 **           already equal to or greater than the sum of nMax for all
38530 **           purgeable caches,
38531 **
38532 **       (c) The system is under memory pressure and wants to avoid
38533 **           unnecessary pages cache entry allocations
38534 **
38535 **      then attempt to recycle a page from the LRU list. If it is the right
38536 **      size, return the recycled buffer. Otherwise, free the buffer and
38537 **      proceed to step 5. 
38538 **
38539 **   5. Otherwise, allocate and return a new page buffer.
38540 */
38541 static void *pcache1Fetch(sqlcipher3_pcache *p, unsigned int iKey, int createFlag){
38542   int nPinned;
38543   PCache1 *pCache = (PCache1 *)p;
38544   PGroup *pGroup;
38545   PgHdr1 *pPage = 0;
38546
38547   assert( pCache->bPurgeable || createFlag!=1 );
38548   assert( pCache->bPurgeable || pCache->nMin==0 );
38549   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38550   assert( pCache->nMin==0 || pCache->bPurgeable );
38551   pcache1EnterMutex(pGroup = pCache->pGroup);
38552
38553   /* Step 1: Search the hash table for an existing entry. */
38554   if( pCache->nHash>0 ){
38555     unsigned int h = iKey % pCache->nHash;
38556     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38557   }
38558
38559   /* Step 2: Abort if no existing page is found and createFlag is 0 */
38560   if( pPage || createFlag==0 ){
38561     pcache1PinPage(pPage);
38562     goto fetch_out;
38563   }
38564
38565   /* The pGroup local variable will normally be initialized by the
38566   ** pcache1EnterMutex() macro above.  But if SQLCIPHER_MUTEX_OMIT is defined,
38567   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38568   ** local variable here.  Delaying the initialization of pGroup is an
38569   ** optimization:  The common case is to exit the module before reaching
38570   ** this point.
38571   */
38572 #ifdef SQLCIPHER_MUTEX_OMIT
38573   pGroup = pCache->pGroup;
38574 #endif
38575
38576
38577   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38578   nPinned = pCache->nPage - pCache->nRecyclable;
38579   assert( nPinned>=0 );
38580   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38581   assert( pCache->n90pct == pCache->nMax*9/10 );
38582   if( createFlag==1 && (
38583         nPinned>=pGroup->mxPinned
38584      || nPinned>=(int)pCache->n90pct
38585      || pcache1UnderMemoryPressure(pCache)
38586   )){
38587     goto fetch_out;
38588   }
38589
38590   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38591     goto fetch_out;
38592   }
38593
38594   /* Step 4. Try to recycle a page. */
38595   if( pCache->bPurgeable && pGroup->pLruTail && (
38596          (pCache->nPage+1>=pCache->nMax)
38597       || pGroup->nCurrentPage>=pGroup->nMaxPage
38598       || pcache1UnderMemoryPressure(pCache)
38599   )){
38600     PCache1 *pOtherCache;
38601     pPage = pGroup->pLruTail;
38602     pcache1RemoveFromHash(pPage);
38603     pcache1PinPage(pPage);
38604     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
38605       pcache1FreePage(pPage);
38606       pPage = 0;
38607     }else{
38608       pGroup->nCurrentPage -= 
38609                (pOtherCache->bPurgeable - pCache->bPurgeable);
38610     }
38611   }
38612
38613   /* Step 5. If a usable page buffer has still not been found, 
38614   ** attempt to allocate a new one. 
38615   */
38616   if( !pPage ){
38617     if( createFlag==1 ) sqlcipher3BeginBenignMalloc();
38618     pPage = pcache1AllocPage(pCache);
38619     if( createFlag==1 ) sqlcipher3EndBenignMalloc();
38620   }
38621
38622   if( pPage ){
38623     unsigned int h = iKey % pCache->nHash;
38624     pCache->nPage++;
38625     pPage->iKey = iKey;
38626     pPage->pNext = pCache->apHash[h];
38627     pPage->pCache = pCache;
38628     pPage->pLruPrev = 0;
38629     pPage->pLruNext = 0;
38630     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
38631     pCache->apHash[h] = pPage;
38632   }
38633
38634 fetch_out:
38635   if( pPage && iKey>pCache->iMaxKey ){
38636     pCache->iMaxKey = iKey;
38637   }
38638   pcache1LeaveMutex(pGroup);
38639   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
38640 }
38641
38642
38643 /*
38644 ** Implementation of the sqlcipher3_pcache.xUnpin method.
38645 **
38646 ** Mark a page as unpinned (eligible for asynchronous recycling).
38647 */
38648 static void pcache1Unpin(sqlcipher3_pcache *p, void *pPg, int reuseUnlikely){
38649   PCache1 *pCache = (PCache1 *)p;
38650   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
38651   PGroup *pGroup = pCache->pGroup;
38652  
38653   assert( pPage->pCache==pCache );
38654   pcache1EnterMutex(pGroup);
38655
38656   /* It is an error to call this function if the page is already 
38657   ** part of the PGroup LRU list.
38658   */
38659   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
38660   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
38661
38662   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
38663     pcache1RemoveFromHash(pPage);
38664     pcache1FreePage(pPage);
38665   }else{
38666     /* Add the page to the PGroup LRU list. */
38667     if( pGroup->pLruHead ){
38668       pGroup->pLruHead->pLruPrev = pPage;
38669       pPage->pLruNext = pGroup->pLruHead;
38670       pGroup->pLruHead = pPage;
38671     }else{
38672       pGroup->pLruTail = pPage;
38673       pGroup->pLruHead = pPage;
38674     }
38675     pCache->nRecyclable++;
38676   }
38677
38678   pcache1LeaveMutex(pCache->pGroup);
38679 }
38680
38681 /*
38682 ** Implementation of the sqlcipher3_pcache.xRekey method. 
38683 */
38684 static void pcache1Rekey(
38685   sqlcipher3_pcache *p,
38686   void *pPg,
38687   unsigned int iOld,
38688   unsigned int iNew
38689 ){
38690   PCache1 *pCache = (PCache1 *)p;
38691   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
38692   PgHdr1 **pp;
38693   unsigned int h; 
38694   assert( pPage->iKey==iOld );
38695   assert( pPage->pCache==pCache );
38696
38697   pcache1EnterMutex(pCache->pGroup);
38698
38699   h = iOld%pCache->nHash;
38700   pp = &pCache->apHash[h];
38701   while( (*pp)!=pPage ){
38702     pp = &(*pp)->pNext;
38703   }
38704   *pp = pPage->pNext;
38705
38706   h = iNew%pCache->nHash;
38707   pPage->iKey = iNew;
38708   pPage->pNext = pCache->apHash[h];
38709   pCache->apHash[h] = pPage;
38710   if( iNew>pCache->iMaxKey ){
38711     pCache->iMaxKey = iNew;
38712   }
38713
38714   pcache1LeaveMutex(pCache->pGroup);
38715 }
38716
38717 /*
38718 ** Implementation of the sqlcipher3_pcache.xTruncate method. 
38719 **
38720 ** Discard all unpinned pages in the cache with a page number equal to
38721 ** or greater than parameter iLimit. Any pinned pages with a page number
38722 ** equal to or greater than iLimit are implicitly unpinned.
38723 */
38724 static void pcache1Truncate(sqlcipher3_pcache *p, unsigned int iLimit){
38725   PCache1 *pCache = (PCache1 *)p;
38726   pcache1EnterMutex(pCache->pGroup);
38727   if( iLimit<=pCache->iMaxKey ){
38728     pcache1TruncateUnsafe(pCache, iLimit);
38729     pCache->iMaxKey = iLimit-1;
38730   }
38731   pcache1LeaveMutex(pCache->pGroup);
38732 }
38733
38734 /*
38735 ** Implementation of the sqlcipher3_pcache.xDestroy method. 
38736 **
38737 ** Destroy a cache allocated using pcache1Create().
38738 */
38739 static void pcache1Destroy(sqlcipher3_pcache *p){
38740   PCache1 *pCache = (PCache1 *)p;
38741   PGroup *pGroup = pCache->pGroup;
38742   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
38743   pcache1EnterMutex(pGroup);
38744   pcache1TruncateUnsafe(pCache, 0);
38745   pGroup->nMaxPage -= pCache->nMax;
38746   pGroup->nMinPage -= pCache->nMin;
38747   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38748   pcache1EnforceMaxPage(pGroup);
38749   pcache1LeaveMutex(pGroup);
38750   sqlcipher3_free(pCache->apHash);
38751   sqlcipher3_free(pCache);
38752 }
38753
38754 /*
38755 ** This function is called during initialization (sqlcipher3_initialize()) to
38756 ** install the default pluggable cache module, assuming the user has not
38757 ** already provided an alternative.
38758 */
38759 SQLCIPHER_PRIVATE void sqlcipher3PCacheSetDefault(void){
38760   static const sqlcipher3_pcache_methods defaultMethods = {
38761     0,                       /* pArg */
38762     pcache1Init,             /* xInit */
38763     pcache1Shutdown,         /* xShutdown */
38764     pcache1Create,           /* xCreate */
38765     pcache1Cachesize,        /* xCachesize */
38766     pcache1Pagecount,        /* xPagecount */
38767     pcache1Fetch,            /* xFetch */
38768     pcache1Unpin,            /* xUnpin */
38769     pcache1Rekey,            /* xRekey */
38770     pcache1Truncate,         /* xTruncate */
38771     pcache1Destroy           /* xDestroy */
38772   };
38773   sqlcipher3_config(SQLCIPHER_CONFIG_PCACHE, &defaultMethods);
38774 }
38775
38776 #ifdef SQLCIPHER_ENABLE_MEMORY_MANAGEMENT
38777 /*
38778 ** This function is called to free superfluous dynamically allocated memory
38779 ** held by the pager system. Memory in use by any SQLite pager allocated
38780 ** by the current thread may be sqlcipher3_free()ed.
38781 **
38782 ** nReq is the number of bytes of memory required. Once this much has
38783 ** been released, the function returns. The return value is the total number 
38784 ** of bytes of memory released.
38785 */
38786 SQLCIPHER_PRIVATE int sqlcipher3PcacheReleaseMemory(int nReq){
38787   int nFree = 0;
38788   assert( sqlcipher3_mutex_notheld(pcache1.grp.mutex) );
38789   assert( sqlcipher3_mutex_notheld(pcache1.mutex) );
38790   if( pcache1.pStart==0 ){
38791     PgHdr1 *p;
38792     pcache1EnterMutex(&pcache1.grp);
38793     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
38794       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
38795       pcache1PinPage(p);
38796       pcache1RemoveFromHash(p);
38797       pcache1FreePage(p);
38798     }
38799     pcache1LeaveMutex(&pcache1.grp);
38800   }
38801   return nFree;
38802 }
38803 #endif /* SQLCIPHER_ENABLE_MEMORY_MANAGEMENT */
38804
38805 #ifdef SQLCIPHER_TEST
38806 /*
38807 ** This function is used by test procedures to inspect the internal state
38808 ** of the global cache.
38809 */
38810 SQLCIPHER_PRIVATE void sqlcipher3PcacheStats(
38811   int *pnCurrent,      /* OUT: Total number of pages cached */
38812   int *pnMax,          /* OUT: Global maximum cache size */
38813   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
38814   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
38815 ){
38816   PgHdr1 *p;
38817   int nRecyclable = 0;
38818   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
38819     nRecyclable++;
38820   }
38821   *pnCurrent = pcache1.grp.nCurrentPage;
38822   *pnMax = pcache1.grp.nMaxPage;
38823   *pnMin = pcache1.grp.nMinPage;
38824   *pnRecyclable = nRecyclable;
38825 }
38826 #endif
38827
38828 /************** End of pcache1.c *********************************************/
38829 /************** Begin file rowset.c ******************************************/
38830 /*
38831 ** 2008 December 3
38832 **
38833 ** The author disclaims copyright to this source code.  In place of
38834 ** a legal notice, here is a blessing:
38835 **
38836 **    May you do good and not evil.
38837 **    May you find forgiveness for yourself and forgive others.
38838 **    May you share freely, never taking more than you give.
38839 **
38840 *************************************************************************
38841 **
38842 ** This module implements an object we call a "RowSet".
38843 **
38844 ** The RowSet object is a collection of rowids.  Rowids
38845 ** are inserted into the RowSet in an arbitrary order.  Inserts
38846 ** can be intermixed with tests to see if a given rowid has been
38847 ** previously inserted into the RowSet.
38848 **
38849 ** After all inserts are finished, it is possible to extract the
38850 ** elements of the RowSet in sorted order.  Once this extraction
38851 ** process has started, no new elements may be inserted.
38852 **
38853 ** Hence, the primitive operations for a RowSet are:
38854 **
38855 **    CREATE
38856 **    INSERT
38857 **    TEST
38858 **    SMALLEST
38859 **    DESTROY
38860 **
38861 ** The CREATE and DESTROY primitives are the constructor and destructor,
38862 ** obviously.  The INSERT primitive adds a new element to the RowSet.
38863 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
38864 ** extracts the least value from the RowSet.
38865 **
38866 ** The INSERT primitive might allocate additional memory.  Memory is
38867 ** allocated in chunks so most INSERTs do no allocation.  There is an 
38868 ** upper bound on the size of allocated memory.  No memory is freed
38869 ** until DESTROY.
38870 **
38871 ** The TEST primitive includes a "batch" number.  The TEST primitive
38872 ** will only see elements that were inserted before the last change
38873 ** in the batch number.  In other words, if an INSERT occurs between
38874 ** two TESTs where the TESTs have the same batch nubmer, then the
38875 ** value added by the INSERT will not be visible to the second TEST.
38876 ** The initial batch number is zero, so if the very first TEST contains
38877 ** a non-zero batch number, it will see all prior INSERTs.
38878 **
38879 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
38880 ** that is attempted.
38881 **
38882 ** The cost of an INSERT is roughly constant.  (Sometime new memory
38883 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
38884 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
38885 ** The cost of a TEST using the same batch number is O(logN).  The cost
38886 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
38887 ** primitives are constant time.  The cost of DESTROY is O(N).
38888 **
38889 ** There is an added cost of O(N) when switching between TEST and
38890 ** SMALLEST primitives.
38891 */
38892
38893
38894 /*
38895 ** Target size for allocation chunks.
38896 */
38897 #define ROWSET_ALLOCATION_SIZE 1024
38898
38899 /*
38900 ** The number of rowset entries per allocation chunk.
38901 */
38902 #define ROWSET_ENTRY_PER_CHUNK  \
38903                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
38904
38905 /*
38906 ** Each entry in a RowSet is an instance of the following object.
38907 */
38908 struct RowSetEntry {            
38909   i64 v;                        /* ROWID value for this entry */
38910   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
38911   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
38912 };
38913
38914 /*
38915 ** RowSetEntry objects are allocated in large chunks (instances of the
38916 ** following structure) to reduce memory allocation overhead.  The
38917 ** chunks are kept on a linked list so that they can be deallocated
38918 ** when the RowSet is destroyed.
38919 */
38920 struct RowSetChunk {
38921   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
38922   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
38923 };
38924
38925 /*
38926 ** A RowSet in an instance of the following structure.
38927 **
38928 ** A typedef of this structure if found in sqlcipherInt.h.
38929 */
38930 struct RowSet {
38931   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
38932   sqlcipher3 *db;                   /* The database connection */
38933   struct RowSetEntry *pEntry;    /* List of entries using pRight */
38934   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
38935   struct RowSetEntry *pFresh;    /* Source of new entry objects */
38936   struct RowSetEntry *pTree;     /* Binary tree of entries */
38937   u16 nFresh;                    /* Number of objects on pFresh */
38938   u8 isSorted;                   /* True if pEntry is sorted */
38939   u8 iBatch;                     /* Current insert batch */
38940 };
38941
38942 /*
38943 ** Turn bulk memory into a RowSet object.  N bytes of memory
38944 ** are available at pSpace.  The db pointer is used as a memory context
38945 ** for any subsequent allocations that need to occur.
38946 ** Return a pointer to the new RowSet object.
38947 **
38948 ** It must be the case that N is sufficient to make a Rowset.  If not
38949 ** an assertion fault occurs.
38950 ** 
38951 ** If N is larger than the minimum, use the surplus as an initial
38952 ** allocation of entries available to be filled.
38953 */
38954 SQLCIPHER_PRIVATE RowSet *sqlcipher3RowSetInit(sqlcipher3 *db, void *pSpace, unsigned int N){
38955   RowSet *p;
38956   assert( N >= ROUND8(sizeof(*p)) );
38957   p = pSpace;
38958   p->pChunk = 0;
38959   p->db = db;
38960   p->pEntry = 0;
38961   p->pLast = 0;
38962   p->pTree = 0;
38963   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
38964   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38965   p->isSorted = 1;
38966   p->iBatch = 0;
38967   return p;
38968 }
38969
38970 /*
38971 ** Deallocate all chunks from a RowSet.  This frees all memory that
38972 ** the RowSet has allocated over its lifetime.  This routine is
38973 ** the destructor for the RowSet.
38974 */
38975 SQLCIPHER_PRIVATE void sqlcipher3RowSetClear(RowSet *p){
38976   struct RowSetChunk *pChunk, *pNextChunk;
38977   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38978     pNextChunk = pChunk->pNextChunk;
38979     sqlcipher3DbFree(p->db, pChunk);
38980   }
38981   p->pChunk = 0;
38982   p->nFresh = 0;
38983   p->pEntry = 0;
38984   p->pLast = 0;
38985   p->pTree = 0;
38986   p->isSorted = 1;
38987 }
38988
38989 /*
38990 ** Insert a new value into a RowSet.
38991 **
38992 ** The mallocFailed flag of the database connection is set if a
38993 ** memory allocation fails.
38994 */
38995 SQLCIPHER_PRIVATE void sqlcipher3RowSetInsert(RowSet *p, i64 rowid){
38996   struct RowSetEntry *pEntry;  /* The new entry */
38997   struct RowSetEntry *pLast;   /* The last prior entry */
38998   assert( p!=0 );
38999   if( p->nFresh==0 ){
39000     struct RowSetChunk *pNew;
39001     pNew = sqlcipher3DbMallocRaw(p->db, sizeof(*pNew));
39002     if( pNew==0 ){
39003       return;
39004     }
39005     pNew->pNextChunk = p->pChunk;
39006     p->pChunk = pNew;
39007     p->pFresh = pNew->aEntry;
39008     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
39009   }
39010   pEntry = p->pFresh++;
39011   p->nFresh--;
39012   pEntry->v = rowid;
39013   pEntry->pRight = 0;
39014   pLast = p->pLast;
39015   if( pLast ){
39016     if( p->isSorted && rowid<=pLast->v ){
39017       p->isSorted = 0;
39018     }
39019     pLast->pRight = pEntry;
39020   }else{
39021     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
39022     p->pEntry = pEntry;
39023   }
39024   p->pLast = pEntry;
39025 }
39026
39027 /*
39028 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
39029 **
39030 ** The input lists are connected via pRight pointers and are 
39031 ** assumed to each already be in sorted order.
39032 */
39033 static struct RowSetEntry *rowSetMerge(
39034   struct RowSetEntry *pA,    /* First sorted list to be merged */
39035   struct RowSetEntry *pB     /* Second sorted list to be merged */
39036 ){
39037   struct RowSetEntry head;
39038   struct RowSetEntry *pTail;
39039
39040   pTail = &head;
39041   while( pA && pB ){
39042     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39043     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
39044     if( pA->v<pB->v ){
39045       pTail->pRight = pA;
39046       pA = pA->pRight;
39047       pTail = pTail->pRight;
39048     }else if( pB->v<pA->v ){
39049       pTail->pRight = pB;
39050       pB = pB->pRight;
39051       pTail = pTail->pRight;
39052     }else{
39053       pA = pA->pRight;
39054     }
39055   }
39056   if( pA ){
39057     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39058     pTail->pRight = pA;
39059   }else{
39060     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
39061     pTail->pRight = pB;
39062   }
39063   return head.pRight;
39064 }
39065
39066 /*
39067 ** Sort all elements on the pEntry list of the RowSet into ascending order.
39068 */ 
39069 static void rowSetSort(RowSet *p){
39070   unsigned int i;
39071   struct RowSetEntry *pEntry;
39072   struct RowSetEntry *aBucket[40];
39073
39074   assert( p->isSorted==0 );
39075   memset(aBucket, 0, sizeof(aBucket));
39076   while( p->pEntry ){
39077     pEntry = p->pEntry;
39078     p->pEntry = pEntry->pRight;
39079     pEntry->pRight = 0;
39080     for(i=0; aBucket[i]; i++){
39081       pEntry = rowSetMerge(aBucket[i], pEntry);
39082       aBucket[i] = 0;
39083     }
39084     aBucket[i] = pEntry;
39085   }
39086   pEntry = 0;
39087   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
39088     pEntry = rowSetMerge(pEntry, aBucket[i]);
39089   }
39090   p->pEntry = pEntry;
39091   p->pLast = 0;
39092   p->isSorted = 1;
39093 }
39094
39095
39096 /*
39097 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
39098 ** Convert this tree into a linked list connected by the pRight pointers
39099 ** and return pointers to the first and last elements of the new list.
39100 */
39101 static void rowSetTreeToList(
39102   struct RowSetEntry *pIn,         /* Root of the input tree */
39103   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
39104   struct RowSetEntry **ppLast      /* Write tail of the output list here */
39105 ){
39106   assert( pIn!=0 );
39107   if( pIn->pLeft ){
39108     struct RowSetEntry *p;
39109     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
39110     p->pRight = pIn;
39111   }else{
39112     *ppFirst = pIn;
39113   }
39114   if( pIn->pRight ){
39115     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
39116   }else{
39117     *ppLast = pIn;
39118   }
39119   assert( (*ppLast)->pRight==0 );
39120 }
39121
39122
39123 /*
39124 ** Convert a sorted list of elements (connected by pRight) into a binary
39125 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
39126 ** node taken from the head of *ppList.  A depth of 2 means a tree with
39127 ** three nodes.  And so forth.
39128 **
39129 ** Use as many entries from the input list as required and update the
39130 ** *ppList to point to the unused elements of the list.  If the input
39131 ** list contains too few elements, then construct an incomplete tree
39132 ** and leave *ppList set to NULL.
39133 **
39134 ** Return a pointer to the root of the constructed binary tree.
39135 */
39136 static struct RowSetEntry *rowSetNDeepTree(
39137   struct RowSetEntry **ppList,
39138   int iDepth
39139 ){
39140   struct RowSetEntry *p;         /* Root of the new tree */
39141   struct RowSetEntry *pLeft;     /* Left subtree */
39142   if( *ppList==0 ){
39143     return 0;
39144   }
39145   if( iDepth==1 ){
39146     p = *ppList;
39147     *ppList = p->pRight;
39148     p->pLeft = p->pRight = 0;
39149     return p;
39150   }
39151   pLeft = rowSetNDeepTree(ppList, iDepth-1);
39152   p = *ppList;
39153   if( p==0 ){
39154     return pLeft;
39155   }
39156   p->pLeft = pLeft;
39157   *ppList = p->pRight;
39158   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
39159   return p;
39160 }
39161
39162 /*
39163 ** Convert a sorted list of elements into a binary tree. Make the tree
39164 ** as deep as it needs to be in order to contain the entire list.
39165 */
39166 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
39167   int iDepth;           /* Depth of the tree so far */
39168   struct RowSetEntry *p;       /* Current tree root */
39169   struct RowSetEntry *pLeft;   /* Left subtree */
39170
39171   assert( pList!=0 );
39172   p = pList;
39173   pList = p->pRight;
39174   p->pLeft = p->pRight = 0;
39175   for(iDepth=1; pList; iDepth++){
39176     pLeft = p;
39177     p = pList;
39178     pList = p->pRight;
39179     p->pLeft = pLeft;
39180     p->pRight = rowSetNDeepTree(&pList, iDepth);
39181   }
39182   return p;
39183 }
39184
39185 /*
39186 ** Convert the list in p->pEntry into a sorted list if it is not
39187 ** sorted already.  If there is a binary tree on p->pTree, then
39188 ** convert it into a list too and merge it into the p->pEntry list.
39189 */
39190 static void rowSetToList(RowSet *p){
39191   if( !p->isSorted ){
39192     rowSetSort(p);
39193   }
39194   if( p->pTree ){
39195     struct RowSetEntry *pHead, *pTail;
39196     rowSetTreeToList(p->pTree, &pHead, &pTail);
39197     p->pTree = 0;
39198     p->pEntry = rowSetMerge(p->pEntry, pHead);
39199   }
39200 }
39201
39202 /*
39203 ** Extract the smallest element from the RowSet.
39204 ** Write the element into *pRowid.  Return 1 on success.  Return
39205 ** 0 if the RowSet is already empty.
39206 **
39207 ** After this routine has been called, the sqlcipher3RowSetInsert()
39208 ** routine may not be called again.  
39209 */
39210 SQLCIPHER_PRIVATE int sqlcipher3RowSetNext(RowSet *p, i64 *pRowid){
39211   rowSetToList(p);
39212   if( p->pEntry ){
39213     *pRowid = p->pEntry->v;
39214     p->pEntry = p->pEntry->pRight;
39215     if( p->pEntry==0 ){
39216       sqlcipher3RowSetClear(p);
39217     }
39218     return 1;
39219   }else{
39220     return 0;
39221   }
39222 }
39223
39224 /*
39225 ** Check to see if element iRowid was inserted into the the rowset as
39226 ** part of any insert batch prior to iBatch.  Return 1 or 0.
39227 */
39228 SQLCIPHER_PRIVATE int sqlcipher3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlcipher3_int64 iRowid){
39229   struct RowSetEntry *p;
39230   if( iBatch!=pRowSet->iBatch ){
39231     if( pRowSet->pEntry ){
39232       rowSetToList(pRowSet);
39233       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
39234       pRowSet->pEntry = 0;
39235       pRowSet->pLast = 0;
39236     }
39237     pRowSet->iBatch = iBatch;
39238   }
39239   p = pRowSet->pTree;
39240   while( p ){
39241     if( p->v<iRowid ){
39242       p = p->pRight;
39243     }else if( p->v>iRowid ){
39244       p = p->pLeft;
39245     }else{
39246       return 1;
39247     }
39248   }
39249   return 0;
39250 }
39251
39252 /************** End of rowset.c **********************************************/
39253 /************** Begin file pager.c *******************************************/
39254 /*
39255 ** 2001 September 15
39256 **
39257 ** The author disclaims copyright to this source code.  In place of
39258 ** a legal notice, here is a blessing:
39259 **
39260 **    May you do good and not evil.
39261 **    May you find forgiveness for yourself and forgive others.
39262 **    May you share freely, never taking more than you give.
39263 **
39264 *************************************************************************
39265 ** This is the implementation of the page cache subsystem or "pager".
39266 ** 
39267 ** The pager is used to access a database disk file.  It implements
39268 ** atomic commit and rollback through the use of a journal file that
39269 ** is separate from the database file.  The pager also implements file
39270 ** locking to prevent two processes from writing the same database
39271 ** file simultaneously, or one process from reading the database while
39272 ** another is writing.
39273 */
39274 #ifndef SQLCIPHER_OMIT_DISKIO
39275 /************** Include wal.h in the middle of pager.c ***********************/
39276 /************** Begin file wal.h *********************************************/
39277 /*
39278 ** 2010 February 1
39279 **
39280 ** The author disclaims copyright to this source code.  In place of
39281 ** a legal notice, here is a blessing:
39282 **
39283 **    May you do good and not evil.
39284 **    May you find forgiveness for yourself and forgive others.
39285 **    May you share freely, never taking more than you give.
39286 **
39287 *************************************************************************
39288 ** This header file defines the interface to the write-ahead logging 
39289 ** system. Refer to the comments below and the header comment attached to 
39290 ** the implementation of each function in log.c for further details.
39291 */
39292
39293 #ifndef _WAL_H_
39294 #define _WAL_H_
39295
39296
39297 #ifdef SQLCIPHER_OMIT_WAL
39298 # define sqlcipher3WalOpen(x,y,z)                   0
39299 # define sqlcipher3WalLimit(x,y)
39300 # define sqlcipher3WalClose(w,x,y,z)                0
39301 # define sqlcipher3WalBeginReadTransaction(y,z)     0
39302 # define sqlcipher3WalEndReadTransaction(z)
39303 # define sqlcipher3WalRead(v,w,x,y,z)               0
39304 # define sqlcipher3WalDbsize(y)                     0
39305 # define sqlcipher3WalBeginWriteTransaction(y)      0
39306 # define sqlcipher3WalEndWriteTransaction(x)        0
39307 # define sqlcipher3WalUndo(x,y,z)                   0
39308 # define sqlcipher3WalSavepoint(y,z)
39309 # define sqlcipher3WalSavepointUndo(y,z)            0
39310 # define sqlcipher3WalFrames(u,v,w,x,y,z)           0
39311 # define sqlcipher3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39312 # define sqlcipher3WalCallback(z)                   0
39313 # define sqlcipher3WalExclusiveMode(y,z)            0
39314 # define sqlcipher3WalHeapMemory(z)                 0
39315 #else
39316
39317 #define WAL_SAVEPOINT_NDATA 4
39318
39319 /* Connection to a write-ahead log (WAL) file. 
39320 ** There is one object of this type for each pager. 
39321 */
39322 typedef struct Wal Wal;
39323
39324 /* Open and close a connection to a write-ahead log. */
39325 SQLCIPHER_PRIVATE int sqlcipher3WalOpen(sqlcipher3_vfs*, sqlcipher3_file*, const char *, int, i64, Wal**);
39326 SQLCIPHER_PRIVATE int sqlcipher3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39327
39328 /* Set the limiting size of a WAL file. */
39329 SQLCIPHER_PRIVATE void sqlcipher3WalLimit(Wal*, i64);
39330
39331 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
39332 ** snapshot is like a read-transaction.  It is the state of the database
39333 ** at an instant in time.  sqlcipher3WalOpenSnapshot gets a read lock and
39334 ** preserves the current state even if the other threads or processes
39335 ** write to or checkpoint the WAL.  sqlcipher3WalCloseSnapshot() closes the
39336 ** transaction and releases the lock.
39337 */
39338 SQLCIPHER_PRIVATE int sqlcipher3WalBeginReadTransaction(Wal *pWal, int *);
39339 SQLCIPHER_PRIVATE void sqlcipher3WalEndReadTransaction(Wal *pWal);
39340
39341 /* Read a page from the write-ahead log, if it is present. */
39342 SQLCIPHER_PRIVATE int sqlcipher3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
39343
39344 /* If the WAL is not empty, return the size of the database. */
39345 SQLCIPHER_PRIVATE Pgno sqlcipher3WalDbsize(Wal *pWal);
39346
39347 /* Obtain or release the WRITER lock. */
39348 SQLCIPHER_PRIVATE int sqlcipher3WalBeginWriteTransaction(Wal *pWal);
39349 SQLCIPHER_PRIVATE int sqlcipher3WalEndWriteTransaction(Wal *pWal);
39350
39351 /* Undo any frames written (but not committed) to the log */
39352 SQLCIPHER_PRIVATE int sqlcipher3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39353
39354 /* Return an integer that records the current (uncommitted) write
39355 ** position in the WAL */
39356 SQLCIPHER_PRIVATE void sqlcipher3WalSavepoint(Wal *pWal, u32 *aWalData);
39357
39358 /* Move the write position of the WAL back to iFrame.  Called in
39359 ** response to a ROLLBACK TO command. */
39360 SQLCIPHER_PRIVATE int sqlcipher3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39361
39362 /* Write a frame or frames to the log. */
39363 SQLCIPHER_PRIVATE int sqlcipher3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39364
39365 /* Copy pages from the log to the database file */ 
39366 SQLCIPHER_PRIVATE int sqlcipher3WalCheckpoint(
39367   Wal *pWal,                      /* Write-ahead log connection */
39368   int eMode,                      /* One of PASSIVE, FULL and RESTART */
39369   int (*xBusy)(void*),            /* Function to call when busy */
39370   void *pBusyArg,                 /* Context argument for xBusyHandler */
39371   int sync_flags,                 /* Flags to sync db file with (or 0) */
39372   int nBuf,                       /* Size of buffer nBuf */
39373   u8 *zBuf,                       /* Temporary buffer to use */
39374   int *pnLog,                     /* OUT: Number of frames in WAL */
39375   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
39376 );
39377
39378 /* Return the value to pass to a sqlcipher3_wal_hook callback, the
39379 ** number of frames in the WAL at the point of the last commit since
39380 ** sqlcipher3WalCallback() was called.  If no commits have occurred since
39381 ** the last call, then return 0.
39382 */
39383 SQLCIPHER_PRIVATE int sqlcipher3WalCallback(Wal *pWal);
39384
39385 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39386 ** by the pager layer on the database file.
39387 */
39388 SQLCIPHER_PRIVATE int sqlcipher3WalExclusiveMode(Wal *pWal, int op);
39389
39390 /* Return true if the argument is non-NULL and the WAL module is using
39391 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39392 ** WAL module is using shared-memory, return false. 
39393 */
39394 SQLCIPHER_PRIVATE int sqlcipher3WalHeapMemory(Wal *pWal);
39395
39396 #endif /* ifndef SQLCIPHER_OMIT_WAL */
39397 #endif /* _WAL_H_ */
39398
39399 /************** End of wal.h *************************************************/
39400 /************** Continuing where we left off in pager.c **********************/
39401
39402
39403 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
39404 **
39405 ** This comment block describes invariants that hold when using a rollback
39406 ** journal.  These invariants do not apply for journal_mode=WAL,
39407 ** journal_mode=MEMORY, or journal_mode=OFF.
39408 **
39409 ** Within this comment block, a page is deemed to have been synced
39410 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
39411 ** Otherwise, the page is not synced until the xSync method of the VFS
39412 ** is called successfully on the file containing the page.
39413 **
39414 ** Definition:  A page of the database file is said to be "overwriteable" if
39415 ** one or more of the following are true about the page:
39416 ** 
39417 **     (a)  The original content of the page as it was at the beginning of
39418 **          the transaction has been written into the rollback journal and
39419 **          synced.
39420 ** 
39421 **     (b)  The page was a freelist leaf page at the start of the transaction.
39422 ** 
39423 **     (c)  The page number is greater than the largest page that existed in
39424 **          the database file at the start of the transaction.
39425 ** 
39426 ** (1) A page of the database file is never overwritten unless one of the
39427 **     following are true:
39428 ** 
39429 **     (a) The page and all other pages on the same sector are overwriteable.
39430 ** 
39431 **     (b) The atomic page write optimization is enabled, and the entire
39432 **         transaction other than the update of the transaction sequence
39433 **         number consists of a single page change.
39434 ** 
39435 ** (2) The content of a page written into the rollback journal exactly matches
39436 **     both the content in the database when the rollback journal was written
39437 **     and the content in the database at the beginning of the current
39438 **     transaction.
39439 ** 
39440 ** (3) Writes to the database file are an integer multiple of the page size
39441 **     in length and are aligned on a page boundary.
39442 ** 
39443 ** (4) Reads from the database file are either aligned on a page boundary and
39444 **     an integer multiple of the page size in length or are taken from the
39445 **     first 100 bytes of the database file.
39446 ** 
39447 ** (5) All writes to the database file are synced prior to the rollback journal
39448 **     being deleted, truncated, or zeroed.
39449 ** 
39450 ** (6) If a master journal file is used, then all writes to the database file
39451 **     are synced prior to the master journal being deleted.
39452 ** 
39453 ** Definition: Two databases (or the same database at two points it time)
39454 ** are said to be "logically equivalent" if they give the same answer to
39455 ** all queries.  Note in particular the the content of freelist leaf
39456 ** pages can be changed arbitarily without effecting the logical equivalence
39457 ** of the database.
39458 ** 
39459 ** (7) At any time, if any subset, including the empty set and the total set,
39460 **     of the unsynced changes to a rollback journal are removed and the 
39461 **     journal is rolled back, the resulting database file will be logical
39462 **     equivalent to the database file at the beginning of the transaction.
39463 ** 
39464 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
39465 **     is called to restore the database file to the same size it was at
39466 **     the beginning of the transaction.  (In some VFSes, the xTruncate
39467 **     method is a no-op, but that does not change the fact the SQLite will
39468 **     invoke it.)
39469 ** 
39470 ** (9) Whenever the database file is modified, at least one bit in the range
39471 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
39472 **     the EXCLUSIVE lock, thus signaling other connections on the same
39473 **     database to flush their caches.
39474 **
39475 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39476 **      than one billion transactions.
39477 **
39478 ** (11) A database file is well-formed at the beginning and at the conclusion
39479 **      of every transaction.
39480 **
39481 ** (12) An EXCLUSIVE lock is held on the database file when writing to
39482 **      the database file.
39483 **
39484 ** (13) A SHARED lock is held on the database file while reading any
39485 **      content out of the database file.
39486 **
39487 ******************************************************************************/
39488
39489 /*
39490 ** Macros for troubleshooting.  Normally turned off
39491 */
39492 #if 0
39493 int sqlcipher3PagerTrace=1;  /* True to enable tracing */
39494 #define sqlcipher3DebugPrintf printf
39495 #define PAGERTRACE(X)     if( sqlcipher3PagerTrace ){ sqlcipher3DebugPrintf X; }
39496 #else
39497 #define PAGERTRACE(X)
39498 #endif
39499
39500 /*
39501 ** The following two macros are used within the PAGERTRACE() macros above
39502 ** to print out file-descriptors. 
39503 **
39504 ** PAGERID() takes a pointer to a Pager struct as its argument. The
39505 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlcipher3_file
39506 ** struct as its argument.
39507 */
39508 #define PAGERID(p) ((int)(p->fd))
39509 #define FILEHANDLEID(fd) ((int)fd)
39510
39511 /*
39512 ** The Pager.eState variable stores the current 'state' of a pager. A
39513 ** pager may be in any one of the seven states shown in the following
39514 ** state diagram.
39515 **
39516 **                            OPEN <------+------+
39517 **                              |         |      |
39518 **                              V         |      |
39519 **               +---------> READER-------+      |
39520 **               |              |                |
39521 **               |              V                |
39522 **               |<-------WRITER_LOCKED------> ERROR
39523 **               |              |                ^  
39524 **               |              V                |
39525 **               |<------WRITER_CACHEMOD-------->|
39526 **               |              |                |
39527 **               |              V                |
39528 **               |<-------WRITER_DBMOD---------->|
39529 **               |              |                |
39530 **               |              V                |
39531 **               +<------WRITER_FINISHED-------->+
39532 **
39533 **
39534 ** List of state transitions and the C [function] that performs each:
39535 ** 
39536 **   OPEN              -> READER              [sqlcipher3PagerSharedLock]
39537 **   READER            -> OPEN                [pager_unlock]
39538 **
39539 **   READER            -> WRITER_LOCKED       [sqlcipher3PagerBegin]
39540 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
39541 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
39542 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlcipher3PagerCommitPhaseOne]
39543 **   WRITER_***        -> READER              [pager_end_transaction]
39544 **
39545 **   WRITER_***        -> ERROR               [pager_error]
39546 **   ERROR             -> OPEN                [pager_unlock]
39547 ** 
39548 **
39549 **  OPEN:
39550 **
39551 **    The pager starts up in this state. Nothing is guaranteed in this
39552 **    state - the file may or may not be locked and the database size is
39553 **    unknown. The database may not be read or written.
39554 **
39555 **    * No read or write transaction is active.
39556 **    * Any lock, or no lock at all, may be held on the database file.
39557 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
39558 **
39559 **  READER:
39560 **
39561 **    In this state all the requirements for reading the database in 
39562 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
39563 **    was) in exclusive-locking mode, a user-level read transaction is 
39564 **    open. The database size is known in this state.
39565 **
39566 **    A connection running with locking_mode=normal enters this state when
39567 **    it opens a read-transaction on the database and returns to state
39568 **    OPEN after the read-transaction is completed. However a connection
39569 **    running in locking_mode=exclusive (including temp databases) remains in
39570 **    this state even after the read-transaction is closed. The only way
39571 **    a locking_mode=exclusive connection can transition from READER to OPEN
39572 **    is via the ERROR state (see below).
39573 ** 
39574 **    * A read transaction may be active (but a write-transaction cannot).
39575 **    * A SHARED or greater lock is held on the database file.
39576 **    * The dbSize variable may be trusted (even if a user-level read 
39577 **      transaction is not active). The dbOrigSize and dbFileSize variables
39578 **      may not be trusted at this point.
39579 **    * If the database is a WAL database, then the WAL connection is open.
39580 **    * Even if a read-transaction is not open, it is guaranteed that 
39581 **      there is no hot-journal in the file-system.
39582 **
39583 **  WRITER_LOCKED:
39584 **
39585 **    The pager moves to this state from READER when a write-transaction
39586 **    is first opened on the database. In WRITER_LOCKED state, all locks 
39587 **    required to start a write-transaction are held, but no actual 
39588 **    modifications to the cache or database have taken place.
39589 **
39590 **    In rollback mode, a RESERVED or (if the transaction was opened with 
39591 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
39592 **    moving to this state, but the journal file is not written to or opened 
39593 **    to in this state. If the transaction is committed or rolled back while 
39594 **    in WRITER_LOCKED state, all that is required is to unlock the database 
39595 **    file.
39596 **
39597 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
39598 **    If the connection is running with locking_mode=exclusive, an attempt
39599 **    is made to obtain an EXCLUSIVE lock on the database file.
39600 **
39601 **    * A write transaction is active.
39602 **    * If the connection is open in rollback-mode, a RESERVED or greater 
39603 **      lock is held on the database file.
39604 **    * If the connection is open in WAL-mode, a WAL write transaction
39605 **      is open (i.e. sqlcipher3WalBeginWriteTransaction() has been successfully
39606 **      called).
39607 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
39608 **    * The contents of the pager cache have not been modified.
39609 **    * The journal file may or may not be open.
39610 **    * Nothing (not even the first header) has been written to the journal.
39611 **
39612 **  WRITER_CACHEMOD:
39613 **
39614 **    A pager moves from WRITER_LOCKED state to this state when a page is
39615 **    first modified by the upper layer. In rollback mode the journal file
39616 **    is opened (if it is not already open) and a header written to the
39617 **    start of it. The database file on disk has not been modified.
39618 **
39619 **    * A write transaction is active.
39620 **    * A RESERVED or greater lock is held on the database file.
39621 **    * The journal file is open and the first header has been written 
39622 **      to it, but the header has not been synced to disk.
39623 **    * The contents of the page cache have been modified.
39624 **
39625 **  WRITER_DBMOD:
39626 **
39627 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
39628 **    when it modifies the contents of the database file. WAL connections
39629 **    never enter this state (since they do not modify the database file,
39630 **    just the log file).
39631 **
39632 **    * A write transaction is active.
39633 **    * An EXCLUSIVE or greater lock is held on the database file.
39634 **    * The journal file is open and the first header has been written 
39635 **      and synced to disk.
39636 **    * The contents of the page cache have been modified (and possibly
39637 **      written to disk).
39638 **
39639 **  WRITER_FINISHED:
39640 **
39641 **    It is not possible for a WAL connection to enter this state.
39642 **
39643 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
39644 **    state after the entire transaction has been successfully written into the
39645 **    database file. In this state the transaction may be committed simply
39646 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
39647 **    not possible to modify the database further. At this point, the upper 
39648 **    layer must either commit or rollback the transaction.
39649 **
39650 **    * A write transaction is active.
39651 **    * An EXCLUSIVE or greater lock is held on the database file.
39652 **    * All writing and syncing of journal and database data has finished.
39653 **      If no error occured, all that remains is to finalize the journal to
39654 **      commit the transaction. If an error did occur, the caller will need
39655 **      to rollback the transaction. 
39656 **
39657 **  ERROR:
39658 **
39659 **    The ERROR state is entered when an IO or disk-full error (including
39660 **    SQLCIPHER_IOERR_NOMEM) occurs at a point in the code that makes it 
39661 **    difficult to be sure that the in-memory pager state (cache contents, 
39662 **    db size etc.) are consistent with the contents of the file-system.
39663 **
39664 **    Temporary pager files may enter the ERROR state, but in-memory pagers
39665 **    cannot.
39666 **
39667 **    For example, if an IO error occurs while performing a rollback, 
39668 **    the contents of the page-cache may be left in an inconsistent state.
39669 **    At this point it would be dangerous to change back to READER state
39670 **    (as usually happens after a rollback). Any subsequent readers might
39671 **    report database corruption (due to the inconsistent cache), and if
39672 **    they upgrade to writers, they may inadvertently corrupt the database
39673 **    file. To avoid this hazard, the pager switches into the ERROR state
39674 **    instead of READER following such an error.
39675 **
39676 **    Once it has entered the ERROR state, any attempt to use the pager
39677 **    to read or write data returns an error. Eventually, once all 
39678 **    outstanding transactions have been abandoned, the pager is able to
39679 **    transition back to OPEN state, discarding the contents of the 
39680 **    page-cache and any other in-memory state at the same time. Everything
39681 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
39682 **    when a read-transaction is next opened on the pager (transitioning
39683 **    the pager into READER state). At that point the system has recovered 
39684 **    from the error.
39685 **
39686 **    Specifically, the pager jumps into the ERROR state if:
39687 **
39688 **      1. An error occurs while attempting a rollback. This happens in
39689 **         function sqlcipher3PagerRollback().
39690 **
39691 **      2. An error occurs while attempting to finalize a journal file
39692 **         following a commit in function sqlcipher3PagerCommitPhaseTwo().
39693 **
39694 **      3. An error occurs while attempting to write to the journal or
39695 **         database file in function pagerStress() in order to free up
39696 **         memory.
39697 **
39698 **    In other cases, the error is returned to the b-tree layer. The b-tree
39699 **    layer then attempts a rollback operation. If the error condition 
39700 **    persists, the pager enters the ERROR state via condition (1) above.
39701 **
39702 **    Condition (3) is necessary because it can be triggered by a read-only
39703 **    statement executed within a transaction. In this case, if the error
39704 **    code were simply returned to the user, the b-tree layer would not
39705 **    automatically attempt a rollback, as it assumes that an error in a
39706 **    read-only statement cannot leave the pager in an internally inconsistent 
39707 **    state.
39708 **
39709 **    * The Pager.errCode variable is set to something other than SQLCIPHER_OK.
39710 **    * There are one or more outstanding references to pages (after the
39711 **      last reference is dropped the pager should move back to OPEN state).
39712 **    * The pager is not an in-memory pager.
39713 **    
39714 **
39715 ** Notes:
39716 **
39717 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
39718 **     connection is open in WAL mode. A WAL connection is always in one
39719 **     of the first four states.
39720 **
39721 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
39722 **     state. There are two exceptions: immediately after exclusive-mode has
39723 **     been turned on (and before any read or write transactions are 
39724 **     executed), and when the pager is leaving the "error state".
39725 **
39726 **   * See also: assert_pager_state().
39727 */
39728 #define PAGER_OPEN                  0
39729 #define PAGER_READER                1
39730 #define PAGER_WRITER_LOCKED         2
39731 #define PAGER_WRITER_CACHEMOD       3
39732 #define PAGER_WRITER_DBMOD          4
39733 #define PAGER_WRITER_FINISHED       5
39734 #define PAGER_ERROR                 6
39735
39736 /*
39737 ** The Pager.eLock variable is almost always set to one of the 
39738 ** following locking-states, according to the lock currently held on
39739 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39740 ** This variable is kept up to date as locks are taken and released by
39741 ** the pagerLockDb() and pagerUnlockDb() wrappers.
39742 **
39743 ** If the VFS xLock() or xUnlock() returns an error other than SQLCIPHER_BUSY
39744 ** (i.e. one of the SQLCIPHER_IOERR subtypes), it is not clear whether or not
39745 ** the operation was successful. In these circumstances pagerLockDb() and
39746 ** pagerUnlockDb() take a conservative approach - eLock is always updated
39747 ** when unlocking the file, and only updated when locking the file if the
39748 ** VFS call is successful. This way, the Pager.eLock variable may be set
39749 ** to a less exclusive (lower) value than the lock that is actually held
39750 ** at the system level, but it is never set to a more exclusive value.
39751 **
39752 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
39753 ** be a few redundant xLock() calls or a lock may be held for longer than
39754 ** required, but nothing really goes wrong.
39755 **
39756 ** The exception is when the database file is unlocked as the pager moves
39757 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
39758 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
39759 ** transition, by the same pager or any other). If the call to xUnlock()
39760 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
39761 ** can confuse the call to xCheckReservedLock() call made later as part
39762 ** of hot-journal detection.
39763 **
39764 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
39765 ** lock held by this process or any others". So xCheckReservedLock may 
39766 ** return true because the caller itself is holding an EXCLUSIVE lock (but
39767 ** doesn't know it because of a previous error in xUnlock). If this happens
39768 ** a hot-journal may be mistaken for a journal being created by an active
39769 ** transaction in another process, causing SQLite to read from the database
39770 ** without rolling it back.
39771 **
39772 ** To work around this, if a call to xUnlock() fails when unlocking the
39773 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
39774 ** is only changed back to a real locking state after a successful call
39775 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
39776 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
39777 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
39778 ** lock on the database file before attempting to roll it back. See function
39779 ** PagerSharedLock() for more detail.
39780 **
39781 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
39782 ** PAGER_OPEN state.
39783 */
39784 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
39785
39786 /*
39787 ** A macro used for invoking the codec if there is one
39788 */
39789 #ifdef SQLCIPHER_HAS_CODEC
39790 # define CODEC1(P,D,N,X,E) \
39791     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
39792 # define CODEC2(P,D,N,X,E,O) \
39793     if( P->xCodec==0 ){ O=(char*)D; }else \
39794     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
39795 #else
39796 # define CODEC1(P,D,N,X,E)   /* NO-OP */
39797 # define CODEC2(P,D,N,X,E,O) O=(char*)D
39798 #endif
39799
39800 /*
39801 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
39802 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
39803 ** This could conceivably cause corruption following a power failure on
39804 ** such a system. This is currently an undocumented limit.
39805 */
39806 #define MAX_SECTOR_SIZE 0x10000
39807
39808 /*
39809 ** An instance of the following structure is allocated for each active
39810 ** savepoint and statement transaction in the system. All such structures
39811 ** are stored in the Pager.aSavepoint[] array, which is allocated and
39812 ** resized using sqlcipher3Realloc().
39813 **
39814 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
39815 ** set to 0. If a journal-header is written into the main journal while
39816 ** the savepoint is active, then iHdrOffset is set to the byte offset 
39817 ** immediately following the last journal record written into the main
39818 ** journal before the journal-header. This is required during savepoint
39819 ** rollback (see pagerPlaybackSavepoint()).
39820 */
39821 typedef struct PagerSavepoint PagerSavepoint;
39822 struct PagerSavepoint {
39823   i64 iOffset;                 /* Starting offset in main journal */
39824   i64 iHdrOffset;              /* See above */
39825   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
39826   Pgno nOrig;                  /* Original number of pages in file */
39827   Pgno iSubRec;                /* Index of first record in sub-journal */
39828 #ifndef SQLCIPHER_OMIT_WAL
39829   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
39830 #endif
39831 };
39832
39833 /*
39834 ** A open page cache is an instance of struct Pager. A description of
39835 ** some of the more important member variables follows:
39836 **
39837 ** eState
39838 **
39839 **   The current 'state' of the pager object. See the comment and state
39840 **   diagram above for a description of the pager state.
39841 **
39842 ** eLock
39843 **
39844 **   For a real on-disk database, the current lock held on the database file -
39845 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39846 **
39847 **   For a temporary or in-memory database (neither of which require any
39848 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
39849 **   databases always have Pager.exclusiveMode==1, this tricks the pager
39850 **   logic into thinking that it already has all the locks it will ever
39851 **   need (and no reason to release them).
39852 **
39853 **   In some (obscure) circumstances, this variable may also be set to
39854 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
39855 **   details.
39856 **
39857 ** changeCountDone
39858 **
39859 **   This boolean variable is used to make sure that the change-counter 
39860 **   (the 4-byte header field at byte offset 24 of the database file) is 
39861 **   not updated more often than necessary. 
39862 **
39863 **   It is set to true when the change-counter field is updated, which 
39864 **   can only happen if an exclusive lock is held on the database file.
39865 **   It is cleared (set to false) whenever an exclusive lock is 
39866 **   relinquished on the database file. Each time a transaction is committed,
39867 **   The changeCountDone flag is inspected. If it is true, the work of
39868 **   updating the change-counter is omitted for the current transaction.
39869 **
39870 **   This mechanism means that when running in exclusive mode, a connection 
39871 **   need only update the change-counter once, for the first transaction
39872 **   committed.
39873 **
39874 ** setMaster
39875 **
39876 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
39877 **   (or may not) specify a master-journal name to be written into the 
39878 **   journal file before it is synced to disk.
39879 **
39880 **   Whether or not a journal file contains a master-journal pointer affects 
39881 **   the way in which the journal file is finalized after the transaction is 
39882 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
39883 **   If a journal file does not contain a master-journal pointer, it is
39884 **   finalized by overwriting the first journal header with zeroes. If
39885 **   it does contain a master-journal pointer the journal file is finalized 
39886 **   by truncating it to zero bytes, just as if the connection were 
39887 **   running in "journal_mode=truncate" mode.
39888 **
39889 **   Journal files that contain master journal pointers cannot be finalized
39890 **   simply by overwriting the first journal-header with zeroes, as the
39891 **   master journal pointer could interfere with hot-journal rollback of any
39892 **   subsequently interrupted transaction that reuses the journal file.
39893 **
39894 **   The flag is cleared as soon as the journal file is finalized (either
39895 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
39896 **   journal file from being successfully finalized, the setMaster flag
39897 **   is cleared anyway (and the pager will move to ERROR state).
39898 **
39899 ** doNotSpill, doNotSyncSpill
39900 **
39901 **   These two boolean variables control the behaviour of cache-spills
39902 **   (calls made by the pcache module to the pagerStress() routine to
39903 **   write cached data to the file-system in order to free up memory).
39904 **
39905 **   When doNotSpill is non-zero, writing to the database from pagerStress()
39906 **   is disabled altogether. This is done in a very obscure case that
39907 **   comes up during savepoint rollback that requires the pcache module
39908 **   to allocate a new page to prevent the journal file from being written
39909 **   while it is being traversed by code in pager_playback().
39910 ** 
39911 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
39912 **   is permitted, but syncing the journal file is not. This flag is set
39913 **   by sqlcipher3PagerWrite() when the file-system sector-size is larger than
39914 **   the database page-size in order to prevent a journal sync from happening 
39915 **   in between the journalling of two pages on the same sector. 
39916 **
39917 ** subjInMemory
39918 **
39919 **   This is a boolean variable. If true, then any required sub-journal
39920 **   is opened as an in-memory journal file. If false, then in-memory
39921 **   sub-journals are only used for in-memory pager files.
39922 **
39923 **   This variable is updated by the upper layer each time a new 
39924 **   write-transaction is opened.
39925 **
39926 ** dbSize, dbOrigSize, dbFileSize
39927 **
39928 **   Variable dbSize is set to the number of pages in the database file.
39929 **   It is valid in PAGER_READER and higher states (all states except for
39930 **   OPEN and ERROR). 
39931 **
39932 **   dbSize is set based on the size of the database file, which may be 
39933 **   larger than the size of the database (the value stored at offset
39934 **   28 of the database header by the btree). If the size of the file
39935 **   is not an integer multiple of the page-size, the value stored in
39936 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
39937 **   Except, any file that is greater than 0 bytes in size is considered
39938 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
39939 **   to dbSize==1).
39940 **
39941 **   During a write-transaction, if pages with page-numbers greater than
39942 **   dbSize are modified in the cache, dbSize is updated accordingly.
39943 **   Similarly, if the database is truncated using PagerTruncateImage(), 
39944 **   dbSize is updated.
39945 **
39946 **   Variables dbOrigSize and dbFileSize are valid in states 
39947 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
39948 **   variable at the start of the transaction. It is used during rollback,
39949 **   and to determine whether or not pages need to be journalled before
39950 **   being modified.
39951 **
39952 **   Throughout a write-transaction, dbFileSize contains the size of
39953 **   the file on disk in pages. It is set to a copy of dbSize when the
39954 **   write-transaction is first opened, and updated when VFS calls are made
39955 **   to write or truncate the database file on disk. 
39956 **
39957 **   The only reason the dbFileSize variable is required is to suppress 
39958 **   unnecessary calls to xTruncate() after committing a transaction. If, 
39959 **   when a transaction is committed, the dbFileSize variable indicates 
39960 **   that the database file is larger than the database image (Pager.dbSize), 
39961 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
39962 **   to measure the database file on disk, and then truncates it if required.
39963 **   dbFileSize is not used when rolling back a transaction. In this case
39964 **   pager_truncate() is called unconditionally (which means there may be
39965 **   a call to xFilesize() that is not strictly required). In either case,
39966 **   pager_truncate() may cause the file to become smaller or larger.
39967 **
39968 ** dbHintSize
39969 **
39970 **   The dbHintSize variable is used to limit the number of calls made to
39971 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
39972 **
39973 **   dbHintSize is set to a copy of the dbSize variable when a
39974 **   write-transaction is opened (at the same time as dbFileSize and
39975 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
39976 **   dbHintSize is increased to the number of pages that correspond to the
39977 **   size-hint passed to the method call. See pager_write_pagelist() for 
39978 **   details.
39979 **
39980 ** errCode
39981 **
39982 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
39983 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
39984 **   is always set to SQLCIPHER_FULL, SQLCIPHER_IOERR or one of the SQLCIPHER_IOERR_XXX 
39985 **   sub-codes.
39986 */
39987 struct Pager {
39988   sqlcipher3_vfs *pVfs;          /* OS functions to use for IO */
39989   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
39990   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
39991   u8 useJournal;              /* Use a rollback journal on this file */
39992   u8 noReadlock;              /* Do not bother to obtain readlocks */
39993   u8 noSync;                  /* Do not sync the journal if true */
39994   u8 fullSync;                /* Do extra syncs of the journal for robustness */
39995   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
39996   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
39997   u8 tempFile;                /* zFilename is a temporary file */
39998   u8 readOnly;                /* True for a read-only database */
39999   u8 memDb;                   /* True to inhibit all file I/O */
40000
40001   /**************************************************************************
40002   ** The following block contains those class members that change during
40003   ** routine opertion.  Class members not in this block are either fixed
40004   ** when the pager is first created or else only change when there is a
40005   ** significant mode change (such as changing the page_size, locking_mode,
40006   ** or the journal_mode).  From another view, these class members describe
40007   ** the "state" of the pager, while other class members describe the
40008   ** "configuration" of the pager.
40009   */
40010   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
40011   u8 eLock;                   /* Current lock held on database file */
40012   u8 changeCountDone;         /* Set after incrementing the change-counter */
40013   u8 setMaster;               /* True if a m-j name has been written to jrnl */
40014   u8 doNotSpill;              /* Do not spill the cache when non-zero */
40015   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
40016   u8 subjInMemory;            /* True to use in-memory sub-journals */
40017   Pgno dbSize;                /* Number of pages in the database */
40018   Pgno dbOrigSize;            /* dbSize before the current transaction */
40019   Pgno dbFileSize;            /* Number of pages in the database file */
40020   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
40021   int errCode;                /* One of several kinds of errors */
40022   int nRec;                   /* Pages journalled since last j-header written */
40023   u32 cksumInit;              /* Quasi-random value added to every checksum */
40024   u32 nSubRec;                /* Number of records written to sub-journal */
40025   Bitvec *pInJournal;         /* One bit for each page in the database file */
40026   sqlcipher3_file *fd;           /* File descriptor for database */
40027   sqlcipher3_file *jfd;          /* File descriptor for main journal */
40028   sqlcipher3_file *sjfd;         /* File descriptor for sub-journal */
40029   i64 journalOff;             /* Current write offset in the journal file */
40030   i64 journalHdr;             /* Byte offset to previous journal header */
40031   sqlcipher3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
40032   PagerSavepoint *aSavepoint; /* Array of active savepoints */
40033   int nSavepoint;             /* Number of elements in aSavepoint[] */
40034   char dbFileVers[16];        /* Changes whenever database file changes */
40035   /*
40036   ** End of the routinely-changing class members
40037   ***************************************************************************/
40038
40039   u16 nExtra;                 /* Add this many bytes to each in-memory page */
40040   i16 nReserve;               /* Number of unused bytes at end of each page */
40041   u32 vfsFlags;               /* Flags for sqlcipher3_vfs.xOpen() */
40042   u32 sectorSize;             /* Assumed sector size during rollback */
40043   int pageSize;               /* Number of bytes in a page */
40044   Pgno mxPgno;                /* Maximum allowed size of the database */
40045   i64 journalSizeLimit;       /* Size limit for persistent journal files */
40046   char *zFilename;            /* Name of the database file */
40047   char *zJournal;             /* Name of the journal file */
40048   int (*xBusyHandler)(void*); /* Function to call when busy */
40049   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
40050   int nHit, nMiss;            /* Total cache hits and misses */
40051 #ifdef SQLCIPHER_TEST
40052   int nRead, nWrite;          /* Database pages read/written */
40053 #endif
40054   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
40055 #ifdef SQLCIPHER_HAS_CODEC
40056   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
40057   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
40058   void (*xCodecFree)(void*);             /* Destructor for the codec */
40059   void *pCodec;               /* First argument to xCodec... methods */
40060 #endif
40061   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
40062   PCache *pPCache;            /* Pointer to page cache object */
40063 #ifndef SQLCIPHER_OMIT_WAL
40064   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
40065   char *zWal;                 /* File name for write-ahead log */
40066 #endif
40067 };
40068
40069 /*
40070 ** The following global variables hold counters used for
40071 ** testing purposes only.  These variables do not exist in
40072 ** a non-testing build.  These variables are not thread-safe.
40073 */
40074 #ifdef SQLCIPHER_TEST
40075 SQLCIPHER_API int sqlcipher3_pager_readdb_count = 0;    /* Number of full pages read from DB */
40076 SQLCIPHER_API int sqlcipher3_pager_writedb_count = 0;   /* Number of full pages written to DB */
40077 SQLCIPHER_API int sqlcipher3_pager_writej_count = 0;    /* Number of pages written to journal */
40078 # define PAGER_INCR(v)  v++
40079 #else
40080 # define PAGER_INCR(v)
40081 #endif
40082
40083
40084
40085 /*
40086 ** Journal files begin with the following magic string.  The data
40087 ** was obtained from /dev/random.  It is used only as a sanity check.
40088 **
40089 ** Since version 2.8.0, the journal format contains additional sanity
40090 ** checking information.  If the power fails while the journal is being
40091 ** written, semi-random garbage data might appear in the journal
40092 ** file after power is restored.  If an attempt is then made
40093 ** to roll the journal back, the database could be corrupted.  The additional
40094 ** sanity checking data is an attempt to discover the garbage in the
40095 ** journal and ignore it.
40096 **
40097 ** The sanity checking information for the new journal format consists
40098 ** of a 32-bit checksum on each page of data.  The checksum covers both
40099 ** the page number and the pPager->pageSize bytes of data for the page.
40100 ** This cksum is initialized to a 32-bit random value that appears in the
40101 ** journal file right after the header.  The random initializer is important,
40102 ** because garbage data that appears at the end of a journal is likely
40103 ** data that was once in other files that have now been deleted.  If the
40104 ** garbage data came from an obsolete journal file, the checksums might
40105 ** be correct.  But by initializing the checksum to random value which
40106 ** is different for every journal, we minimize that risk.
40107 */
40108 static const unsigned char aJournalMagic[] = {
40109   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
40110 };
40111
40112 /*
40113 ** The size of the of each page record in the journal is given by
40114 ** the following macro.
40115 */
40116 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
40117
40118 /*
40119 ** The journal header size for this pager. This is usually the same 
40120 ** size as a single disk sector. See also setSectorSize().
40121 */
40122 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
40123
40124 /*
40125 ** The macro MEMDB is true if we are dealing with an in-memory database.
40126 ** We do this as a macro so that if the SQLCIPHER_OMIT_MEMORYDB macro is set,
40127 ** the value of MEMDB will be a constant and the compiler will optimize
40128 ** out code that would never execute.
40129 */
40130 #ifdef SQLCIPHER_OMIT_MEMORYDB
40131 # define MEMDB 0
40132 #else
40133 # define MEMDB pPager->memDb
40134 #endif
40135
40136 /*
40137 ** The maximum legal page number is (2^31 - 1).
40138 */
40139 #define PAGER_MAX_PGNO 2147483647
40140
40141 /*
40142 ** The argument to this macro is a file descriptor (type sqlcipher3_file*).
40143 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
40144 **
40145 ** This is so that expressions can be written as:
40146 **
40147 **   if( isOpen(pPager->jfd) ){ ...
40148 **
40149 ** instead of
40150 **
40151 **   if( pPager->jfd->pMethods ){ ...
40152 */
40153 #define isOpen(pFd) ((pFd)->pMethods)
40154
40155 /*
40156 ** Return true if this pager uses a write-ahead log instead of the usual
40157 ** rollback journal. Otherwise false.
40158 */
40159 #ifndef SQLCIPHER_OMIT_WAL
40160 static int pagerUseWal(Pager *pPager){
40161   return (pPager->pWal!=0);
40162 }
40163 #else
40164 # define pagerUseWal(x) 0
40165 # define pagerRollbackWal(x) 0
40166 # define pagerWalFrames(v,w,x,y,z) 0
40167 # define pagerOpenWalIfPresent(z) SQLCIPHER_OK
40168 # define pagerBeginReadTransaction(z) SQLCIPHER_OK
40169 #endif
40170
40171 #ifndef NDEBUG 
40172 /*
40173 ** Usage:
40174 **
40175 **   assert( assert_pager_state(pPager) );
40176 **
40177 ** This function runs many asserts to try to find inconsistencies in
40178 ** the internal state of the Pager object.
40179 */
40180 static int assert_pager_state(Pager *p){
40181   Pager *pPager = p;
40182
40183   /* State must be valid. */
40184   assert( p->eState==PAGER_OPEN
40185        || p->eState==PAGER_READER
40186        || p->eState==PAGER_WRITER_LOCKED
40187        || p->eState==PAGER_WRITER_CACHEMOD
40188        || p->eState==PAGER_WRITER_DBMOD
40189        || p->eState==PAGER_WRITER_FINISHED
40190        || p->eState==PAGER_ERROR
40191   );
40192
40193   /* Regardless of the current state, a temp-file connection always behaves
40194   ** as if it has an exclusive lock on the database file. It never updates
40195   ** the change-counter field, so the changeCountDone flag is always set.
40196   */
40197   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
40198   assert( p->tempFile==0 || pPager->changeCountDone );
40199
40200   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
40201   ** And if the journal-mode is "OFF", the journal file must not be open.
40202   */
40203   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
40204   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
40205
40206   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
40207   ** this means an in-memory pager performs no IO at all, it cannot encounter 
40208   ** either SQLCIPHER_IOERR or SQLCIPHER_FULL during rollback or while finalizing 
40209   ** a journal file. (although the in-memory journal implementation may 
40210   ** return SQLCIPHER_IOERR_NOMEM while the journal file is being written). It 
40211   ** is therefore not possible for an in-memory pager to enter the ERROR 
40212   ** state.
40213   */
40214   if( MEMDB ){
40215     assert( p->noSync );
40216     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
40217          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
40218     );
40219     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
40220     assert( pagerUseWal(p)==0 );
40221   }
40222
40223   /* If changeCountDone is set, a RESERVED lock or greater must be held
40224   ** on the file.
40225   */
40226   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
40227   assert( p->eLock!=PENDING_LOCK );
40228
40229   switch( p->eState ){
40230     case PAGER_OPEN:
40231       assert( !MEMDB );
40232       assert( pPager->errCode==SQLCIPHER_OK );
40233       assert( sqlcipher3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
40234       break;
40235
40236     case PAGER_READER:
40237       assert( pPager->errCode==SQLCIPHER_OK );
40238       assert( p->eLock!=UNKNOWN_LOCK );
40239       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
40240       break;
40241
40242     case PAGER_WRITER_LOCKED:
40243       assert( p->eLock!=UNKNOWN_LOCK );
40244       assert( pPager->errCode==SQLCIPHER_OK );
40245       if( !pagerUseWal(pPager) ){
40246         assert( p->eLock>=RESERVED_LOCK );
40247       }
40248       assert( pPager->dbSize==pPager->dbOrigSize );
40249       assert( pPager->dbOrigSize==pPager->dbFileSize );
40250       assert( pPager->dbOrigSize==pPager->dbHintSize );
40251       assert( pPager->setMaster==0 );
40252       break;
40253
40254     case PAGER_WRITER_CACHEMOD:
40255       assert( p->eLock!=UNKNOWN_LOCK );
40256       assert( pPager->errCode==SQLCIPHER_OK );
40257       if( !pagerUseWal(pPager) ){
40258         /* It is possible that if journal_mode=wal here that neither the
40259         ** journal file nor the WAL file are open. This happens during
40260         ** a rollback transaction that switches from journal_mode=off
40261         ** to journal_mode=wal.
40262         */
40263         assert( p->eLock>=RESERVED_LOCK );
40264         assert( isOpen(p->jfd) 
40265              || p->journalMode==PAGER_JOURNALMODE_OFF 
40266              || p->journalMode==PAGER_JOURNALMODE_WAL 
40267         );
40268       }
40269       assert( pPager->dbOrigSize==pPager->dbFileSize );
40270       assert( pPager->dbOrigSize==pPager->dbHintSize );
40271       break;
40272
40273     case PAGER_WRITER_DBMOD:
40274       assert( p->eLock==EXCLUSIVE_LOCK );
40275       assert( pPager->errCode==SQLCIPHER_OK );
40276       assert( !pagerUseWal(pPager) );
40277       assert( p->eLock>=EXCLUSIVE_LOCK );
40278       assert( isOpen(p->jfd) 
40279            || p->journalMode==PAGER_JOURNALMODE_OFF 
40280            || p->journalMode==PAGER_JOURNALMODE_WAL 
40281       );
40282       assert( pPager->dbOrigSize<=pPager->dbHintSize );
40283       break;
40284
40285     case PAGER_WRITER_FINISHED:
40286       assert( p->eLock==EXCLUSIVE_LOCK );
40287       assert( pPager->errCode==SQLCIPHER_OK );
40288       assert( !pagerUseWal(pPager) );
40289       assert( isOpen(p->jfd) 
40290            || p->journalMode==PAGER_JOURNALMODE_OFF 
40291            || p->journalMode==PAGER_JOURNALMODE_WAL 
40292       );
40293       break;
40294
40295     case PAGER_ERROR:
40296       /* There must be at least one outstanding reference to the pager if
40297       ** in ERROR state. Otherwise the pager should have already dropped
40298       ** back to OPEN state.
40299       */
40300       assert( pPager->errCode!=SQLCIPHER_OK );
40301       assert( sqlcipher3PcacheRefCount(pPager->pPCache)>0 );
40302       break;
40303   }
40304
40305   return 1;
40306 }
40307 #endif /* ifndef NDEBUG */
40308
40309 #ifdef SQLCIPHER_DEBUG 
40310 /*
40311 ** Return a pointer to a human readable string in a static buffer
40312 ** containing the state of the Pager object passed as an argument. This
40313 ** is intended to be used within debuggers. For example, as an alternative
40314 ** to "print *pPager" in gdb:
40315 **
40316 ** (gdb) printf "%s", print_pager_state(pPager)
40317 */
40318 static char *print_pager_state(Pager *p){
40319   static char zRet[1024];
40320
40321   sqlcipher3_snprintf(1024, zRet,
40322       "Filename:      %s\n"
40323       "State:         %s errCode=%d\n"
40324       "Lock:          %s\n"
40325       "Locking mode:  locking_mode=%s\n"
40326       "Journal mode:  journal_mode=%s\n"
40327       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40328       "Journal:       journalOff=%lld journalHdr=%lld\n"
40329       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40330       , p->zFilename
40331       , p->eState==PAGER_OPEN            ? "OPEN" :
40332         p->eState==PAGER_READER          ? "READER" :
40333         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
40334         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40335         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
40336         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40337         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
40338       , (int)p->errCode
40339       , p->eLock==NO_LOCK         ? "NO_LOCK" :
40340         p->eLock==RESERVED_LOCK   ? "RESERVED" :
40341         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
40342         p->eLock==SHARED_LOCK     ? "SHARED" :
40343         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
40344       , p->exclusiveMode ? "exclusive" : "normal"
40345       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
40346         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
40347         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
40348         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
40349         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40350         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
40351       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40352       , p->journalOff, p->journalHdr
40353       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40354   );
40355
40356   return zRet;
40357 }
40358 #endif
40359
40360 /*
40361 ** Return true if it is necessary to write page *pPg into the sub-journal.
40362 ** A page needs to be written into the sub-journal if there exists one
40363 ** or more open savepoints for which:
40364 **
40365 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
40366 **   * The bit corresponding to the page-number is not set in
40367 **     PagerSavepoint.pInSavepoint.
40368 */
40369 static int subjRequiresPage(PgHdr *pPg){
40370   Pgno pgno = pPg->pgno;
40371   Pager *pPager = pPg->pPager;
40372   int i;
40373   for(i=0; i<pPager->nSavepoint; i++){
40374     PagerSavepoint *p = &pPager->aSavepoint[i];
40375     if( p->nOrig>=pgno && 0==sqlcipher3BitvecTest(p->pInSavepoint, pgno) ){
40376       return 1;
40377     }
40378   }
40379   return 0;
40380 }
40381
40382 /*
40383 ** Return true if the page is already in the journal file.
40384 */
40385 static int pageInJournal(PgHdr *pPg){
40386   return sqlcipher3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
40387 }
40388
40389 /*
40390 ** Read a 32-bit integer from the given file descriptor.  Store the integer
40391 ** that is read in *pRes.  Return SQLCIPHER_OK if everything worked, or an
40392 ** error code is something goes wrong.
40393 **
40394 ** All values are stored on disk as big-endian.
40395 */
40396 static int read32bits(sqlcipher3_file *fd, i64 offset, u32 *pRes){
40397   unsigned char ac[4];
40398   int rc = sqlcipher3OsRead(fd, ac, sizeof(ac), offset);
40399   if( rc==SQLCIPHER_OK ){
40400     *pRes = sqlcipher3Get4byte(ac);
40401   }
40402   return rc;
40403 }
40404
40405 /*
40406 ** Write a 32-bit integer into a string buffer in big-endian byte order.
40407 */
40408 #define put32bits(A,B)  sqlcipher3Put4byte((u8*)A,B)
40409
40410
40411 /*
40412 ** Write a 32-bit integer into the given file descriptor.  Return SQLCIPHER_OK
40413 ** on success or an error code is something goes wrong.
40414 */
40415 static int write32bits(sqlcipher3_file *fd, i64 offset, u32 val){
40416   char ac[4];
40417   put32bits(ac, val);
40418   return sqlcipher3OsWrite(fd, ac, 4, offset);
40419 }
40420
40421 /*
40422 ** Unlock the database file to level eLock, which must be either NO_LOCK
40423 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40424 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40425 **
40426 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40427 ** called, do not modify it. See the comment above the #define of 
40428 ** UNKNOWN_LOCK for an explanation of this.
40429 */
40430 static int pagerUnlockDb(Pager *pPager, int eLock){
40431   int rc = SQLCIPHER_OK;
40432
40433   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40434   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40435   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40436   if( isOpen(pPager->fd) ){
40437     assert( pPager->eLock>=eLock );
40438     rc = sqlcipher3OsUnlock(pPager->fd, eLock);
40439     if( pPager->eLock!=UNKNOWN_LOCK ){
40440       pPager->eLock = (u8)eLock;
40441     }
40442     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40443   }
40444   return rc;
40445 }
40446
40447 /*
40448 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
40449 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40450 ** Pager.eLock variable to the new locking state. 
40451 **
40452 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
40453 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
40454 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
40455 ** of this.
40456 */
40457 static int pagerLockDb(Pager *pPager, int eLock){
40458   int rc = SQLCIPHER_OK;
40459
40460   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40461   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40462     rc = sqlcipher3OsLock(pPager->fd, eLock);
40463     if( rc==SQLCIPHER_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40464       pPager->eLock = (u8)eLock;
40465       IOTRACE(("LOCK %p %d\n", pPager, eLock))
40466     }
40467   }
40468   return rc;
40469 }
40470
40471 /*
40472 ** This function determines whether or not the atomic-write optimization
40473 ** can be used with this pager. The optimization can be used if:
40474 **
40475 **  (a) the value returned by OsDeviceCharacteristics() indicates that
40476 **      a database page may be written atomically, and
40477 **  (b) the value returned by OsSectorSize() is less than or equal
40478 **      to the page size.
40479 **
40480 ** The optimization is also always enabled for temporary files. It is
40481 ** an error to call this function if pPager is opened on an in-memory
40482 ** database.
40483 **
40484 ** If the optimization cannot be used, 0 is returned. If it can be used,
40485 ** then the value returned is the size of the journal file when it
40486 ** contains rollback data for exactly one page.
40487 */
40488 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
40489 static int jrnlBufferSize(Pager *pPager){
40490   assert( !MEMDB );
40491   if( !pPager->tempFile ){
40492     int dc;                           /* Device characteristics */
40493     int nSector;                      /* Sector size */
40494     int szPage;                       /* Page size */
40495
40496     assert( isOpen(pPager->fd) );
40497     dc = sqlcipher3OsDeviceCharacteristics(pPager->fd);
40498     nSector = pPager->sectorSize;
40499     szPage = pPager->pageSize;
40500
40501     assert(SQLCIPHER_IOCAP_ATOMIC512==(512>>8));
40502     assert(SQLCIPHER_IOCAP_ATOMIC64K==(65536>>8));
40503     if( 0==(dc&(SQLCIPHER_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
40504       return 0;
40505     }
40506   }
40507
40508   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
40509 }
40510 #endif
40511
40512 /*
40513 ** If SQLCIPHER_CHECK_PAGES is defined then we do some sanity checking
40514 ** on the cache using a hash function.  This is used for testing
40515 ** and debugging only.
40516 */
40517 #ifdef SQLCIPHER_CHECK_PAGES
40518 /*
40519 ** Return a 32-bit hash of the page data for pPage.
40520 */
40521 static u32 pager_datahash(int nByte, unsigned char *pData){
40522   u32 hash = 0;
40523   int i;
40524   for(i=0; i<nByte; i++){
40525     hash = (hash*1039) + pData[i];
40526   }
40527   return hash;
40528 }
40529 static u32 pager_pagehash(PgHdr *pPage){
40530   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
40531 }
40532 static void pager_set_pagehash(PgHdr *pPage){
40533   pPage->pageHash = pager_pagehash(pPage);
40534 }
40535
40536 /*
40537 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLCIPHER_CHECK_PAGES
40538 ** is defined, and NDEBUG is not defined, an assert() statement checks
40539 ** that the page is either dirty or still matches the calculated page-hash.
40540 */
40541 #define CHECK_PAGE(x) checkPage(x)
40542 static void checkPage(PgHdr *pPg){
40543   Pager *pPager = pPg->pPager;
40544   assert( pPager->eState!=PAGER_ERROR );
40545   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
40546 }
40547
40548 #else
40549 #define pager_datahash(X,Y)  0
40550 #define pager_pagehash(X)  0
40551 #define pager_set_pagehash(X)
40552 #define CHECK_PAGE(x)
40553 #endif  /* SQLCIPHER_CHECK_PAGES */
40554
40555 /*
40556 ** When this is called the journal file for pager pPager must be open.
40557 ** This function attempts to read a master journal file name from the 
40558 ** end of the file and, if successful, copies it into memory supplied 
40559 ** by the caller. See comments above writeMasterJournal() for the format
40560 ** used to store a master journal file name at the end of a journal file.
40561 **
40562 ** zMaster must point to a buffer of at least nMaster bytes allocated by
40563 ** the caller. This should be sqlcipher3_vfs.mxPathname+1 (to ensure there is
40564 ** enough space to write the master journal name). If the master journal
40565 ** name in the journal is longer than nMaster bytes (including a
40566 ** nul-terminator), then this is handled as if no master journal name
40567 ** were present in the journal.
40568 **
40569 ** If a master journal file name is present at the end of the journal
40570 ** file, then it is copied into the buffer pointed to by zMaster. A
40571 ** nul-terminator byte is appended to the buffer following the master
40572 ** journal file name.
40573 **
40574 ** If it is determined that no master journal file name is present 
40575 ** zMaster[0] is set to 0 and SQLCIPHER_OK returned.
40576 **
40577 ** If an error occurs while reading from the journal file, an SQLite
40578 ** error code is returned.
40579 */
40580 static int readMasterJournal(sqlcipher3_file *pJrnl, char *zMaster, u32 nMaster){
40581   int rc;                    /* Return code */
40582   u32 len;                   /* Length in bytes of master journal name */
40583   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
40584   u32 cksum;                 /* MJ checksum value read from journal */
40585   u32 u;                     /* Unsigned loop counter */
40586   unsigned char aMagic[8];   /* A buffer to hold the magic header */
40587   zMaster[0] = '\0';
40588
40589   if( SQLCIPHER_OK!=(rc = sqlcipher3OsFileSize(pJrnl, &szJ))
40590    || szJ<16
40591    || SQLCIPHER_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
40592    || len>=nMaster 
40593    || SQLCIPHER_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
40594    || SQLCIPHER_OK!=(rc = sqlcipher3OsRead(pJrnl, aMagic, 8, szJ-8))
40595    || memcmp(aMagic, aJournalMagic, 8)
40596    || SQLCIPHER_OK!=(rc = sqlcipher3OsRead(pJrnl, zMaster, len, szJ-16-len))
40597   ){
40598     return rc;
40599   }
40600
40601   /* See if the checksum matches the master journal name */
40602   for(u=0; u<len; u++){
40603     cksum -= zMaster[u];
40604   }
40605   if( cksum ){
40606     /* If the checksum doesn't add up, then one or more of the disk sectors
40607     ** containing the master journal filename is corrupted. This means
40608     ** definitely roll back, so just return SQLCIPHER_OK and report a (nul)
40609     ** master-journal filename.
40610     */
40611     len = 0;
40612   }
40613   zMaster[len] = '\0';
40614    
40615   return SQLCIPHER_OK;
40616 }
40617
40618 /*
40619 ** Return the offset of the sector boundary at or immediately 
40620 ** following the value in pPager->journalOff, assuming a sector 
40621 ** size of pPager->sectorSize bytes.
40622 **
40623 ** i.e for a sector size of 512:
40624 **
40625 **   Pager.journalOff          Return value
40626 **   ---------------------------------------
40627 **   0                         0
40628 **   512                       512
40629 **   100                       512
40630 **   2000                      2048
40631 ** 
40632 */
40633 static i64 journalHdrOffset(Pager *pPager){
40634   i64 offset = 0;
40635   i64 c = pPager->journalOff;
40636   if( c ){
40637     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
40638   }
40639   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
40640   assert( offset>=c );
40641   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
40642   return offset;
40643 }
40644
40645 /*
40646 ** The journal file must be open when this function is called.
40647 **
40648 ** This function is a no-op if the journal file has not been written to
40649 ** within the current transaction (i.e. if Pager.journalOff==0).
40650 **
40651 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
40652 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
40653 ** zero the 28-byte header at the start of the journal file. In either case, 
40654 ** if the pager is not in no-sync mode, sync the journal file immediately 
40655 ** after writing or truncating it.
40656 **
40657 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
40658 ** following the truncation or zeroing described above the size of the 
40659 ** journal file in bytes is larger than this value, then truncate the
40660 ** journal file to Pager.journalSizeLimit bytes. The journal file does
40661 ** not need to be synced following this operation.
40662 **
40663 ** If an IO error occurs, abandon processing and return the IO error code.
40664 ** Otherwise, return SQLCIPHER_OK.
40665 */
40666 static int zeroJournalHdr(Pager *pPager, int doTruncate){
40667   int rc = SQLCIPHER_OK;                               /* Return code */
40668   assert( isOpen(pPager->jfd) );
40669   if( pPager->journalOff ){
40670     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
40671
40672     IOTRACE(("JZEROHDR %p\n", pPager))
40673     if( doTruncate || iLimit==0 ){
40674       rc = sqlcipher3OsTruncate(pPager->jfd, 0);
40675     }else{
40676       static const char zeroHdr[28] = {0};
40677       rc = sqlcipher3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
40678     }
40679     if( rc==SQLCIPHER_OK && !pPager->noSync ){
40680       rc = sqlcipher3OsSync(pPager->jfd, SQLCIPHER_SYNC_DATAONLY|pPager->syncFlags);
40681     }
40682
40683     /* At this point the transaction is committed but the write lock 
40684     ** is still held on the file. If there is a size limit configured for 
40685     ** the persistent journal and the journal file currently consumes more
40686     ** space than that limit allows for, truncate it now. There is no need
40687     ** to sync the file following this operation.
40688     */
40689     if( rc==SQLCIPHER_OK && iLimit>0 ){
40690       i64 sz;
40691       rc = sqlcipher3OsFileSize(pPager->jfd, &sz);
40692       if( rc==SQLCIPHER_OK && sz>iLimit ){
40693         rc = sqlcipher3OsTruncate(pPager->jfd, iLimit);
40694       }
40695     }
40696   }
40697   return rc;
40698 }
40699
40700 /*
40701 ** The journal file must be open when this routine is called. A journal
40702 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
40703 ** current location.
40704 **
40705 ** The format for the journal header is as follows:
40706 ** - 8 bytes: Magic identifying journal format.
40707 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
40708 ** - 4 bytes: Random number used for page hash.
40709 ** - 4 bytes: Initial database page count.
40710 ** - 4 bytes: Sector size used by the process that wrote this journal.
40711 ** - 4 bytes: Database page size.
40712 ** 
40713 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
40714 */
40715 static int writeJournalHdr(Pager *pPager){
40716   int rc = SQLCIPHER_OK;                 /* Return code */
40717   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
40718   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
40719   u32 nWrite;                         /* Bytes of header sector written */
40720   int ii;                             /* Loop counter */
40721
40722   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40723
40724   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
40725     nHeader = JOURNAL_HDR_SZ(pPager);
40726   }
40727
40728   /* If there are active savepoints and any of them were created 
40729   ** since the most recent journal header was written, update the 
40730   ** PagerSavepoint.iHdrOffset fields now.
40731   */
40732   for(ii=0; ii<pPager->nSavepoint; ii++){
40733     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
40734       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
40735     }
40736   }
40737
40738   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
40739
40740   /* 
40741   ** Write the nRec Field - the number of page records that follow this
40742   ** journal header. Normally, zero is written to this value at this time.
40743   ** After the records are added to the journal (and the journal synced, 
40744   ** if in full-sync mode), the zero is overwritten with the true number
40745   ** of records (see syncJournal()).
40746   **
40747   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
40748   ** reading the journal this value tells SQLite to assume that the
40749   ** rest of the journal file contains valid page records. This assumption
40750   ** is dangerous, as if a failure occurred whilst writing to the journal
40751   ** file it may contain some garbage data. There are two scenarios
40752   ** where this risk can be ignored:
40753   **
40754   **   * When the pager is in no-sync mode. Corruption can follow a
40755   **     power failure in this case anyway.
40756   **
40757   **   * When the SQLCIPHER_IOCAP_SAFE_APPEND flag is set. This guarantees
40758   **     that garbage data is never appended to the journal file.
40759   */
40760   assert( isOpen(pPager->fd) || pPager->noSync );
40761   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
40762    || (sqlcipher3OsDeviceCharacteristics(pPager->fd)&SQLCIPHER_IOCAP_SAFE_APPEND) 
40763   ){
40764     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40765     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
40766   }else{
40767     memset(zHeader, 0, sizeof(aJournalMagic)+4);
40768   }
40769
40770   /* The random check-hash initialiser */ 
40771   sqlcipher3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
40772   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
40773   /* The initial database size */
40774   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
40775   /* The assumed sector size for this process */
40776   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
40777
40778   /* The page size */
40779   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
40780
40781   /* Initializing the tail of the buffer is not necessary.  Everything
40782   ** works find if the following memset() is omitted.  But initializing
40783   ** the memory prevents valgrind from complaining, so we are willing to
40784   ** take the performance hit.
40785   */
40786   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
40787          nHeader-(sizeof(aJournalMagic)+20));
40788
40789   /* In theory, it is only necessary to write the 28 bytes that the 
40790   ** journal header consumes to the journal file here. Then increment the 
40791   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
40792   ** record is written to the following sector (leaving a gap in the file
40793   ** that will be implicitly filled in by the OS).
40794   **
40795   ** However it has been discovered that on some systems this pattern can 
40796   ** be significantly slower than contiguously writing data to the file,
40797   ** even if that means explicitly writing data to the block of 
40798   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
40799   ** is done. 
40800   **
40801   ** The loop is required here in case the sector-size is larger than the 
40802   ** database page size. Since the zHeader buffer is only Pager.pageSize
40803   ** bytes in size, more than one call to sqlcipher3OsWrite() may be required
40804   ** to populate the entire journal header sector.
40805   */ 
40806   for(nWrite=0; rc==SQLCIPHER_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
40807     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
40808     rc = sqlcipher3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
40809     assert( pPager->journalHdr <= pPager->journalOff );
40810     pPager->journalOff += nHeader;
40811   }
40812
40813   return rc;
40814 }
40815
40816 /*
40817 ** The journal file must be open when this is called. A journal header file
40818 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
40819 ** file. The current location in the journal file is given by
40820 ** pPager->journalOff. See comments above function writeJournalHdr() for
40821 ** a description of the journal header format.
40822 **
40823 ** If the header is read successfully, *pNRec is set to the number of
40824 ** page records following this header and *pDbSize is set to the size of the
40825 ** database before the transaction began, in pages. Also, pPager->cksumInit
40826 ** is set to the value read from the journal header. SQLCIPHER_OK is returned
40827 ** in this case.
40828 **
40829 ** If the journal header file appears to be corrupted, SQLCIPHER_DONE is
40830 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
40831 ** cannot be read from the journal file an error code is returned.
40832 */
40833 static int readJournalHdr(
40834   Pager *pPager,               /* Pager object */
40835   int isHot,
40836   i64 journalSize,             /* Size of the open journal file in bytes */
40837   u32 *pNRec,                  /* OUT: Value read from the nRec field */
40838   u32 *pDbSize                 /* OUT: Value of original database size field */
40839 ){
40840   int rc;                      /* Return code */
40841   unsigned char aMagic[8];     /* A buffer to hold the magic header */
40842   i64 iHdrOff;                 /* Offset of journal header being read */
40843
40844   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40845
40846   /* Advance Pager.journalOff to the start of the next sector. If the
40847   ** journal file is too small for there to be a header stored at this
40848   ** point, return SQLCIPHER_DONE.
40849   */
40850   pPager->journalOff = journalHdrOffset(pPager);
40851   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
40852     return SQLCIPHER_DONE;
40853   }
40854   iHdrOff = pPager->journalOff;
40855
40856   /* Read in the first 8 bytes of the journal header. If they do not match
40857   ** the  magic string found at the start of each journal header, return
40858   ** SQLCIPHER_DONE. If an IO error occurs, return an error code. Otherwise,
40859   ** proceed.
40860   */
40861   if( isHot || iHdrOff!=pPager->journalHdr ){
40862     rc = sqlcipher3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
40863     if( rc ){
40864       return rc;
40865     }
40866     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
40867       return SQLCIPHER_DONE;
40868     }
40869   }
40870
40871   /* Read the first three 32-bit fields of the journal header: The nRec
40872   ** field, the checksum-initializer and the database size at the start
40873   ** of the transaction. Return an error code if anything goes wrong.
40874   */
40875   if( SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
40876    || SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
40877    || SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
40878   ){
40879     return rc;
40880   }
40881
40882   if( pPager->journalOff==0 ){
40883     u32 iPageSize;               /* Page-size field of journal header */
40884     u32 iSectorSize;             /* Sector-size field of journal header */
40885
40886     /* Read the page-size and sector-size journal header fields. */
40887     if( SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
40888      || SQLCIPHER_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
40889     ){
40890       return rc;
40891     }
40892
40893     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
40894     ** journal header to zero. In this case, assume that the Pager.pageSize
40895     ** variable is already set to the correct page size.
40896     */
40897     if( iPageSize==0 ){
40898       iPageSize = pPager->pageSize;
40899     }
40900
40901     /* Check that the values read from the page-size and sector-size fields
40902     ** are within range. To be 'in range', both values need to be a power
40903     ** of two greater than or equal to 512 or 32, and not greater than their 
40904     ** respective compile time maximum limits.
40905     */
40906     if( iPageSize<512                  || iSectorSize<32
40907      || iPageSize>SQLCIPHER_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
40908      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
40909     ){
40910       /* If the either the page-size or sector-size in the journal-header is 
40911       ** invalid, then the process that wrote the journal-header must have 
40912       ** crashed before the header was synced. In this case stop reading 
40913       ** the journal file here.
40914       */
40915       return SQLCIPHER_DONE;
40916     }
40917
40918     /* Update the page-size to match the value read from the journal. 
40919     ** Use a testcase() macro to make sure that malloc failure within 
40920     ** PagerSetPagesize() is tested.
40921     */
40922     rc = sqlcipher3PagerSetPagesize(pPager, &iPageSize, -1);
40923     testcase( rc!=SQLCIPHER_OK );
40924
40925     /* Update the assumed sector-size to match the value used by 
40926     ** the process that created this journal. If this journal was
40927     ** created by a process other than this one, then this routine
40928     ** is being called from within pager_playback(). The local value
40929     ** of Pager.sectorSize is restored at the end of that routine.
40930     */
40931     pPager->sectorSize = iSectorSize;
40932   }
40933
40934   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
40935   return rc;
40936 }
40937
40938
40939 /*
40940 ** Write the supplied master journal name into the journal file for pager
40941 ** pPager at the current location. The master journal name must be the last
40942 ** thing written to a journal file. If the pager is in full-sync mode, the
40943 ** journal file descriptor is advanced to the next sector boundary before
40944 ** anything is written. The format is:
40945 **
40946 **   + 4 bytes: PAGER_MJ_PGNO.
40947 **   + N bytes: Master journal filename in utf-8.
40948 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
40949 **   + 4 bytes: Master journal name checksum.
40950 **   + 8 bytes: aJournalMagic[].
40951 **
40952 ** The master journal page checksum is the sum of the bytes in the master
40953 ** journal name, where each byte is interpreted as a signed 8-bit integer.
40954 **
40955 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
40956 ** this call is a no-op.
40957 */
40958 static int writeMasterJournal(Pager *pPager, const char *zMaster){
40959   int rc;                          /* Return code */
40960   int nMaster;                     /* Length of string zMaster */
40961   i64 iHdrOff;                     /* Offset of header in journal file */
40962   i64 jrnlSize;                    /* Size of journal file on disk */
40963   u32 cksum = 0;                   /* Checksum of string zMaster */
40964
40965   assert( pPager->setMaster==0 );
40966   assert( !pagerUseWal(pPager) );
40967
40968   if( !zMaster 
40969    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
40970    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40971   ){
40972     return SQLCIPHER_OK;
40973   }
40974   pPager->setMaster = 1;
40975   assert( isOpen(pPager->jfd) );
40976   assert( pPager->journalHdr <= pPager->journalOff );
40977
40978   /* Calculate the length in bytes and the checksum of zMaster */
40979   for(nMaster=0; zMaster[nMaster]; nMaster++){
40980     cksum += zMaster[nMaster];
40981   }
40982
40983   /* If in full-sync mode, advance to the next disk sector before writing
40984   ** the master journal name. This is in case the previous page written to
40985   ** the journal has already been synced.
40986   */
40987   if( pPager->fullSync ){
40988     pPager->journalOff = journalHdrOffset(pPager);
40989   }
40990   iHdrOff = pPager->journalOff;
40991
40992   /* Write the master journal data to the end of the journal file. If
40993   ** an error occurs, return the error code to the caller.
40994   */
40995   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
40996    || (0 != (rc = sqlcipher3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
40997    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
40998    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
40999    || (0 != (rc = sqlcipher3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
41000   ){
41001     return rc;
41002   }
41003   pPager->journalOff += (nMaster+20);
41004
41005   /* If the pager is in peristent-journal mode, then the physical 
41006   ** journal-file may extend past the end of the master-journal name
41007   ** and 8 bytes of magic data just written to the file. This is 
41008   ** dangerous because the code to rollback a hot-journal file
41009   ** will not be able to find the master-journal name to determine 
41010   ** whether or not the journal is hot. 
41011   **
41012   ** Easiest thing to do in this scenario is to truncate the journal 
41013   ** file to the required size.
41014   */ 
41015   if( SQLCIPHER_OK==(rc = sqlcipher3OsFileSize(pPager->jfd, &jrnlSize))
41016    && jrnlSize>pPager->journalOff
41017   ){
41018     rc = sqlcipher3OsTruncate(pPager->jfd, pPager->journalOff);
41019   }
41020   return rc;
41021 }
41022
41023 /*
41024 ** Find a page in the hash table given its page number. Return
41025 ** a pointer to the page or NULL if the requested page is not 
41026 ** already in memory.
41027 */
41028 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
41029   PgHdr *p;                         /* Return value */
41030
41031   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
41032   ** fail, since no attempt to allocate dynamic memory will be made.
41033   */
41034   (void)sqlcipher3PcacheFetch(pPager->pPCache, pgno, 0, &p);
41035   return p;
41036 }
41037
41038 /*
41039 ** Discard the entire contents of the in-memory page-cache.
41040 */
41041 static void pager_reset(Pager *pPager){
41042   sqlcipher3BackupRestart(pPager->pBackup);
41043   sqlcipher3PcacheClear(pPager->pPCache);
41044 }
41045
41046 /*
41047 ** Free all structures in the Pager.aSavepoint[] array and set both
41048 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
41049 ** if it is open and the pager is not in exclusive mode.
41050 */
41051 static void releaseAllSavepoints(Pager *pPager){
41052   int ii;               /* Iterator for looping through Pager.aSavepoint */
41053   for(ii=0; ii<pPager->nSavepoint; ii++){
41054     sqlcipher3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
41055   }
41056   if( !pPager->exclusiveMode || sqlcipher3IsMemJournal(pPager->sjfd) ){
41057     sqlcipher3OsClose(pPager->sjfd);
41058   }
41059   sqlcipher3_free(pPager->aSavepoint);
41060   pPager->aSavepoint = 0;
41061   pPager->nSavepoint = 0;
41062   pPager->nSubRec = 0;
41063 }
41064
41065 /*
41066 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
41067 ** bitvecs of all open savepoints. Return SQLCIPHER_OK if successful
41068 ** or SQLCIPHER_NOMEM if a malloc failure occurs.
41069 */
41070 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
41071   int ii;                   /* Loop counter */
41072   int rc = SQLCIPHER_OK;       /* Result code */
41073
41074   for(ii=0; ii<pPager->nSavepoint; ii++){
41075     PagerSavepoint *p = &pPager->aSavepoint[ii];
41076     if( pgno<=p->nOrig ){
41077       rc |= sqlcipher3BitvecSet(p->pInSavepoint, pgno);
41078       testcase( rc==SQLCIPHER_NOMEM );
41079       assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_NOMEM );
41080     }
41081   }
41082   return rc;
41083 }
41084
41085 /*
41086 ** This function is a no-op if the pager is in exclusive mode and not
41087 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
41088 ** state.
41089 **
41090 ** If the pager is not in exclusive-access mode, the database file is
41091 ** completely unlocked. If the file is unlocked and the file-system does
41092 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
41093 ** closed (if it is open).
41094 **
41095 ** If the pager is in ERROR state when this function is called, the 
41096 ** contents of the pager cache are discarded before switching back to 
41097 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
41098 ** or not, any journal file left in the file-system will be treated
41099 ** as a hot-journal and rolled back the next time a read-transaction
41100 ** is opened (by this or by any other connection).
41101 */
41102 static void pager_unlock(Pager *pPager){
41103
41104   assert( pPager->eState==PAGER_READER 
41105        || pPager->eState==PAGER_OPEN 
41106        || pPager->eState==PAGER_ERROR 
41107   );
41108
41109   sqlcipher3BitvecDestroy(pPager->pInJournal);
41110   pPager->pInJournal = 0;
41111   releaseAllSavepoints(pPager);
41112
41113   if( pagerUseWal(pPager) ){
41114     assert( !isOpen(pPager->jfd) );
41115     sqlcipher3WalEndReadTransaction(pPager->pWal);
41116     pPager->eState = PAGER_OPEN;
41117   }else if( !pPager->exclusiveMode ){
41118     int rc;                       /* Error code returned by pagerUnlockDb() */
41119     int iDc = isOpen(pPager->fd)?sqlcipher3OsDeviceCharacteristics(pPager->fd):0;
41120
41121     /* If the operating system support deletion of open files, then
41122     ** close the journal file when dropping the database lock.  Otherwise
41123     ** another connection with journal_mode=delete might delete the file
41124     ** out from under us.
41125     */
41126     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
41127     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
41128     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
41129     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
41130     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41131     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
41132     if( 0==(iDc & SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN)
41133      || 1!=(pPager->journalMode & 5)
41134     ){
41135       sqlcipher3OsClose(pPager->jfd);
41136     }
41137
41138     /* If the pager is in the ERROR state and the call to unlock the database
41139     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
41140     ** above the #define for UNKNOWN_LOCK for an explanation of why this
41141     ** is necessary.
41142     */
41143     rc = pagerUnlockDb(pPager, NO_LOCK);
41144     if( rc!=SQLCIPHER_OK && pPager->eState==PAGER_ERROR ){
41145       pPager->eLock = UNKNOWN_LOCK;
41146     }
41147
41148     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
41149     ** without clearing the error code. This is intentional - the error
41150     ** code is cleared and the cache reset in the block below.
41151     */
41152     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
41153     pPager->changeCountDone = 0;
41154     pPager->eState = PAGER_OPEN;
41155   }
41156
41157   /* If Pager.errCode is set, the contents of the pager cache cannot be
41158   ** trusted. Now that there are no outstanding references to the pager,
41159   ** it can safely move back to PAGER_OPEN state. This happens in both
41160   ** normal and exclusive-locking mode.
41161   */
41162   if( pPager->errCode ){
41163     assert( !MEMDB );
41164     pager_reset(pPager);
41165     pPager->changeCountDone = pPager->tempFile;
41166     pPager->eState = PAGER_OPEN;
41167     pPager->errCode = SQLCIPHER_OK;
41168   }
41169
41170   pPager->journalOff = 0;
41171   pPager->journalHdr = 0;
41172   pPager->setMaster = 0;
41173 }
41174
41175 /*
41176 ** This function is called whenever an IOERR or FULL error that requires
41177 ** the pager to transition into the ERROR state may ahve occurred.
41178 ** The first argument is a pointer to the pager structure, the second 
41179 ** the error-code about to be returned by a pager API function. The 
41180 ** value returned is a copy of the second argument to this function. 
41181 **
41182 ** If the second argument is SQLCIPHER_FULL, SQLCIPHER_IOERR or one of the
41183 ** IOERR sub-codes, the pager enters the ERROR state and the error code
41184 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
41185 ** all major API calls on the Pager will immediately return Pager.errCode.
41186 **
41187 ** The ERROR state indicates that the contents of the pager-cache 
41188 ** cannot be trusted. This state can be cleared by completely discarding 
41189 ** the contents of the pager-cache. If a transaction was active when
41190 ** the persistent error occurred, then the rollback journal may need
41191 ** to be replayed to restore the contents of the database file (as if
41192 ** it were a hot-journal).
41193 */
41194 static int pager_error(Pager *pPager, int rc){
41195   int rc2 = rc & 0xff;
41196   assert( rc==SQLCIPHER_OK || !MEMDB );
41197   assert(
41198        pPager->errCode==SQLCIPHER_FULL ||
41199        pPager->errCode==SQLCIPHER_OK ||
41200        (pPager->errCode & 0xff)==SQLCIPHER_IOERR
41201   );
41202   if( rc2==SQLCIPHER_FULL || rc2==SQLCIPHER_IOERR ){
41203     pPager->errCode = rc;
41204     pPager->eState = PAGER_ERROR;
41205   }
41206   return rc;
41207 }
41208
41209 /*
41210 ** This routine ends a transaction. A transaction is usually ended by 
41211 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
41212 ** after rollback of a hot-journal, or if an error occurs while opening
41213 ** the journal file or writing the very first journal-header of a
41214 ** database transaction.
41215 ** 
41216 ** This routine is never called in PAGER_ERROR state. If it is called
41217 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
41218 ** exclusive than a RESERVED lock, it is a no-op.
41219 **
41220 ** Otherwise, any active savepoints are released.
41221 **
41222 ** If the journal file is open, then it is "finalized". Once a journal 
41223 ** file has been finalized it is not possible to use it to roll back a 
41224 ** transaction. Nor will it be considered to be a hot-journal by this
41225 ** or any other database connection. Exactly how a journal is finalized
41226 ** depends on whether or not the pager is running in exclusive mode and
41227 ** the current journal-mode (Pager.journalMode value), as follows:
41228 **
41229 **   journalMode==MEMORY
41230 **     Journal file descriptor is simply closed. This destroys an 
41231 **     in-memory journal.
41232 **
41233 **   journalMode==TRUNCATE
41234 **     Journal file is truncated to zero bytes in size.
41235 **
41236 **   journalMode==PERSIST
41237 **     The first 28 bytes of the journal file are zeroed. This invalidates
41238 **     the first journal header in the file, and hence the entire journal
41239 **     file. An invalid journal file cannot be rolled back.
41240 **
41241 **   journalMode==DELETE
41242 **     The journal file is closed and deleted using sqlcipher3OsDelete().
41243 **
41244 **     If the pager is running in exclusive mode, this method of finalizing
41245 **     the journal file is never used. Instead, if the journalMode is
41246 **     DELETE and the pager is in exclusive mode, the method described under
41247 **     journalMode==PERSIST is used instead.
41248 **
41249 ** After the journal is finalized, the pager moves to PAGER_READER state.
41250 ** If running in non-exclusive rollback mode, the lock on the file is 
41251 ** downgraded to a SHARED_LOCK.
41252 **
41253 ** SQLCIPHER_OK is returned if no error occurs. If an error occurs during
41254 ** any of the IO operations to finalize the journal file or unlock the
41255 ** database then the IO error code is returned to the user. If the 
41256 ** operation to finalize the journal file fails, then the code still
41257 ** tries to unlock the database file if not in exclusive mode. If the
41258 ** unlock operation fails as well, then the first error code related
41259 ** to the first error encountered (the journal finalization one) is
41260 ** returned.
41261 */
41262 static int pager_end_transaction(Pager *pPager, int hasMaster){
41263   int rc = SQLCIPHER_OK;      /* Error code from journal finalization operation */
41264   int rc2 = SQLCIPHER_OK;     /* Error code from db file unlock operation */
41265
41266   /* Do nothing if the pager does not have an open write transaction
41267   ** or at least a RESERVED lock. This function may be called when there
41268   ** is no write-transaction active but a RESERVED or greater lock is
41269   ** held under two circumstances:
41270   **
41271   **   1. After a successful hot-journal rollback, it is called with
41272   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41273   **
41274   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
41275   **      lock switches back to locking_mode=normal and then executes a
41276   **      read-transaction, this function is called with eState==PAGER_READER 
41277   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41278   */
41279   assert( assert_pager_state(pPager) );
41280   assert( pPager->eState!=PAGER_ERROR );
41281   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41282     return SQLCIPHER_OK;
41283   }
41284
41285   releaseAllSavepoints(pPager);
41286   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41287   if( isOpen(pPager->jfd) ){
41288     assert( !pagerUseWal(pPager) );
41289
41290     /* Finalize the journal file. */
41291     if( sqlcipher3IsMemJournal(pPager->jfd) ){
41292       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41293       sqlcipher3OsClose(pPager->jfd);
41294     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41295       if( pPager->journalOff==0 ){
41296         rc = SQLCIPHER_OK;
41297       }else{
41298         rc = sqlcipher3OsTruncate(pPager->jfd, 0);
41299       }
41300       pPager->journalOff = 0;
41301     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41302       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41303     ){
41304       rc = zeroJournalHdr(pPager, hasMaster);
41305       pPager->journalOff = 0;
41306     }else{
41307       /* This branch may be executed with Pager.journalMode==MEMORY if
41308       ** a hot-journal was just rolled back. In this case the journal
41309       ** file should be closed and deleted. If this connection writes to
41310       ** the database file, it will do so using an in-memory journal. 
41311       */
41312       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
41313            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
41314            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
41315       );
41316       sqlcipher3OsClose(pPager->jfd);
41317       if( !pPager->tempFile ){
41318         rc = sqlcipher3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41319       }
41320     }
41321   }
41322
41323 #ifdef SQLCIPHER_CHECK_PAGES
41324   sqlcipher3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41325   if( pPager->dbSize==0 && sqlcipher3PcacheRefCount(pPager->pPCache)>0 ){
41326     PgHdr *p = pager_lookup(pPager, 1);
41327     if( p ){
41328       p->pageHash = 0;
41329       sqlcipher3PagerUnref(p);
41330     }
41331   }
41332 #endif
41333
41334   sqlcipher3BitvecDestroy(pPager->pInJournal);
41335   pPager->pInJournal = 0;
41336   pPager->nRec = 0;
41337   sqlcipher3PcacheCleanAll(pPager->pPCache);
41338   sqlcipher3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41339
41340   if( pagerUseWal(pPager) ){
41341     /* Drop the WAL write-lock, if any. Also, if the connection was in 
41342     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
41343     ** lock held on the database file.
41344     */
41345     rc2 = sqlcipher3WalEndWriteTransaction(pPager->pWal);
41346     assert( rc2==SQLCIPHER_OK );
41347   }
41348   if( !pPager->exclusiveMode 
41349    && (!pagerUseWal(pPager) || sqlcipher3WalExclusiveMode(pPager->pWal, 0))
41350   ){
41351     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41352     pPager->changeCountDone = 0;
41353   }
41354   pPager->eState = PAGER_READER;
41355   pPager->setMaster = 0;
41356
41357   return (rc==SQLCIPHER_OK?rc2:rc);
41358 }
41359
41360 /*
41361 ** Execute a rollback if a transaction is active and unlock the 
41362 ** database file. 
41363 **
41364 ** If the pager has already entered the ERROR state, do not attempt 
41365 ** the rollback at this time. Instead, pager_unlock() is called. The
41366 ** call to pager_unlock() will discard all in-memory pages, unlock
41367 ** the database file and move the pager back to OPEN state. If this 
41368 ** means that there is a hot-journal left in the file-system, the next 
41369 ** connection to obtain a shared lock on the pager (which may be this one) 
41370 ** will roll it back.
41371 **
41372 ** If the pager has not already entered the ERROR state, but an IO or
41373 ** malloc error occurs during a rollback, then this will itself cause 
41374 ** the pager to enter the ERROR state. Which will be cleared by the
41375 ** call to pager_unlock(), as described above.
41376 */
41377 static void pagerUnlockAndRollback(Pager *pPager){
41378   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41379     assert( assert_pager_state(pPager) );
41380     if( pPager->eState>=PAGER_WRITER_LOCKED ){
41381       sqlcipher3BeginBenignMalloc();
41382       sqlcipher3PagerRollback(pPager);
41383       sqlcipher3EndBenignMalloc();
41384     }else if( !pPager->exclusiveMode ){
41385       assert( pPager->eState==PAGER_READER );
41386       pager_end_transaction(pPager, 0);
41387     }
41388   }
41389   pager_unlock(pPager);
41390 }
41391
41392 /*
41393 ** Parameter aData must point to a buffer of pPager->pageSize bytes
41394 ** of data. Compute and return a checksum based ont the contents of the 
41395 ** page of data and the current value of pPager->cksumInit.
41396 **
41397 ** This is not a real checksum. It is really just the sum of the 
41398 ** random initial value (pPager->cksumInit) and every 200th byte
41399 ** of the page data, starting with byte offset (pPager->pageSize%200).
41400 ** Each byte is interpreted as an 8-bit unsigned integer.
41401 **
41402 ** Changing the formula used to compute this checksum results in an
41403 ** incompatible journal file format.
41404 **
41405 ** If journal corruption occurs due to a power failure, the most likely 
41406 ** scenario is that one end or the other of the record will be changed. 
41407 ** It is much less likely that the two ends of the journal record will be
41408 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
41409 ** though fast and simple, catches the mostly likely kind of corruption.
41410 */
41411 static u32 pager_cksum(Pager *pPager, const u8 *aData){
41412   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
41413   int i = pPager->pageSize-200;          /* Loop counter */
41414   while( i>0 ){
41415     cksum += aData[i];
41416     i -= 200;
41417   }
41418   return cksum;
41419 }
41420
41421 /*
41422 ** Report the current page size and number of reserved bytes back
41423 ** to the codec.
41424 */
41425 #ifdef SQLCIPHER_HAS_CODEC
41426 static void pagerReportSize(Pager *pPager){
41427   if( pPager->xCodecSizeChng ){
41428     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41429                            (int)pPager->nReserve);
41430   }
41431 }
41432 #else
41433 # define pagerReportSize(X)     /* No-op if we do not support a codec */
41434 #endif
41435
41436 /*
41437 ** Read a single page from either the journal file (if isMainJrnl==1) or
41438 ** from the sub-journal (if isMainJrnl==0) and playback that page.
41439 ** The page begins at offset *pOffset into the file. The *pOffset
41440 ** value is increased to the start of the next page in the journal.
41441 **
41442 ** The main rollback journal uses checksums - the statement journal does 
41443 ** not.
41444 **
41445 ** If the page number of the page record read from the (sub-)journal file
41446 ** is greater than the current value of Pager.dbSize, then playback is
41447 ** skipped and SQLCIPHER_OK is returned.
41448 **
41449 ** If pDone is not NULL, then it is a record of pages that have already
41450 ** been played back.  If the page at *pOffset has already been played back
41451 ** (if the corresponding pDone bit is set) then skip the playback.
41452 ** Make sure the pDone bit corresponding to the *pOffset page is set
41453 ** prior to returning.
41454 **
41455 ** If the page record is successfully read from the (sub-)journal file
41456 ** and played back, then SQLCIPHER_OK is returned. If an IO error occurs
41457 ** while reading the record from the (sub-)journal file or while writing
41458 ** to the database file, then the IO error code is returned. If data
41459 ** is successfully read from the (sub-)journal file but appears to be
41460 ** corrupted, SQLCIPHER_DONE is returned. Data is considered corrupted in
41461 ** two circumstances:
41462 ** 
41463 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
41464 **   * If the record is being rolled back from the main journal file
41465 **     and the checksum field does not match the record content.
41466 **
41467 ** Neither of these two scenarios are possible during a savepoint rollback.
41468 **
41469 ** If this is a savepoint rollback, then memory may have to be dynamically
41470 ** allocated by this function. If this is the case and an allocation fails,
41471 ** SQLCIPHER_NOMEM is returned.
41472 */
41473 static int pager_playback_one_page(
41474   Pager *pPager,                /* The pager being played back */
41475   i64 *pOffset,                 /* Offset of record to playback */
41476   Bitvec *pDone,                /* Bitvec of pages already played back */
41477   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
41478   int isSavepnt                 /* True for a savepoint rollback */
41479 ){
41480   int rc;
41481   PgHdr *pPg;                   /* An existing page in the cache */
41482   Pgno pgno;                    /* The page number of a page in journal */
41483   u32 cksum;                    /* Checksum used for sanity checking */
41484   char *aData;                  /* Temporary storage for the page */
41485   sqlcipher3_file *jfd;            /* The file descriptor for the journal file */
41486   int isSynced;                 /* True if journal page is synced */
41487
41488   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
41489   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
41490   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
41491   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
41492
41493   aData = pPager->pTmpSpace;
41494   assert( aData );         /* Temp storage must have already been allocated */
41495   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
41496
41497   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
41498   ** or savepoint rollback done at the request of the caller) or this is
41499   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
41500   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
41501   ** only reads from the main journal, not the sub-journal.
41502   */
41503   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
41504        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
41505   );
41506   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
41507
41508   /* Read the page number and page data from the journal or sub-journal
41509   ** file. Return an error code to the caller if an IO error occurs.
41510   */
41511   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
41512   rc = read32bits(jfd, *pOffset, &pgno);
41513   if( rc!=SQLCIPHER_OK ) return rc;
41514   rc = sqlcipher3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
41515   if( rc!=SQLCIPHER_OK ) return rc;
41516   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
41517
41518   /* Sanity checking on the page.  This is more important that I originally
41519   ** thought.  If a power failure occurs while the journal is being written,
41520   ** it could cause invalid data to be written into the journal.  We need to
41521   ** detect this invalid data (with high probability) and ignore it.
41522   */
41523   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
41524     assert( !isSavepnt );
41525     return SQLCIPHER_DONE;
41526   }
41527   if( pgno>(Pgno)pPager->dbSize || sqlcipher3BitvecTest(pDone, pgno) ){
41528     return SQLCIPHER_OK;
41529   }
41530   if( isMainJrnl ){
41531     rc = read32bits(jfd, (*pOffset)-4, &cksum);
41532     if( rc ) return rc;
41533     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
41534       return SQLCIPHER_DONE;
41535     }
41536   }
41537
41538   /* If this page has already been played by before during the current
41539   ** rollback, then don't bother to play it back again.
41540   */
41541   if( pDone && (rc = sqlcipher3BitvecSet(pDone, pgno))!=SQLCIPHER_OK ){
41542     return rc;
41543   }
41544
41545   /* When playing back page 1, restore the nReserve setting
41546   */
41547   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
41548     pPager->nReserve = ((u8*)aData)[20];
41549     pagerReportSize(pPager);
41550   }
41551
41552   /* If the pager is in CACHEMOD state, then there must be a copy of this
41553   ** page in the pager cache. In this case just update the pager cache,
41554   ** not the database file. The page is left marked dirty in this case.
41555   **
41556   ** An exception to the above rule: If the database is in no-sync mode
41557   ** and a page is moved during an incremental vacuum then the page may
41558   ** not be in the pager cache. Later: if a malloc() or IO error occurs
41559   ** during a Movepage() call, then the page may not be in the cache
41560   ** either. So the condition described in the above paragraph is not
41561   ** assert()able.
41562   **
41563   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
41564   ** pager cache if it exists and the main file. The page is then marked 
41565   ** not dirty. Since this code is only executed in PAGER_OPEN state for
41566   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
41567   ** if the pager is in OPEN state.
41568   **
41569   ** Ticket #1171:  The statement journal might contain page content that is
41570   ** different from the page content at the start of the transaction.
41571   ** This occurs when a page is changed prior to the start of a statement
41572   ** then changed again within the statement.  When rolling back such a
41573   ** statement we must not write to the original database unless we know
41574   ** for certain that original page contents are synced into the main rollback
41575   ** journal.  Otherwise, a power loss might leave modified data in the
41576   ** database file without an entry in the rollback journal that can
41577   ** restore the database to its original form.  Two conditions must be
41578   ** met before writing to the database files. (1) the database must be
41579   ** locked.  (2) we know that the original page content is fully synced
41580   ** in the main journal either because the page is not in cache or else
41581   ** the page is marked as needSync==0.
41582   **
41583   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
41584   ** is possible to fail a statement on a database that does not yet exist.
41585   ** Do not attempt to write if database file has never been opened.
41586   */
41587   if( pagerUseWal(pPager) ){
41588     pPg = 0;
41589   }else{
41590     pPg = pager_lookup(pPager, pgno);
41591   }
41592   assert( pPg || !MEMDB );
41593   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
41594   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
41595            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
41596            (isMainJrnl?"main-journal":"sub-journal")
41597   ));
41598   if( isMainJrnl ){
41599     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
41600   }else{
41601     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
41602   }
41603   if( isOpen(pPager->fd)
41604    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41605    && isSynced
41606   ){
41607     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
41608     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
41609     assert( !pagerUseWal(pPager) );
41610     rc = sqlcipher3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
41611     if( pgno>pPager->dbFileSize ){
41612       pPager->dbFileSize = pgno;
41613     }
41614     if( pPager->pBackup ){
41615       CODEC1(pPager, aData, pgno, 3, rc=SQLCIPHER_NOMEM);
41616       sqlcipher3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
41617       CODEC2(pPager, aData, pgno, 7, rc=SQLCIPHER_NOMEM, aData);
41618     }
41619   }else if( !isMainJrnl && pPg==0 ){
41620     /* If this is a rollback of a savepoint and data was not written to
41621     ** the database and the page is not in-memory, there is a potential
41622     ** problem. When the page is next fetched by the b-tree layer, it 
41623     ** will be read from the database file, which may or may not be 
41624     ** current. 
41625     **
41626     ** There are a couple of different ways this can happen. All are quite
41627     ** obscure. When running in synchronous mode, this can only happen 
41628     ** if the page is on the free-list at the start of the transaction, then
41629     ** populated, then moved using sqlcipher3PagerMovepage().
41630     **
41631     ** The solution is to add an in-memory page to the cache containing
41632     ** the data just read from the sub-journal. Mark the page as dirty 
41633     ** and if the pager requires a journal-sync, then mark the page as 
41634     ** requiring a journal-sync before it is written.
41635     */
41636     assert( isSavepnt );
41637     assert( pPager->doNotSpill==0 );
41638     pPager->doNotSpill++;
41639     rc = sqlcipher3PagerAcquire(pPager, pgno, &pPg, 1);
41640     assert( pPager->doNotSpill==1 );
41641     pPager->doNotSpill--;
41642     if( rc!=SQLCIPHER_OK ) return rc;
41643     pPg->flags &= ~PGHDR_NEED_READ;
41644     sqlcipher3PcacheMakeDirty(pPg);
41645   }
41646   if( pPg ){
41647     /* No page should ever be explicitly rolled back that is in use, except
41648     ** for page 1 which is held in use in order to keep the lock on the
41649     ** database active. However such a page may be rolled back as a result
41650     ** of an internal error resulting in an automatic call to
41651     ** sqlcipher3PagerRollback().
41652     */
41653     void *pData;
41654     pData = pPg->pData;
41655     memcpy(pData, (u8*)aData, pPager->pageSize);
41656     pPager->xReiniter(pPg);
41657     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
41658       /* If the contents of this page were just restored from the main 
41659       ** journal file, then its content must be as they were when the 
41660       ** transaction was first opened. In this case we can mark the page
41661       ** as clean, since there will be no need to write it out to the
41662       ** database.
41663       **
41664       ** There is one exception to this rule. If the page is being rolled
41665       ** back as part of a savepoint (or statement) rollback from an 
41666       ** unsynced portion of the main journal file, then it is not safe
41667       ** to mark the page as clean. This is because marking the page as
41668       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
41669       ** already in the journal file (recorded in Pager.pInJournal) and
41670       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
41671       ** again within this transaction, it will be marked as dirty but
41672       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
41673       ** be written out into the database file before its journal file
41674       ** segment is synced. If a crash occurs during or following this,
41675       ** database corruption may ensue.
41676       */
41677       assert( !pagerUseWal(pPager) );
41678       sqlcipher3PcacheMakeClean(pPg);
41679     }
41680     pager_set_pagehash(pPg);
41681
41682     /* If this was page 1, then restore the value of Pager.dbFileVers.
41683     ** Do this before any decoding. */
41684     if( pgno==1 ){
41685       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
41686     }
41687
41688     /* Decode the page just read from disk */
41689     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLCIPHER_NOMEM);
41690     sqlcipher3PcacheRelease(pPg);
41691   }
41692   return rc;
41693 }
41694
41695 /*
41696 ** Parameter zMaster is the name of a master journal file. A single journal
41697 ** file that referred to the master journal file has just been rolled back.
41698 ** This routine checks if it is possible to delete the master journal file,
41699 ** and does so if it is.
41700 **
41701 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
41702 ** available for use within this function.
41703 **
41704 ** When a master journal file is created, it is populated with the names 
41705 ** of all of its child journals, one after another, formatted as utf-8 
41706 ** encoded text. The end of each child journal file is marked with a 
41707 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
41708 ** file for a transaction involving two databases might be:
41709 **
41710 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
41711 **
41712 ** A master journal file may only be deleted once all of its child 
41713 ** journals have been rolled back.
41714 **
41715 ** This function reads the contents of the master-journal file into 
41716 ** memory and loops through each of the child journal names. For
41717 ** each child journal, it checks if:
41718 **
41719 **   * if the child journal exists, and if so
41720 **   * if the child journal contains a reference to master journal 
41721 **     file zMaster
41722 **
41723 ** If a child journal can be found that matches both of the criteria
41724 ** above, this function returns without doing anything. Otherwise, if
41725 ** no such child journal can be found, file zMaster is deleted from
41726 ** the file-system using sqlcipher3OsDelete().
41727 **
41728 ** If an IO error within this function, an error code is returned. This
41729 ** function allocates memory by calling sqlcipher3Malloc(). If an allocation
41730 ** fails, SQLCIPHER_NOMEM is returned. Otherwise, if no IO or malloc errors 
41731 ** occur, SQLCIPHER_OK is returned.
41732 **
41733 ** TODO: This function allocates a single block of memory to load
41734 ** the entire contents of the master journal file. This could be
41735 ** a couple of kilobytes or so - potentially larger than the page 
41736 ** size.
41737 */
41738 static int pager_delmaster(Pager *pPager, const char *zMaster){
41739   sqlcipher3_vfs *pVfs = pPager->pVfs;
41740   int rc;                   /* Return code */
41741   sqlcipher3_file *pMaster;    /* Malloc'd master-journal file descriptor */
41742   sqlcipher3_file *pJournal;   /* Malloc'd child-journal file descriptor */
41743   char *zMasterJournal = 0; /* Contents of master journal file */
41744   i64 nMasterJournal;       /* Size of master journal file */
41745   char *zJournal;           /* Pointer to one journal within MJ file */
41746   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
41747   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
41748
41749   /* Allocate space for both the pJournal and pMaster file descriptors.
41750   ** If successful, open the master journal file for reading.
41751   */
41752   pMaster = (sqlcipher3_file *)sqlcipher3MallocZero(pVfs->szOsFile * 2);
41753   pJournal = (sqlcipher3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
41754   if( !pMaster ){
41755     rc = SQLCIPHER_NOMEM;
41756   }else{
41757     const int flags = (SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_MASTER_JOURNAL);
41758     rc = sqlcipher3OsOpen(pVfs, zMaster, pMaster, flags, 0);
41759   }
41760   if( rc!=SQLCIPHER_OK ) goto delmaster_out;
41761
41762   /* Load the entire master journal file into space obtained from
41763   ** sqlcipher3_malloc() and pointed to by zMasterJournal.   Also obtain
41764   ** sufficient space (in zMasterPtr) to hold the names of master
41765   ** journal files extracted from regular rollback-journals.
41766   */
41767   rc = sqlcipher3OsFileSize(pMaster, &nMasterJournal);
41768   if( rc!=SQLCIPHER_OK ) goto delmaster_out;
41769   nMasterPtr = pVfs->mxPathname+1;
41770   zMasterJournal = sqlcipher3Malloc((int)nMasterJournal + nMasterPtr + 1);
41771   if( !zMasterJournal ){
41772     rc = SQLCIPHER_NOMEM;
41773     goto delmaster_out;
41774   }
41775   zMasterPtr = &zMasterJournal[nMasterJournal+1];
41776   rc = sqlcipher3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
41777   if( rc!=SQLCIPHER_OK ) goto delmaster_out;
41778   zMasterJournal[nMasterJournal] = 0;
41779
41780   zJournal = zMasterJournal;
41781   while( (zJournal-zMasterJournal)<nMasterJournal ){
41782     int exists;
41783     rc = sqlcipher3OsAccess(pVfs, zJournal, SQLCIPHER_ACCESS_EXISTS, &exists);
41784     if( rc!=SQLCIPHER_OK ){
41785       goto delmaster_out;
41786     }
41787     if( exists ){
41788       /* One of the journals pointed to by the master journal exists.
41789       ** Open it and check if it points at the master journal. If
41790       ** so, return without deleting the master journal file.
41791       */
41792       int c;
41793       int flags = (SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_MAIN_JOURNAL);
41794       rc = sqlcipher3OsOpen(pVfs, zJournal, pJournal, flags, 0);
41795       if( rc!=SQLCIPHER_OK ){
41796         goto delmaster_out;
41797       }
41798
41799       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
41800       sqlcipher3OsClose(pJournal);
41801       if( rc!=SQLCIPHER_OK ){
41802         goto delmaster_out;
41803       }
41804
41805       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
41806       if( c ){
41807         /* We have a match. Do not delete the master journal file. */
41808         goto delmaster_out;
41809       }
41810     }
41811     zJournal += (sqlcipher3Strlen30(zJournal)+1);
41812   }
41813  
41814   sqlcipher3OsClose(pMaster);
41815   rc = sqlcipher3OsDelete(pVfs, zMaster, 0);
41816
41817 delmaster_out:
41818   sqlcipher3_free(zMasterJournal);
41819   if( pMaster ){
41820     sqlcipher3OsClose(pMaster);
41821     assert( !isOpen(pJournal) );
41822     sqlcipher3_free(pMaster);
41823   }
41824   return rc;
41825 }
41826
41827
41828 /*
41829 ** This function is used to change the actual size of the database 
41830 ** file in the file-system. This only happens when committing a transaction,
41831 ** or rolling back a transaction (including rolling back a hot-journal).
41832 **
41833 ** If the main database file is not open, or the pager is not in either
41834 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
41835 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
41836 ** If the file on disk is currently larger than nPage pages, then use the VFS
41837 ** xTruncate() method to truncate it.
41838 **
41839 ** Or, it might might be the case that the file on disk is smaller than 
41840 ** nPage pages. Some operating system implementations can get confused if 
41841 ** you try to truncate a file to some size that is larger than it 
41842 ** currently is, so detect this case and write a single zero byte to 
41843 ** the end of the new file instead.
41844 **
41845 ** If successful, return SQLCIPHER_OK. If an IO error occurs while modifying
41846 ** the database file, return the error code to the caller.
41847 */
41848 static int pager_truncate(Pager *pPager, Pgno nPage){
41849   int rc = SQLCIPHER_OK;
41850   assert( pPager->eState!=PAGER_ERROR );
41851   assert( pPager->eState!=PAGER_READER );
41852   
41853   if( isOpen(pPager->fd) 
41854    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
41855   ){
41856     i64 currentSize, newSize;
41857     int szPage = pPager->pageSize;
41858     assert( pPager->eLock==EXCLUSIVE_LOCK );
41859     /* TODO: Is it safe to use Pager.dbFileSize here? */
41860     rc = sqlcipher3OsFileSize(pPager->fd, &currentSize);
41861     newSize = szPage*(i64)nPage;
41862     if( rc==SQLCIPHER_OK && currentSize!=newSize ){
41863       if( currentSize>newSize ){
41864         rc = sqlcipher3OsTruncate(pPager->fd, newSize);
41865       }else{
41866         char *pTmp = pPager->pTmpSpace;
41867         memset(pTmp, 0, szPage);
41868         testcase( (newSize-szPage) <  currentSize );
41869         testcase( (newSize-szPage) == currentSize );
41870         testcase( (newSize-szPage) >  currentSize );
41871         rc = sqlcipher3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
41872       }
41873       if( rc==SQLCIPHER_OK ){
41874         pPager->dbFileSize = nPage;
41875       }
41876     }
41877   }
41878   return rc;
41879 }
41880
41881 /*
41882 ** Set the value of the Pager.sectorSize variable for the given
41883 ** pager based on the value returned by the xSectorSize method
41884 ** of the open database file. The sector size will be used used 
41885 ** to determine the size and alignment of journal header and 
41886 ** master journal pointers within created journal files.
41887 **
41888 ** For temporary files the effective sector size is always 512 bytes.
41889 **
41890 ** Otherwise, for non-temporary files, the effective sector size is
41891 ** the value returned by the xSectorSize() method rounded up to 32 if
41892 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
41893 ** is greater than MAX_SECTOR_SIZE.
41894 */
41895 static void setSectorSize(Pager *pPager){
41896   assert( isOpen(pPager->fd) || pPager->tempFile );
41897
41898   if( !pPager->tempFile ){
41899     /* Sector size doesn't matter for temporary files. Also, the file
41900     ** may not have been opened yet, in which case the OsSectorSize()
41901     ** call will segfault.
41902     */
41903     pPager->sectorSize = sqlcipher3OsSectorSize(pPager->fd);
41904   }
41905   if( pPager->sectorSize<32 ){
41906     pPager->sectorSize = 512;
41907   }
41908   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
41909     assert( MAX_SECTOR_SIZE>=512 );
41910     pPager->sectorSize = MAX_SECTOR_SIZE;
41911   }
41912 }
41913
41914 /*
41915 ** Playback the journal and thus restore the database file to
41916 ** the state it was in before we started making changes.  
41917 **
41918 ** The journal file format is as follows: 
41919 **
41920 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
41921 **  (2)  4 byte big-endian integer which is the number of valid page records
41922 **       in the journal.  If this value is 0xffffffff, then compute the
41923 **       number of page records from the journal size.
41924 **  (3)  4 byte big-endian integer which is the initial value for the 
41925 **       sanity checksum.
41926 **  (4)  4 byte integer which is the number of pages to truncate the
41927 **       database to during a rollback.
41928 **  (5)  4 byte big-endian integer which is the sector size.  The header
41929 **       is this many bytes in size.
41930 **  (6)  4 byte big-endian integer which is the page size.
41931 **  (7)  zero padding out to the next sector size.
41932 **  (8)  Zero or more pages instances, each as follows:
41933 **        +  4 byte page number.
41934 **        +  pPager->pageSize bytes of data.
41935 **        +  4 byte checksum
41936 **
41937 ** When we speak of the journal header, we mean the first 7 items above.
41938 ** Each entry in the journal is an instance of the 8th item.
41939 **
41940 ** Call the value from the second bullet "nRec".  nRec is the number of
41941 ** valid page entries in the journal.  In most cases, you can compute the
41942 ** value of nRec from the size of the journal file.  But if a power
41943 ** failure occurred while the journal was being written, it could be the
41944 ** case that the size of the journal file had already been increased but
41945 ** the extra entries had not yet made it safely to disk.  In such a case,
41946 ** the value of nRec computed from the file size would be too large.  For
41947 ** that reason, we always use the nRec value in the header.
41948 **
41949 ** If the nRec value is 0xffffffff it means that nRec should be computed
41950 ** from the file size.  This value is used when the user selects the
41951 ** no-sync option for the journal.  A power failure could lead to corruption
41952 ** in this case.  But for things like temporary table (which will be
41953 ** deleted when the power is restored) we don't care.  
41954 **
41955 ** If the file opened as the journal file is not a well-formed
41956 ** journal file then all pages up to the first corrupted page are rolled
41957 ** back (or no pages if the journal header is corrupted). The journal file
41958 ** is then deleted and SQLCIPHER_OK returned, just as if no corruption had
41959 ** been encountered.
41960 **
41961 ** If an I/O or malloc() error occurs, the journal-file is not deleted
41962 ** and an error code is returned.
41963 **
41964 ** The isHot parameter indicates that we are trying to rollback a journal
41965 ** that might be a hot journal.  Or, it could be that the journal is 
41966 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
41967 ** If the journal really is hot, reset the pager cache prior rolling
41968 ** back any content.  If the journal is merely persistent, no reset is
41969 ** needed.
41970 */
41971 static int pager_playback(Pager *pPager, int isHot){
41972   sqlcipher3_vfs *pVfs = pPager->pVfs;
41973   i64 szJ;                 /* Size of the journal file in bytes */
41974   u32 nRec;                /* Number of Records in the journal */
41975   u32 u;                   /* Unsigned loop counter */
41976   Pgno mxPg = 0;           /* Size of the original file in pages */
41977   int rc;                  /* Result code of a subroutine */
41978   int res = 1;             /* Value returned by sqlcipher3OsAccess() */
41979   char *zMaster = 0;       /* Name of master journal file if any */
41980   int needPagerReset;      /* True to reset page prior to first page rollback */
41981
41982   /* Figure out how many records are in the journal.  Abort early if
41983   ** the journal is empty.
41984   */
41985   assert( isOpen(pPager->jfd) );
41986   rc = sqlcipher3OsFileSize(pPager->jfd, &szJ);
41987   if( rc!=SQLCIPHER_OK ){
41988     goto end_playback;
41989   }
41990
41991   /* Read the master journal name from the journal, if it is present.
41992   ** If a master journal file name is specified, but the file is not
41993   ** present on disk, then the journal is not hot and does not need to be
41994   ** played back.
41995   **
41996   ** TODO: Technically the following is an error because it assumes that
41997   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41998   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41999   **  mxPathname is 512, which is the same as the minimum allowable value
42000   ** for pageSize.
42001   */
42002   zMaster = pPager->pTmpSpace;
42003   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42004   if( rc==SQLCIPHER_OK && zMaster[0] ){
42005     rc = sqlcipher3OsAccess(pVfs, zMaster, SQLCIPHER_ACCESS_EXISTS, &res);
42006   }
42007   zMaster = 0;
42008   if( rc!=SQLCIPHER_OK || !res ){
42009     goto end_playback;
42010   }
42011   pPager->journalOff = 0;
42012   needPagerReset = isHot;
42013
42014   /* This loop terminates either when a readJournalHdr() or 
42015   ** pager_playback_one_page() call returns SQLCIPHER_DONE or an IO error 
42016   ** occurs. 
42017   */
42018   while( 1 ){
42019     /* Read the next journal header from the journal file.  If there are
42020     ** not enough bytes left in the journal file for a complete header, or
42021     ** it is corrupted, then a process must have failed while writing it.
42022     ** This indicates nothing more needs to be rolled back.
42023     */
42024     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
42025     if( rc!=SQLCIPHER_OK ){ 
42026       if( rc==SQLCIPHER_DONE ){
42027         rc = SQLCIPHER_OK;
42028       }
42029       goto end_playback;
42030     }
42031
42032     /* If nRec is 0xffffffff, then this journal was created by a process
42033     ** working in no-sync mode. This means that the rest of the journal
42034     ** file consists of pages, there are no more journal headers. Compute
42035     ** the value of nRec based on this assumption.
42036     */
42037     if( nRec==0xffffffff ){
42038       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
42039       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
42040     }
42041
42042     /* If nRec is 0 and this rollback is of a transaction created by this
42043     ** process and if this is the final header in the journal, then it means
42044     ** that this part of the journal was being filled but has not yet been
42045     ** synced to disk.  Compute the number of pages based on the remaining
42046     ** size of the file.
42047     **
42048     ** The third term of the test was added to fix ticket #2565.
42049     ** When rolling back a hot journal, nRec==0 always means that the next
42050     ** chunk of the journal contains zero pages to be rolled back.  But
42051     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
42052     ** the journal, it means that the journal might contain additional
42053     ** pages that need to be rolled back and that the number of pages 
42054     ** should be computed based on the journal file size.
42055     */
42056     if( nRec==0 && !isHot &&
42057         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
42058       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
42059     }
42060
42061     /* If this is the first header read from the journal, truncate the
42062     ** database file back to its original size.
42063     */
42064     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
42065       rc = pager_truncate(pPager, mxPg);
42066       if( rc!=SQLCIPHER_OK ){
42067         goto end_playback;
42068       }
42069       pPager->dbSize = mxPg;
42070     }
42071
42072     /* Copy original pages out of the journal and back into the 
42073     ** database file and/or page cache.
42074     */
42075     for(u=0; u<nRec; u++){
42076       if( needPagerReset ){
42077         pager_reset(pPager);
42078         needPagerReset = 0;
42079       }
42080       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
42081       if( rc!=SQLCIPHER_OK ){
42082         if( rc==SQLCIPHER_DONE ){
42083           pPager->journalOff = szJ;
42084           break;
42085         }else if( rc==SQLCIPHER_IOERR_SHORT_READ ){
42086           /* If the journal has been truncated, simply stop reading and
42087           ** processing the journal. This might happen if the journal was
42088           ** not completely written and synced prior to a crash.  In that
42089           ** case, the database should have never been written in the
42090           ** first place so it is OK to simply abandon the rollback. */
42091           rc = SQLCIPHER_OK;
42092           goto end_playback;
42093         }else{
42094           /* If we are unable to rollback, quit and return the error
42095           ** code.  This will cause the pager to enter the error state
42096           ** so that no further harm will be done.  Perhaps the next
42097           ** process to come along will be able to rollback the database.
42098           */
42099           goto end_playback;
42100         }
42101       }
42102     }
42103   }
42104   /*NOTREACHED*/
42105   assert( 0 );
42106
42107 end_playback:
42108   /* Following a rollback, the database file should be back in its original
42109   ** state prior to the start of the transaction, so invoke the
42110   ** SQLCIPHER_FCNTL_DB_UNCHANGED file-control method to disable the
42111   ** assertion that the transaction counter was modified.
42112   */
42113   assert(
42114     pPager->fd->pMethods==0 ||
42115     sqlcipher3OsFileControl(pPager->fd,SQLCIPHER_FCNTL_DB_UNCHANGED,0)>=SQLCIPHER_OK
42116   );
42117
42118   /* If this playback is happening automatically as a result of an IO or 
42119   ** malloc error that occurred after the change-counter was updated but 
42120   ** before the transaction was committed, then the change-counter 
42121   ** modification may just have been reverted. If this happens in exclusive 
42122   ** mode, then subsequent transactions performed by the connection will not
42123   ** update the change-counter at all. This may lead to cache inconsistency
42124   ** problems for other processes at some point in the future. So, just
42125   ** in case this has happened, clear the changeCountDone flag now.
42126   */
42127   pPager->changeCountDone = pPager->tempFile;
42128
42129   if( rc==SQLCIPHER_OK ){
42130     zMaster = pPager->pTmpSpace;
42131     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42132     testcase( rc!=SQLCIPHER_OK );
42133   }
42134   if( rc==SQLCIPHER_OK
42135    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42136   ){
42137     rc = sqlcipher3PagerSync(pPager);
42138   }
42139   if( rc==SQLCIPHER_OK ){
42140     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
42141     testcase( rc!=SQLCIPHER_OK );
42142   }
42143   if( rc==SQLCIPHER_OK && zMaster[0] && res ){
42144     /* If there was a master journal and this routine will return success,
42145     ** see if it is possible to delete the master journal.
42146     */
42147     rc = pager_delmaster(pPager, zMaster);
42148     testcase( rc!=SQLCIPHER_OK );
42149   }
42150
42151   /* The Pager.sectorSize variable may have been updated while rolling
42152   ** back a journal created by a process with a different sector size
42153   ** value. Reset it to the correct value for this process.
42154   */
42155   setSectorSize(pPager);
42156   return rc;
42157 }
42158
42159
42160 /*
42161 ** Read the content for page pPg out of the database file and into 
42162 ** pPg->pData. A shared lock or greater must be held on the database
42163 ** file before this function is called.
42164 **
42165 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
42166 ** the value read from the database file.
42167 **
42168 ** If an IO error occurs, then the IO error is returned to the caller.
42169 ** Otherwise, SQLCIPHER_OK is returned.
42170 */
42171 static int readDbPage(PgHdr *pPg){
42172   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
42173   Pgno pgno = pPg->pgno;       /* Page number to read */
42174   int rc = SQLCIPHER_OK;          /* Return code */
42175   int isInWal = 0;             /* True if page is in log file */
42176   int pgsz = pPager->pageSize; /* Number of bytes to read */
42177
42178   assert( pPager->eState>=PAGER_READER && !MEMDB );
42179   assert( isOpen(pPager->fd) );
42180
42181   if( NEVER(!isOpen(pPager->fd)) ){
42182     assert( pPager->tempFile );
42183     memset(pPg->pData, 0, pPager->pageSize);
42184     return SQLCIPHER_OK;
42185   }
42186
42187   if( pagerUseWal(pPager) ){
42188     /* Try to pull the page from the write-ahead log. */
42189     rc = sqlcipher3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
42190   }
42191   if( rc==SQLCIPHER_OK && !isInWal ){
42192     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
42193     rc = sqlcipher3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
42194     if( rc==SQLCIPHER_IOERR_SHORT_READ ){
42195       rc = SQLCIPHER_OK;
42196     }
42197   }
42198
42199   if( pgno==1 ){
42200     if( rc ){
42201       /* If the read is unsuccessful, set the dbFileVers[] to something
42202       ** that will never be a valid file version.  dbFileVers[] is a copy
42203       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
42204       ** zero or the size of the database in page. Bytes 32..35 and 35..39
42205       ** should be page numbers which are never 0xffffffff.  So filling
42206       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42207       **
42208       ** For an encrypted database, the situation is more complex:  bytes
42209       ** 24..39 of the database are white noise.  But the probability of
42210       ** white noising equaling 16 bytes of 0xff is vanishingly small so
42211       ** we should still be ok.
42212       */
42213       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42214     }else{
42215       u8 *dbFileVers = &((u8*)pPg->pData)[24];
42216       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42217     }
42218   }
42219   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLCIPHER_NOMEM);
42220
42221   PAGER_INCR(sqlcipher3_pager_readdb_count);
42222   PAGER_INCR(pPager->nRead);
42223   IOTRACE(("PGIN %p %d\n", pPager, pgno));
42224   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42225                PAGERID(pPager), pgno, pager_pagehash(pPg)));
42226
42227   return rc;
42228 }
42229
42230 /*
42231 ** Update the value of the change-counter at offsets 24 and 92 in
42232 ** the header and the sqlcipher version number at offset 96.
42233 **
42234 ** This is an unconditional update.  See also the pager_incr_changecounter()
42235 ** routine which only updates the change-counter if the update is actually
42236 ** needed, as determined by the pPager->changeCountDone state variable.
42237 */
42238 static void pager_write_changecounter(PgHdr *pPg){
42239   u32 change_counter;
42240
42241   /* Increment the value just read and write it back to byte 24. */
42242   change_counter = sqlcipher3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42243   put32bits(((char*)pPg->pData)+24, change_counter);
42244
42245   /* Also store the SQLite version number in bytes 96..99 and in
42246   ** bytes 92..95 store the change counter for which the version number
42247   ** is valid. */
42248   put32bits(((char*)pPg->pData)+92, change_counter);
42249   put32bits(((char*)pPg->pData)+96, SQLCIPHER_VERSION_NUMBER);
42250 }
42251
42252 #ifndef SQLCIPHER_OMIT_WAL
42253 /*
42254 ** This function is invoked once for each page that has already been 
42255 ** written into the log file when a WAL transaction is rolled back.
42256 ** Parameter iPg is the page number of said page. The pCtx argument 
42257 ** is actually a pointer to the Pager structure.
42258 **
42259 ** If page iPg is present in the cache, and has no outstanding references,
42260 ** it is discarded. Otherwise, if there are one or more outstanding
42261 ** references, the page content is reloaded from the database. If the
42262 ** attempt to reload content from the database is required and fails, 
42263 ** return an SQLite error code. Otherwise, SQLCIPHER_OK.
42264 */
42265 static int pagerUndoCallback(void *pCtx, Pgno iPg){
42266   int rc = SQLCIPHER_OK;
42267   Pager *pPager = (Pager *)pCtx;
42268   PgHdr *pPg;
42269
42270   pPg = sqlcipher3PagerLookup(pPager, iPg);
42271   if( pPg ){
42272     if( sqlcipher3PcachePageRefcount(pPg)==1 ){
42273       sqlcipher3PcacheDrop(pPg);
42274     }else{
42275       rc = readDbPage(pPg);
42276       if( rc==SQLCIPHER_OK ){
42277         pPager->xReiniter(pPg);
42278       }
42279       sqlcipher3PagerUnref(pPg);
42280     }
42281   }
42282
42283   /* Normally, if a transaction is rolled back, any backup processes are
42284   ** updated as data is copied out of the rollback journal and into the
42285   ** database. This is not generally possible with a WAL database, as
42286   ** rollback involves simply truncating the log file. Therefore, if one
42287   ** or more frames have already been written to the log (and therefore 
42288   ** also copied into the backup databases) as part of this transaction,
42289   ** the backups must be restarted.
42290   */
42291   sqlcipher3BackupRestart(pPager->pBackup);
42292
42293   return rc;
42294 }
42295
42296 /*
42297 ** This function is called to rollback a transaction on a WAL database.
42298 */
42299 static int pagerRollbackWal(Pager *pPager){
42300   int rc;                         /* Return Code */
42301   PgHdr *pList;                   /* List of dirty pages to revert */
42302
42303   /* For all pages in the cache that are currently dirty or have already
42304   ** been written (but not committed) to the log file, do one of the 
42305   ** following:
42306   **
42307   **   + Discard the cached page (if refcount==0), or
42308   **   + Reload page content from the database (if refcount>0).
42309   */
42310   pPager->dbSize = pPager->dbOrigSize;
42311   rc = sqlcipher3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42312   pList = sqlcipher3PcacheDirtyList(pPager->pPCache);
42313   while( pList && rc==SQLCIPHER_OK ){
42314     PgHdr *pNext = pList->pDirty;
42315     rc = pagerUndoCallback((void *)pPager, pList->pgno);
42316     pList = pNext;
42317   }
42318
42319   return rc;
42320 }
42321
42322 /*
42323 ** This function is a wrapper around sqlcipher3WalFrames(). As well as logging
42324 ** the contents of the list of pages headed by pList (connected by pDirty),
42325 ** this function notifies any active backup processes that the pages have
42326 ** changed. 
42327 **
42328 ** The list of pages passed into this routine is always sorted by page number.
42329 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
42330 */ 
42331 static int pagerWalFrames(
42332   Pager *pPager,                  /* Pager object */
42333   PgHdr *pList,                   /* List of frames to log */
42334   Pgno nTruncate,                 /* Database size after this commit */
42335   int isCommit,                   /* True if this is a commit */
42336   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
42337 ){
42338   int rc;                         /* Return code */
42339 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_CHECK_PAGES)
42340   PgHdr *p;                       /* For looping over pages */
42341 #endif
42342
42343   assert( pPager->pWal );
42344   assert( pList );
42345 #ifdef SQLCIPHER_DEBUG
42346   /* Verify that the page list is in accending order */
42347   for(p=pList; p && p->pDirty; p=p->pDirty){
42348     assert( p->pgno < p->pDirty->pgno );
42349   }
42350 #endif
42351
42352   if( isCommit ){
42353     /* If a WAL transaction is being committed, there is no point in writing
42354     ** any pages with page numbers greater than nTruncate into the WAL file.
42355     ** They will never be read by any client. So remove them from the pDirty
42356     ** list here. */
42357     PgHdr *p;
42358     PgHdr **ppNext = &pList;
42359     for(p=pList; (*ppNext = p); p=p->pDirty){
42360       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
42361     }
42362     assert( pList );
42363   }
42364
42365   if( pList->pgno==1 ) pager_write_changecounter(pList);
42366   rc = sqlcipher3WalFrames(pPager->pWal, 
42367       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
42368   );
42369   if( rc==SQLCIPHER_OK && pPager->pBackup ){
42370     PgHdr *p;
42371     for(p=pList; p; p=p->pDirty){
42372       sqlcipher3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42373     }
42374   }
42375
42376 #ifdef SQLCIPHER_CHECK_PAGES
42377   pList = sqlcipher3PcacheDirtyList(pPager->pPCache);
42378   for(p=pList; p; p=p->pDirty){
42379     pager_set_pagehash(p);
42380   }
42381 #endif
42382
42383   return rc;
42384 }
42385
42386 /*
42387 ** Begin a read transaction on the WAL.
42388 **
42389 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
42390 ** makes a snapshot of the database at the current point in time and preserves
42391 ** that snapshot for use by the reader in spite of concurrently changes by
42392 ** other writers or checkpointers.
42393 */
42394 static int pagerBeginReadTransaction(Pager *pPager){
42395   int rc;                         /* Return code */
42396   int changed = 0;                /* True if cache must be reset */
42397
42398   assert( pagerUseWal(pPager) );
42399   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42400
42401   /* sqlcipher3WalEndReadTransaction() was not called for the previous
42402   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
42403   ** are in locking_mode=NORMAL and EndRead() was previously called,
42404   ** the duplicate call is harmless.
42405   */
42406   sqlcipher3WalEndReadTransaction(pPager->pWal);
42407
42408   rc = sqlcipher3WalBeginReadTransaction(pPager->pWal, &changed);
42409   if( rc!=SQLCIPHER_OK || changed ){
42410     pager_reset(pPager);
42411   }
42412
42413   return rc;
42414 }
42415 #endif
42416
42417 /*
42418 ** This function is called as part of the transition from PAGER_OPEN
42419 ** to PAGER_READER state to determine the size of the database file
42420 ** in pages (assuming the page size currently stored in Pager.pageSize).
42421 **
42422 ** If no error occurs, SQLCIPHER_OK is returned and the size of the database
42423 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42424 ** SQLCIPHER_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42425 */
42426 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
42427   Pgno nPage;                     /* Value to return via *pnPage */
42428
42429   /* Query the WAL sub-system for the database size. The WalDbsize()
42430   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
42431   ** if the database size is not available. The database size is not
42432   ** available from the WAL sub-system if the log file is empty or
42433   ** contains no valid committed transactions.
42434   */
42435   assert( pPager->eState==PAGER_OPEN );
42436   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
42437   nPage = sqlcipher3WalDbsize(pPager->pWal);
42438
42439   /* If the database size was not available from the WAL sub-system,
42440   ** determine it based on the size of the database file. If the size
42441   ** of the database file is not an integer multiple of the page-size,
42442   ** round down to the nearest page. Except, any file larger than 0
42443   ** bytes in size is considered to contain at least one page.
42444   */
42445   if( nPage==0 ){
42446     i64 n = 0;                    /* Size of db file in bytes */
42447     assert( isOpen(pPager->fd) || pPager->tempFile );
42448     if( isOpen(pPager->fd) ){
42449       int rc = sqlcipher3OsFileSize(pPager->fd, &n);
42450       if( rc!=SQLCIPHER_OK ){
42451         return rc;
42452       }
42453     }
42454     nPage = (Pgno)(n / pPager->pageSize);
42455     if( nPage==0 && n>0 ){
42456       nPage = 1;
42457     }
42458   }
42459
42460   /* If the current number of pages in the file is greater than the
42461   ** configured maximum pager number, increase the allowed limit so
42462   ** that the file can be read.
42463   */
42464   if( nPage>pPager->mxPgno ){
42465     pPager->mxPgno = (Pgno)nPage;
42466   }
42467
42468   *pnPage = nPage;
42469   return SQLCIPHER_OK;
42470 }
42471
42472 #ifndef SQLCIPHER_OMIT_WAL
42473 /*
42474 ** Check if the *-wal file that corresponds to the database opened by pPager
42475 ** exists if the database is not empy, or verify that the *-wal file does
42476 ** not exist (by deleting it) if the database file is empty.
42477 **
42478 ** If the database is not empty and the *-wal file exists, open the pager
42479 ** in WAL mode.  If the database is empty or if no *-wal file exists and
42480 ** if no error occurs, make sure Pager.journalMode is not set to
42481 ** PAGER_JOURNALMODE_WAL.
42482 **
42483 ** Return SQLCIPHER_OK or an error code.
42484 **
42485 ** The caller must hold a SHARED lock on the database file to call this
42486 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
42487 ** a WAL on a none-empty database, this ensures there is no race condition 
42488 ** between the xAccess() below and an xDelete() being executed by some 
42489 ** other connection.
42490 */
42491 static int pagerOpenWalIfPresent(Pager *pPager){
42492   int rc = SQLCIPHER_OK;
42493   assert( pPager->eState==PAGER_OPEN );
42494   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
42495
42496   if( !pPager->tempFile ){
42497     int isWal;                    /* True if WAL file exists */
42498     Pgno nPage;                   /* Size of the database file */
42499
42500     rc = pagerPagecount(pPager, &nPage);
42501     if( rc ) return rc;
42502     if( nPage==0 ){
42503       rc = sqlcipher3OsDelete(pPager->pVfs, pPager->zWal, 0);
42504       isWal = 0;
42505     }else{
42506       rc = sqlcipher3OsAccess(
42507           pPager->pVfs, pPager->zWal, SQLCIPHER_ACCESS_EXISTS, &isWal
42508       );
42509     }
42510     if( rc==SQLCIPHER_OK ){
42511       if( isWal ){
42512         testcase( sqlcipher3PcachePagecount(pPager->pPCache)==0 );
42513         rc = sqlcipher3PagerOpenWal(pPager, 0);
42514       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
42515         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
42516       }
42517     }
42518   }
42519   return rc;
42520 }
42521 #endif
42522
42523 /*
42524 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
42525 ** the entire master journal file. The case pSavepoint==NULL occurs when 
42526 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
42527 ** savepoint.
42528 **
42529 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
42530 ** being rolled back), then the rollback consists of up to three stages,
42531 ** performed in the order specified:
42532 **
42533 **   * Pages are played back from the main journal starting at byte
42534 **     offset PagerSavepoint.iOffset and continuing to 
42535 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
42536 **     file if PagerSavepoint.iHdrOffset is zero.
42537 **
42538 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
42539 **     back starting from the journal header immediately following 
42540 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
42541 **
42542 **   * Pages are then played back from the sub-journal file, starting
42543 **     with the PagerSavepoint.iSubRec and continuing to the end of
42544 **     the journal file.
42545 **
42546 ** Throughout the rollback process, each time a page is rolled back, the
42547 ** corresponding bit is set in a bitvec structure (variable pDone in the
42548 ** implementation below). This is used to ensure that a page is only
42549 ** rolled back the first time it is encountered in either journal.
42550 **
42551 ** If pSavepoint is NULL, then pages are only played back from the main
42552 ** journal file. There is no need for a bitvec in this case.
42553 **
42554 ** In either case, before playback commences the Pager.dbSize variable
42555 ** is reset to the value that it held at the start of the savepoint 
42556 ** (or transaction). No page with a page-number greater than this value
42557 ** is played back. If one is encountered it is simply skipped.
42558 */
42559 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
42560   i64 szJ;                 /* Effective size of the main journal */
42561   i64 iHdrOff;             /* End of first segment of main-journal records */
42562   int rc = SQLCIPHER_OK;      /* Return code */
42563   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
42564
42565   assert( pPager->eState!=PAGER_ERROR );
42566   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42567
42568   /* Allocate a bitvec to use to store the set of pages rolled back */
42569   if( pSavepoint ){
42570     pDone = sqlcipher3BitvecCreate(pSavepoint->nOrig);
42571     if( !pDone ){
42572       return SQLCIPHER_NOMEM;
42573     }
42574   }
42575
42576   /* Set the database size back to the value it was before the savepoint 
42577   ** being reverted was opened.
42578   */
42579   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
42580   pPager->changeCountDone = pPager->tempFile;
42581
42582   if( !pSavepoint && pagerUseWal(pPager) ){
42583     return pagerRollbackWal(pPager);
42584   }
42585
42586   /* Use pPager->journalOff as the effective size of the main rollback
42587   ** journal.  The actual file might be larger than this in
42588   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
42589   ** past pPager->journalOff is off-limits to us.
42590   */
42591   szJ = pPager->journalOff;
42592   assert( pagerUseWal(pPager)==0 || szJ==0 );
42593
42594   /* Begin by rolling back records from the main journal starting at
42595   ** PagerSavepoint.iOffset and continuing to the next journal header.
42596   ** There might be records in the main journal that have a page number
42597   ** greater than the current database size (pPager->dbSize) but those
42598   ** will be skipped automatically.  Pages are added to pDone as they
42599   ** are played back.
42600   */
42601   if( pSavepoint && !pagerUseWal(pPager) ){
42602     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
42603     pPager->journalOff = pSavepoint->iOffset;
42604     while( rc==SQLCIPHER_OK && pPager->journalOff<iHdrOff ){
42605       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42606     }
42607     assert( rc!=SQLCIPHER_DONE );
42608   }else{
42609     pPager->journalOff = 0;
42610   }
42611
42612   /* Continue rolling back records out of the main journal starting at
42613   ** the first journal header seen and continuing until the effective end
42614   ** of the main journal file.  Continue to skip out-of-range pages and
42615   ** continue adding pages rolled back to pDone.
42616   */
42617   while( rc==SQLCIPHER_OK && pPager->journalOff<szJ ){
42618     u32 ii;            /* Loop counter */
42619     u32 nJRec = 0;     /* Number of Journal Records */
42620     u32 dummy;
42621     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
42622     assert( rc!=SQLCIPHER_DONE );
42623
42624     /*
42625     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
42626     ** test is related to ticket #2565.  See the discussion in the
42627     ** pager_playback() function for additional information.
42628     */
42629     if( nJRec==0 
42630      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
42631     ){
42632       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
42633     }
42634     for(ii=0; rc==SQLCIPHER_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
42635       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42636     }
42637     assert( rc!=SQLCIPHER_DONE );
42638   }
42639   assert( rc!=SQLCIPHER_OK || pPager->journalOff>=szJ );
42640
42641   /* Finally,  rollback pages from the sub-journal.  Page that were
42642   ** previously rolled back out of the main journal (and are hence in pDone)
42643   ** will be skipped.  Out-of-range pages are also skipped.
42644   */
42645   if( pSavepoint ){
42646     u32 ii;            /* Loop counter */
42647     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
42648
42649     if( pagerUseWal(pPager) ){
42650       rc = sqlcipher3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
42651     }
42652     for(ii=pSavepoint->iSubRec; rc==SQLCIPHER_OK && ii<pPager->nSubRec; ii++){
42653       assert( offset==ii*(4+pPager->pageSize) );
42654       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
42655     }
42656     assert( rc!=SQLCIPHER_DONE );
42657   }
42658
42659   sqlcipher3BitvecDestroy(pDone);
42660   if( rc==SQLCIPHER_OK ){
42661     pPager->journalOff = szJ;
42662   }
42663
42664   return rc;
42665 }
42666
42667 /*
42668 ** Change the maximum number of in-memory pages that are allowed.
42669 */
42670 SQLCIPHER_PRIVATE void sqlcipher3PagerSetCachesize(Pager *pPager, int mxPage){
42671   sqlcipher3PcacheSetCachesize(pPager->pPCache, mxPage);
42672 }
42673
42674 /*
42675 ** Adjust the robustness of the database to damage due to OS crashes
42676 ** or power failures by changing the number of syncs()s when writing
42677 ** the rollback journal.  There are three levels:
42678 **
42679 **    OFF       sqlcipher3OsSync() is never called.  This is the default
42680 **              for temporary and transient files.
42681 **
42682 **    NORMAL    The journal is synced once before writes begin on the
42683 **              database.  This is normally adequate protection, but
42684 **              it is theoretically possible, though very unlikely,
42685 **              that an inopertune power failure could leave the journal
42686 **              in a state which would cause damage to the database
42687 **              when it is rolled back.
42688 **
42689 **    FULL      The journal is synced twice before writes begin on the
42690 **              database (with some additional information - the nRec field
42691 **              of the journal header - being written in between the two
42692 **              syncs).  If we assume that writing a
42693 **              single disk sector is atomic, then this mode provides
42694 **              assurance that the journal will not be corrupted to the
42695 **              point of causing damage to the database during rollback.
42696 **
42697 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
42698 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
42699 ** prior to the start of checkpoint and that the database file is synced
42700 ** at the conclusion of the checkpoint if the entire content of the WAL
42701 ** was written back into the database.  But no sync operations occur for
42702 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
42703 ** file is synced following each commit operation, in addition to the
42704 ** syncs associated with NORMAL.
42705 **
42706 ** Do not confuse synchronous=FULL with SQLCIPHER_SYNC_FULL.  The
42707 ** SQLCIPHER_SYNC_FULL macro means to use the MacOSX-style full-fsync
42708 ** using fcntl(F_FULLFSYNC).  SQLCIPHER_SYNC_NORMAL means to do an
42709 ** ordinary fsync() call.  There is no difference between SQLCIPHER_SYNC_FULL
42710 ** and SQLCIPHER_SYNC_NORMAL on platforms other than MacOSX.  But the
42711 ** synchronous=FULL versus synchronous=NORMAL setting determines when
42712 ** the xSync primitive is called and is relevant to all platforms.
42713 **
42714 ** Numeric values associated with these states are OFF==1, NORMAL=2,
42715 ** and FULL=3.
42716 */
42717 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
42718 SQLCIPHER_PRIVATE void sqlcipher3PagerSetSafetyLevel(
42719   Pager *pPager,        /* The pager to set safety level for */
42720   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
42721   int bFullFsync,       /* PRAGMA fullfsync */
42722   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
42723 ){
42724   assert( level>=1 && level<=3 );
42725   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
42726   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
42727   if( pPager->noSync ){
42728     pPager->syncFlags = 0;
42729     pPager->ckptSyncFlags = 0;
42730   }else if( bFullFsync ){
42731     pPager->syncFlags = SQLCIPHER_SYNC_FULL;
42732     pPager->ckptSyncFlags = SQLCIPHER_SYNC_FULL;
42733   }else if( bCkptFullFsync ){
42734     pPager->syncFlags = SQLCIPHER_SYNC_NORMAL;
42735     pPager->ckptSyncFlags = SQLCIPHER_SYNC_FULL;
42736   }else{
42737     pPager->syncFlags = SQLCIPHER_SYNC_NORMAL;
42738     pPager->ckptSyncFlags = SQLCIPHER_SYNC_NORMAL;
42739   }
42740 }
42741 #endif
42742
42743 /*
42744 ** The following global variable is incremented whenever the library
42745 ** attempts to open a temporary file.  This information is used for
42746 ** testing and analysis only.  
42747 */
42748 #ifdef SQLCIPHER_TEST
42749 SQLCIPHER_API int sqlcipher3_opentemp_count = 0;
42750 #endif
42751
42752 /*
42753 ** Open a temporary file.
42754 **
42755 ** Write the file descriptor into *pFile. Return SQLCIPHER_OK on success 
42756 ** or some other error code if we fail. The OS will automatically 
42757 ** delete the temporary file when it is closed.
42758 **
42759 ** The flags passed to the VFS layer xOpen() call are those specified
42760 ** by parameter vfsFlags ORed with the following:
42761 **
42762 **     SQLCIPHER_OPEN_READWRITE
42763 **     SQLCIPHER_OPEN_CREATE
42764 **     SQLCIPHER_OPEN_EXCLUSIVE
42765 **     SQLCIPHER_OPEN_DELETEONCLOSE
42766 */
42767 static int pagerOpentemp(
42768   Pager *pPager,        /* The pager object */
42769   sqlcipher3_file *pFile,  /* Write the file descriptor here */
42770   int vfsFlags          /* Flags passed through to the VFS */
42771 ){
42772   int rc;               /* Return code */
42773
42774 #ifdef SQLCIPHER_TEST
42775   sqlcipher3_opentemp_count++;  /* Used for testing and analysis only */
42776 #endif
42777
42778   vfsFlags |=  SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE |
42779             SQLCIPHER_OPEN_EXCLUSIVE | SQLCIPHER_OPEN_DELETEONCLOSE;
42780   rc = sqlcipher3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
42781   assert( rc!=SQLCIPHER_OK || isOpen(pFile) );
42782   return rc;
42783 }
42784
42785 /*
42786 ** Set the busy handler function.
42787 **
42788 ** The pager invokes the busy-handler if sqlcipher3OsLock() returns 
42789 ** SQLCIPHER_BUSY when trying to upgrade from no-lock to a SHARED lock,
42790 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
42791 ** lock. It does *not* invoke the busy handler when upgrading from
42792 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
42793 ** (which occurs during hot-journal rollback). Summary:
42794 **
42795 **   Transition                        | Invokes xBusyHandler
42796 **   --------------------------------------------------------
42797 **   NO_LOCK       -> SHARED_LOCK      | Yes
42798 **   SHARED_LOCK   -> RESERVED_LOCK    | No
42799 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
42800 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
42801 **
42802 ** If the busy-handler callback returns non-zero, the lock is 
42803 ** retried. If it returns zero, then the SQLCIPHER_BUSY error is
42804 ** returned to the caller of the pager API function.
42805 */
42806 SQLCIPHER_PRIVATE void sqlcipher3PagerSetBusyhandler(
42807   Pager *pPager,                       /* Pager object */
42808   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
42809   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
42810 ){  
42811   pPager->xBusyHandler = xBusyHandler;
42812   pPager->pBusyHandlerArg = pBusyHandlerArg;
42813 }
42814
42815 /*
42816 ** Change the page size used by the Pager object. The new page size 
42817 ** is passed in *pPageSize.
42818 **
42819 ** If the pager is in the error state when this function is called, it
42820 ** is a no-op. The value returned is the error state error code (i.e. 
42821 ** one of SQLCIPHER_IOERR, an SQLCIPHER_IOERR_xxx sub-code or SQLCIPHER_FULL).
42822 **
42823 ** Otherwise, if all of the following are true:
42824 **
42825 **   * the new page size (value of *pPageSize) is valid (a power 
42826 **     of two between 512 and SQLCIPHER_MAX_PAGE_SIZE, inclusive), and
42827 **
42828 **   * there are no outstanding page references, and
42829 **
42830 **   * the database is either not an in-memory database or it is
42831 **     an in-memory database that currently consists of zero pages.
42832 **
42833 ** then the pager object page size is set to *pPageSize.
42834 **
42835 ** If the page size is changed, then this function uses sqlcipher3PagerMalloc() 
42836 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
42837 ** fails, SQLCIPHER_NOMEM is returned and the page size remains unchanged. 
42838 ** In all other cases, SQLCIPHER_OK is returned.
42839 **
42840 ** If the page size is not changed, either because one of the enumerated
42841 ** conditions above is not true, the pager was in error state when this
42842 ** function was called, or because the memory allocation attempt failed, 
42843 ** then *pPageSize is set to the old, retained page size before returning.
42844 */
42845 SQLCIPHER_PRIVATE int sqlcipher3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
42846   int rc = SQLCIPHER_OK;
42847
42848   /* It is not possible to do a full assert_pager_state() here, as this
42849   ** function may be called from within PagerOpen(), before the state
42850   ** of the Pager object is internally consistent.
42851   **
42852   ** At one point this function returned an error if the pager was in 
42853   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
42854   ** there is at least one outstanding page reference, this function
42855   ** is a no-op for that case anyhow.
42856   */
42857
42858   u32 pageSize = *pPageSize;
42859   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLCIPHER_MAX_PAGE_SIZE) );
42860   if( (pPager->memDb==0 || pPager->dbSize==0)
42861    && sqlcipher3PcacheRefCount(pPager->pPCache)==0 
42862    && pageSize && pageSize!=(u32)pPager->pageSize 
42863   ){
42864     char *pNew = NULL;             /* New temp space */
42865     i64 nByte = 0;
42866
42867     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
42868       rc = sqlcipher3OsFileSize(pPager->fd, &nByte);
42869     }
42870     if( rc==SQLCIPHER_OK ){
42871       pNew = (char *)sqlcipher3PageMalloc(pageSize);
42872       if( !pNew ) rc = SQLCIPHER_NOMEM;
42873     }
42874
42875     if( rc==SQLCIPHER_OK ){
42876       pager_reset(pPager);
42877       pPager->dbSize = (Pgno)(nByte/pageSize);
42878       pPager->pageSize = pageSize;
42879       sqlcipher3PageFree(pPager->pTmpSpace);
42880       pPager->pTmpSpace = pNew;
42881       sqlcipher3PcacheSetPageSize(pPager->pPCache, pageSize);
42882     }
42883   }
42884
42885   *pPageSize = pPager->pageSize;
42886   if( rc==SQLCIPHER_OK ){
42887     if( nReserve<0 ) nReserve = pPager->nReserve;
42888     assert( nReserve>=0 && nReserve<1000 );
42889     pPager->nReserve = (i16)nReserve;
42890     pagerReportSize(pPager);
42891   }
42892   return rc;
42893 }
42894
42895 /*
42896 ** Return a pointer to the "temporary page" buffer held internally
42897 ** by the pager.  This is a buffer that is big enough to hold the
42898 ** entire content of a database page.  This buffer is used internally
42899 ** during rollback and will be overwritten whenever a rollback
42900 ** occurs.  But other modules are free to use it too, as long as
42901 ** no rollbacks are happening.
42902 */
42903 SQLCIPHER_PRIVATE void *sqlcipher3PagerTempSpace(Pager *pPager){
42904   return pPager->pTmpSpace;
42905 }
42906
42907 /*
42908 ** Attempt to set the maximum database page count if mxPage is positive. 
42909 ** Make no changes if mxPage is zero or negative.  And never reduce the
42910 ** maximum page count below the current size of the database.
42911 **
42912 ** Regardless of mxPage, return the current maximum page count.
42913 */
42914 SQLCIPHER_PRIVATE int sqlcipher3PagerMaxPageCount(Pager *pPager, int mxPage){
42915   if( mxPage>0 ){
42916     pPager->mxPgno = mxPage;
42917   }
42918   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
42919   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
42920   return pPager->mxPgno;
42921 }
42922
42923 /*
42924 ** The following set of routines are used to disable the simulated
42925 ** I/O error mechanism.  These routines are used to avoid simulated
42926 ** errors in places where we do not care about errors.
42927 **
42928 ** Unless -DSQLCIPHER_TEST=1 is used, these routines are all no-ops
42929 ** and generate no code.
42930 */
42931 #ifdef SQLCIPHER_TEST
42932 SQLCIPHER_API extern int sqlcipher3_io_error_pending;
42933 SQLCIPHER_API extern int sqlcipher3_io_error_hit;
42934 static int saved_cnt;
42935 void disable_simulated_io_errors(void){
42936   saved_cnt = sqlcipher3_io_error_pending;
42937   sqlcipher3_io_error_pending = -1;
42938 }
42939 void enable_simulated_io_errors(void){
42940   sqlcipher3_io_error_pending = saved_cnt;
42941 }
42942 #else
42943 # define disable_simulated_io_errors()
42944 # define enable_simulated_io_errors()
42945 #endif
42946
42947 /*
42948 ** Read the first N bytes from the beginning of the file into memory
42949 ** that pDest points to. 
42950 **
42951 ** If the pager was opened on a transient file (zFilename==""), or
42952 ** opened on a file less than N bytes in size, the output buffer is
42953 ** zeroed and SQLCIPHER_OK returned. The rationale for this is that this 
42954 ** function is used to read database headers, and a new transient or
42955 ** zero sized database has a header than consists entirely of zeroes.
42956 **
42957 ** If any IO error apart from SQLCIPHER_IOERR_SHORT_READ is encountered,
42958 ** the error code is returned to the caller and the contents of the
42959 ** output buffer undefined.
42960 */
42961 SQLCIPHER_PRIVATE int sqlcipher3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42962   int rc = SQLCIPHER_OK;
42963   memset(pDest, 0, N);
42964   assert( isOpen(pPager->fd) || pPager->tempFile );
42965
42966   /* This routine is only called by btree immediately after creating
42967   ** the Pager object.  There has not been an opportunity to transition
42968   ** to WAL mode yet.
42969   */
42970   assert( !pagerUseWal(pPager) );
42971
42972   if( isOpen(pPager->fd) ){
42973     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42974     rc = sqlcipher3OsRead(pPager->fd, pDest, N, 0);
42975     if( rc==SQLCIPHER_IOERR_SHORT_READ ){
42976       rc = SQLCIPHER_OK;
42977     }
42978   }
42979   return rc;
42980 }
42981
42982 /*
42983 ** This function may only be called when a read-transaction is open on
42984 ** the pager. It returns the total number of pages in the database.
42985 **
42986 ** However, if the file is between 1 and <page-size> bytes in size, then 
42987 ** this is considered a 1 page file.
42988 */
42989 SQLCIPHER_PRIVATE void sqlcipher3PagerPagecount(Pager *pPager, int *pnPage){
42990   assert( pPager->eState>=PAGER_READER );
42991   assert( pPager->eState!=PAGER_WRITER_FINISHED );
42992   *pnPage = (int)pPager->dbSize;
42993 }
42994
42995
42996 /*
42997 ** Try to obtain a lock of type locktype on the database file. If
42998 ** a similar or greater lock is already held, this function is a no-op
42999 ** (returning SQLCIPHER_OK immediately).
43000 **
43001 ** Otherwise, attempt to obtain the lock using sqlcipher3OsLock(). Invoke 
43002 ** the busy callback if the lock is currently not available. Repeat 
43003 ** until the busy callback returns false or until the attempt to 
43004 ** obtain the lock succeeds.
43005 **
43006 ** Return SQLCIPHER_OK on success and an error code if we cannot obtain
43007 ** the lock. If the lock is obtained successfully, set the Pager.state 
43008 ** variable to locktype before returning.
43009 */
43010 static int pager_wait_on_lock(Pager *pPager, int locktype){
43011   int rc;                              /* Return code */
43012
43013   /* Check that this is either a no-op (because the requested lock is 
43014   ** already held, or one of the transistions that the busy-handler
43015   ** may be invoked during, according to the comment above
43016   ** sqlcipher3PagerSetBusyhandler().
43017   */
43018   assert( (pPager->eLock>=locktype)
43019        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
43020        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
43021   );
43022
43023   do {
43024     rc = pagerLockDb(pPager, locktype);
43025   }while( rc==SQLCIPHER_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
43026   return rc;
43027 }
43028
43029 /*
43030 ** Function assertTruncateConstraint(pPager) checks that one of the 
43031 ** following is true for all dirty pages currently in the page-cache:
43032 **
43033 **   a) The page number is less than or equal to the size of the 
43034 **      current database image, in pages, OR
43035 **
43036 **   b) if the page content were written at this time, it would not
43037 **      be necessary to write the current content out to the sub-journal
43038 **      (as determined by function subjRequiresPage()).
43039 **
43040 ** If the condition asserted by this function were not true, and the
43041 ** dirty page were to be discarded from the cache via the pagerStress()
43042 ** routine, pagerStress() would not write the current page content to
43043 ** the database file. If a savepoint transaction were rolled back after
43044 ** this happened, the correct behaviour would be to restore the current
43045 ** content of the page. However, since this content is not present in either
43046 ** the database file or the portion of the rollback journal and 
43047 ** sub-journal rolled back the content could not be restored and the
43048 ** database image would become corrupt. It is therefore fortunate that 
43049 ** this circumstance cannot arise.
43050 */
43051 #if defined(SQLCIPHER_DEBUG)
43052 static void assertTruncateConstraintCb(PgHdr *pPg){
43053   assert( pPg->flags&PGHDR_DIRTY );
43054   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
43055 }
43056 static void assertTruncateConstraint(Pager *pPager){
43057   sqlcipher3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
43058 }
43059 #else
43060 # define assertTruncateConstraint(pPager)
43061 #endif
43062
43063 /*
43064 ** Truncate the in-memory database file image to nPage pages. This 
43065 ** function does not actually modify the database file on disk. It 
43066 ** just sets the internal state of the pager object so that the 
43067 ** truncation will be done when the current transaction is committed.
43068 */
43069 SQLCIPHER_PRIVATE void sqlcipher3PagerTruncateImage(Pager *pPager, Pgno nPage){
43070   assert( pPager->dbSize>=nPage );
43071   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43072   pPager->dbSize = nPage;
43073   assertTruncateConstraint(pPager);
43074 }
43075
43076
43077 /*
43078 ** This function is called before attempting a hot-journal rollback. It
43079 ** syncs the journal file to disk, then sets pPager->journalHdr to the
43080 ** size of the journal file so that the pager_playback() routine knows
43081 ** that the entire journal file has been synced.
43082 **
43083 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
43084 ** that if a power-failure occurs during the rollback, the process that
43085 ** attempts rollback following system recovery sees the same journal
43086 ** content as this process.
43087 **
43088 ** If everything goes as planned, SQLCIPHER_OK is returned. Otherwise, 
43089 ** an SQLite error code.
43090 */
43091 static int pagerSyncHotJournal(Pager *pPager){
43092   int rc = SQLCIPHER_OK;
43093   if( !pPager->noSync ){
43094     rc = sqlcipher3OsSync(pPager->jfd, SQLCIPHER_SYNC_NORMAL);
43095   }
43096   if( rc==SQLCIPHER_OK ){
43097     rc = sqlcipher3OsFileSize(pPager->jfd, &pPager->journalHdr);
43098   }
43099   return rc;
43100 }
43101
43102 /*
43103 ** Shutdown the page cache.  Free all memory and close all files.
43104 **
43105 ** If a transaction was in progress when this routine is called, that
43106 ** transaction is rolled back.  All outstanding pages are invalidated
43107 ** and their memory is freed.  Any attempt to use a page associated
43108 ** with this page cache after this function returns will likely
43109 ** result in a coredump.
43110 **
43111 ** This function always succeeds. If a transaction is active an attempt
43112 ** is made to roll it back. If an error occurs during the rollback 
43113 ** a hot journal may be left in the filesystem but no error is returned
43114 ** to the caller.
43115 */
43116 SQLCIPHER_PRIVATE int sqlcipher3PagerClose(Pager *pPager){
43117   u8 *pTmp = (u8 *)pPager->pTmpSpace;
43118
43119   assert( assert_pager_state(pPager) );
43120   disable_simulated_io_errors();
43121   sqlcipher3BeginBenignMalloc();
43122   /* pPager->errCode = 0; */
43123   pPager->exclusiveMode = 0;
43124 #ifndef SQLCIPHER_OMIT_WAL
43125   sqlcipher3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
43126   pPager->pWal = 0;
43127 #endif
43128   pager_reset(pPager);
43129   if( MEMDB ){
43130     pager_unlock(pPager);
43131   }else{
43132     /* If it is open, sync the journal file before calling UnlockAndRollback.
43133     ** If this is not done, then an unsynced portion of the open journal 
43134     ** file may be played back into the database. If a power failure occurs 
43135     ** while this is happening, the database could become corrupt.
43136     **
43137     ** If an error occurs while trying to sync the journal, shift the pager
43138     ** into the ERROR state. This causes UnlockAndRollback to unlock the
43139     ** database and close the journal file without attempting to roll it
43140     ** back or finalize it. The next database user will have to do hot-journal
43141     ** rollback before accessing the database file.
43142     */
43143     if( isOpen(pPager->jfd) ){
43144       pager_error(pPager, pagerSyncHotJournal(pPager));
43145     }
43146     pagerUnlockAndRollback(pPager);
43147   }
43148   sqlcipher3EndBenignMalloc();
43149   enable_simulated_io_errors();
43150   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
43151   IOTRACE(("CLOSE %p\n", pPager))
43152   sqlcipher3OsClose(pPager->jfd);
43153   sqlcipher3OsClose(pPager->fd);
43154   sqlcipher3PageFree(pTmp);
43155   sqlcipher3PcacheClose(pPager->pPCache);
43156
43157 #ifdef SQLCIPHER_HAS_CODEC
43158   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43159 #endif
43160
43161   assert( !pPager->aSavepoint && !pPager->pInJournal );
43162   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
43163
43164   sqlcipher3_free(pPager);
43165   return SQLCIPHER_OK;
43166 }
43167
43168 #if !defined(NDEBUG) || defined(SQLCIPHER_TEST)
43169 /*
43170 ** Return the page number for page pPg.
43171 */
43172 SQLCIPHER_PRIVATE Pgno sqlcipher3PagerPagenumber(DbPage *pPg){
43173   return pPg->pgno;
43174 }
43175 #endif
43176
43177 /*
43178 ** Increment the reference count for page pPg.
43179 */
43180 SQLCIPHER_PRIVATE void sqlcipher3PagerRef(DbPage *pPg){
43181   sqlcipher3PcacheRef(pPg);
43182 }
43183
43184 /*
43185 ** Sync the journal. In other words, make sure all the pages that have
43186 ** been written to the journal have actually reached the surface of the
43187 ** disk and can be restored in the event of a hot-journal rollback.
43188 **
43189 ** If the Pager.noSync flag is set, then this function is a no-op.
43190 ** Otherwise, the actions required depend on the journal-mode and the 
43191 ** device characteristics of the the file-system, as follows:
43192 **
43193 **   * If the journal file is an in-memory journal file, no action need
43194 **     be taken.
43195 **
43196 **   * Otherwise, if the device does not support the SAFE_APPEND property,
43197 **     then the nRec field of the most recently written journal header
43198 **     is updated to contain the number of journal records that have
43199 **     been written following it. If the pager is operating in full-sync
43200 **     mode, then the journal file is synced before this field is updated.
43201 **
43202 **   * If the device does not support the SEQUENTIAL property, then 
43203 **     journal file is synced.
43204 **
43205 ** Or, in pseudo-code:
43206 **
43207 **   if( NOT <in-memory journal> ){
43208 **     if( NOT SAFE_APPEND ){
43209 **       if( <full-sync mode> ) xSync(<journal file>);
43210 **       <update nRec field>
43211 **     } 
43212 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
43213 **   }
43214 **
43215 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
43216 ** page currently held in memory before returning SQLCIPHER_OK. If an IO
43217 ** error is encountered, then the IO error code is returned to the caller.
43218 */
43219 static int syncJournal(Pager *pPager, int newHdr){
43220   int rc;                         /* Return code */
43221
43222   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43223        || pPager->eState==PAGER_WRITER_DBMOD
43224   );
43225   assert( assert_pager_state(pPager) );
43226   assert( !pagerUseWal(pPager) );
43227
43228   rc = sqlcipher3PagerExclusiveLock(pPager);
43229   if( rc!=SQLCIPHER_OK ) return rc;
43230
43231   if( !pPager->noSync ){
43232     assert( !pPager->tempFile );
43233     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
43234       const int iDc = sqlcipher3OsDeviceCharacteristics(pPager->fd);
43235       assert( isOpen(pPager->jfd) );
43236
43237       if( 0==(iDc&SQLCIPHER_IOCAP_SAFE_APPEND) ){
43238         /* This block deals with an obscure problem. If the last connection
43239         ** that wrote to this database was operating in persistent-journal
43240         ** mode, then the journal file may at this point actually be larger
43241         ** than Pager.journalOff bytes. If the next thing in the journal
43242         ** file happens to be a journal-header (written as part of the
43243         ** previous connection's transaction), and a crash or power-failure 
43244         ** occurs after nRec is updated but before this connection writes 
43245         ** anything else to the journal file (or commits/rolls back its 
43246         ** transaction), then SQLite may become confused when doing the 
43247         ** hot-journal rollback following recovery. It may roll back all
43248         ** of this connections data, then proceed to rolling back the old,
43249         ** out-of-date data that follows it. Database corruption.
43250         **
43251         ** To work around this, if the journal file does appear to contain
43252         ** a valid header following Pager.journalOff, then write a 0x00
43253         ** byte to the start of it to prevent it from being recognized.
43254         **
43255         ** Variable iNextHdrOffset is set to the offset at which this
43256         ** problematic header will occur, if it exists. aMagic is used 
43257         ** as a temporary buffer to inspect the first couple of bytes of
43258         ** the potential journal header.
43259         */
43260         i64 iNextHdrOffset;
43261         u8 aMagic[8];
43262         u8 zHeader[sizeof(aJournalMagic)+4];
43263
43264         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43265         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
43266
43267         iNextHdrOffset = journalHdrOffset(pPager);
43268         rc = sqlcipher3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
43269         if( rc==SQLCIPHER_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
43270           static const u8 zerobyte = 0;
43271           rc = sqlcipher3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
43272         }
43273         if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_IOERR_SHORT_READ ){
43274           return rc;
43275         }
43276
43277         /* Write the nRec value into the journal file header. If in
43278         ** full-synchronous mode, sync the journal first. This ensures that
43279         ** all data has really hit the disk before nRec is updated to mark
43280         ** it as a candidate for rollback.
43281         **
43282         ** This is not required if the persistent media supports the
43283         ** SAFE_APPEND property. Because in this case it is not possible 
43284         ** for garbage data to be appended to the file, the nRec field
43285         ** is populated with 0xFFFFFFFF when the journal header is written
43286         ** and never needs to be updated.
43287         */
43288         if( pPager->fullSync && 0==(iDc&SQLCIPHER_IOCAP_SEQUENTIAL) ){
43289           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43290           IOTRACE(("JSYNC %p\n", pPager))
43291           rc = sqlcipher3OsSync(pPager->jfd, pPager->syncFlags);
43292           if( rc!=SQLCIPHER_OK ) return rc;
43293         }
43294         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
43295         rc = sqlcipher3OsWrite(
43296             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
43297         );
43298         if( rc!=SQLCIPHER_OK ) return rc;
43299       }
43300       if( 0==(iDc&SQLCIPHER_IOCAP_SEQUENTIAL) ){
43301         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43302         IOTRACE(("JSYNC %p\n", pPager))
43303         rc = sqlcipher3OsSync(pPager->jfd, pPager->syncFlags| 
43304           (pPager->syncFlags==SQLCIPHER_SYNC_FULL?SQLCIPHER_SYNC_DATAONLY:0)
43305         );
43306         if( rc!=SQLCIPHER_OK ) return rc;
43307       }
43308
43309       pPager->journalHdr = pPager->journalOff;
43310       if( newHdr && 0==(iDc&SQLCIPHER_IOCAP_SAFE_APPEND) ){
43311         pPager->nRec = 0;
43312         rc = writeJournalHdr(pPager);
43313         if( rc!=SQLCIPHER_OK ) return rc;
43314       }
43315     }else{
43316       pPager->journalHdr = pPager->journalOff;
43317     }
43318   }
43319
43320   /* Unless the pager is in noSync mode, the journal file was just 
43321   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
43322   ** all pages.
43323   */
43324   sqlcipher3PcacheClearSyncFlags(pPager->pPCache);
43325   pPager->eState = PAGER_WRITER_DBMOD;
43326   assert( assert_pager_state(pPager) );
43327   return SQLCIPHER_OK;
43328 }
43329
43330 /*
43331 ** The argument is the first in a linked list of dirty pages connected
43332 ** by the PgHdr.pDirty pointer. This function writes each one of the
43333 ** in-memory pages in the list to the database file. The argument may
43334 ** be NULL, representing an empty list. In this case this function is
43335 ** a no-op.
43336 **
43337 ** The pager must hold at least a RESERVED lock when this function
43338 ** is called. Before writing anything to the database file, this lock
43339 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
43340 ** SQLCIPHER_BUSY is returned and no data is written to the database file.
43341 ** 
43342 ** If the pager is a temp-file pager and the actual file-system file
43343 ** is not yet open, it is created and opened before any data is 
43344 ** written out.
43345 **
43346 ** Once the lock has been upgraded and, if necessary, the file opened,
43347 ** the pages are written out to the database file in list order. Writing
43348 ** a page is skipped if it meets either of the following criteria:
43349 **
43350 **   * The page number is greater than Pager.dbSize, or
43351 **   * The PGHDR_DONT_WRITE flag is set on the page.
43352 **
43353 ** If writing out a page causes the database file to grow, Pager.dbFileSize
43354 ** is updated accordingly. If page 1 is written out, then the value cached
43355 ** in Pager.dbFileVers[] is updated to match the new value stored in
43356 ** the database file.
43357 **
43358 ** If everything is successful, SQLCIPHER_OK is returned. If an IO error 
43359 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
43360 ** be obtained, SQLCIPHER_BUSY is returned.
43361 */
43362 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
43363   int rc = SQLCIPHER_OK;                  /* Return code */
43364
43365   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
43366   assert( !pagerUseWal(pPager) );
43367   assert( pPager->eState==PAGER_WRITER_DBMOD );
43368   assert( pPager->eLock==EXCLUSIVE_LOCK );
43369
43370   /* If the file is a temp-file has not yet been opened, open it now. It
43371   ** is not possible for rc to be other than SQLCIPHER_OK if this branch
43372   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
43373   */
43374   if( !isOpen(pPager->fd) ){
43375     assert( pPager->tempFile && rc==SQLCIPHER_OK );
43376     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
43377   }
43378
43379   /* Before the first write, give the VFS a hint of what the final
43380   ** file size will be.
43381   */
43382   assert( rc!=SQLCIPHER_OK || isOpen(pPager->fd) );
43383   if( rc==SQLCIPHER_OK && pPager->dbSize>pPager->dbHintSize ){
43384     sqlcipher3_int64 szFile = pPager->pageSize * (sqlcipher3_int64)pPager->dbSize;
43385     sqlcipher3OsFileControl(pPager->fd, SQLCIPHER_FCNTL_SIZE_HINT, &szFile);
43386     pPager->dbHintSize = pPager->dbSize;
43387   }
43388
43389   while( rc==SQLCIPHER_OK && pList ){
43390     Pgno pgno = pList->pgno;
43391
43392     /* If there are dirty pages in the page cache with page numbers greater
43393     ** than Pager.dbSize, this means sqlcipher3PagerTruncateImage() was called to
43394     ** make the file smaller (presumably by auto-vacuum code). Do not write
43395     ** any such pages to the file.
43396     **
43397     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
43398     ** set (set by sqlcipher3PagerDontWrite()).
43399     */
43400     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
43401       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
43402       char *pData;                                   /* Data to write */    
43403
43404       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
43405       if( pList->pgno==1 ) pager_write_changecounter(pList);
43406
43407       /* Encode the database */
43408       CODEC2(pPager, pList->pData, pgno, 6, return SQLCIPHER_NOMEM, pData);
43409
43410       /* Write out the page data. */
43411       rc = sqlcipher3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
43412
43413       /* If page 1 was just written, update Pager.dbFileVers to match
43414       ** the value now stored in the database file. If writing this 
43415       ** page caused the database file to grow, update dbFileSize. 
43416       */
43417       if( pgno==1 ){
43418         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
43419       }
43420       if( pgno>pPager->dbFileSize ){
43421         pPager->dbFileSize = pgno;
43422       }
43423
43424       /* Update any backup objects copying the contents of this pager. */
43425       sqlcipher3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
43426
43427       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
43428                    PAGERID(pPager), pgno, pager_pagehash(pList)));
43429       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
43430       PAGER_INCR(sqlcipher3_pager_writedb_count);
43431       PAGER_INCR(pPager->nWrite);
43432     }else{
43433       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
43434     }
43435     pager_set_pagehash(pList);
43436     pList = pList->pDirty;
43437   }
43438
43439   return rc;
43440 }
43441
43442 /*
43443 ** Ensure that the sub-journal file is open. If it is already open, this 
43444 ** function is a no-op.
43445 **
43446 ** SQLCIPHER_OK is returned if everything goes according to plan. An 
43447 ** SQLCIPHER_IOERR_XXX error code is returned if a call to sqlcipher3OsOpen() 
43448 ** fails.
43449 */
43450 static int openSubJournal(Pager *pPager){
43451   int rc = SQLCIPHER_OK;
43452   if( !isOpen(pPager->sjfd) ){
43453     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
43454       sqlcipher3MemJournalOpen(pPager->sjfd);
43455     }else{
43456       rc = pagerOpentemp(pPager, pPager->sjfd, SQLCIPHER_OPEN_SUBJOURNAL);
43457     }
43458   }
43459   return rc;
43460 }
43461
43462 /*
43463 ** Append a record of the current state of page pPg to the sub-journal. 
43464 ** It is the callers responsibility to use subjRequiresPage() to check 
43465 ** that it is really required before calling this function.
43466 **
43467 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
43468 ** for all open savepoints before returning.
43469 **
43470 ** This function returns SQLCIPHER_OK if everything is successful, an IO
43471 ** error code if the attempt to write to the sub-journal fails, or 
43472 ** SQLCIPHER_NOMEM if a malloc fails while setting a bit in a savepoint
43473 ** bitvec.
43474 */
43475 static int subjournalPage(PgHdr *pPg){
43476   int rc = SQLCIPHER_OK;
43477   Pager *pPager = pPg->pPager;
43478   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43479
43480     /* Open the sub-journal, if it has not already been opened */
43481     assert( pPager->useJournal );
43482     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
43483     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
43484     assert( pagerUseWal(pPager) 
43485          || pageInJournal(pPg) 
43486          || pPg->pgno>pPager->dbOrigSize 
43487     );
43488     rc = openSubJournal(pPager);
43489
43490     /* If the sub-journal was opened successfully (or was already open),
43491     ** write the journal record into the file.  */
43492     if( rc==SQLCIPHER_OK ){
43493       void *pData = pPg->pData;
43494       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
43495       char *pData2;
43496   
43497       CODEC2(pPager, pData, pPg->pgno, 7, return SQLCIPHER_NOMEM, pData2);
43498       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
43499       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
43500       if( rc==SQLCIPHER_OK ){
43501         rc = sqlcipher3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
43502       }
43503     }
43504   }
43505   if( rc==SQLCIPHER_OK ){
43506     pPager->nSubRec++;
43507     assert( pPager->nSavepoint>0 );
43508     rc = addToSavepointBitvecs(pPager, pPg->pgno);
43509   }
43510   return rc;
43511 }
43512
43513 /*
43514 ** This function is called by the pcache layer when it has reached some
43515 ** soft memory limit. The first argument is a pointer to a Pager object
43516 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
43517 ** database). The second argument is a reference to a page that is 
43518 ** currently dirty but has no outstanding references. The page
43519 ** is always associated with the Pager object passed as the first 
43520 ** argument.
43521 **
43522 ** The job of this function is to make pPg clean by writing its contents
43523 ** out to the database file, if possible. This may involve syncing the
43524 ** journal file. 
43525 **
43526 ** If successful, sqlcipher3PcacheMakeClean() is called on the page and
43527 ** SQLCIPHER_OK returned. If an IO error occurs while trying to make the
43528 ** page clean, the IO error code is returned. If the page cannot be
43529 ** made clean for some other reason, but no error occurs, then SQLCIPHER_OK
43530 ** is returned by sqlcipher3PcacheMakeClean() is not called.
43531 */
43532 static int pagerStress(void *p, PgHdr *pPg){
43533   Pager *pPager = (Pager *)p;
43534   int rc = SQLCIPHER_OK;
43535
43536   assert( pPg->pPager==pPager );
43537   assert( pPg->flags&PGHDR_DIRTY );
43538
43539   /* The doNotSyncSpill flag is set during times when doing a sync of
43540   ** journal (and adding a new header) is not allowed.  This occurs
43541   ** during calls to sqlcipher3PagerWrite() while trying to journal multiple
43542   ** pages belonging to the same sector.
43543   **
43544   ** The doNotSpill flag inhibits all cache spilling regardless of whether
43545   ** or not a sync is required.  This is set during a rollback.
43546   **
43547   ** Spilling is also prohibited when in an error state since that could
43548   ** lead to database corruption.   In the current implementaton it 
43549   ** is impossible for sqlcipher3PcacheFetch() to be called with createFlag==1
43550   ** while in the error state, hence it is impossible for this routine to
43551   ** be called in the error state.  Nevertheless, we include a NEVER()
43552   ** test for the error state as a safeguard against future changes.
43553   */
43554   if( NEVER(pPager->errCode) ) return SQLCIPHER_OK;
43555   if( pPager->doNotSpill ) return SQLCIPHER_OK;
43556   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
43557     return SQLCIPHER_OK;
43558   }
43559
43560   pPg->pDirty = 0;
43561   if( pagerUseWal(pPager) ){
43562     /* Write a single frame for this page to the log. */
43563     if( subjRequiresPage(pPg) ){ 
43564       rc = subjournalPage(pPg); 
43565     }
43566     if( rc==SQLCIPHER_OK ){
43567       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
43568     }
43569   }else{
43570   
43571     /* Sync the journal file if required. */
43572     if( pPg->flags&PGHDR_NEED_SYNC 
43573      || pPager->eState==PAGER_WRITER_CACHEMOD
43574     ){
43575       rc = syncJournal(pPager, 1);
43576     }
43577   
43578     /* If the page number of this page is larger than the current size of
43579     ** the database image, it may need to be written to the sub-journal.
43580     ** This is because the call to pager_write_pagelist() below will not
43581     ** actually write data to the file in this case.
43582     **
43583     ** Consider the following sequence of events:
43584     **
43585     **   BEGIN;
43586     **     <journal page X>
43587     **     <modify page X>
43588     **     SAVEPOINT sp;
43589     **       <shrink database file to Y pages>
43590     **       pagerStress(page X)
43591     **     ROLLBACK TO sp;
43592     **
43593     ** If (X>Y), then when pagerStress is called page X will not be written
43594     ** out to the database file, but will be dropped from the cache. Then,
43595     ** following the "ROLLBACK TO sp" statement, reading page X will read
43596     ** data from the database file. This will be the copy of page X as it
43597     ** was when the transaction started, not as it was when "SAVEPOINT sp"
43598     ** was executed.
43599     **
43600     ** The solution is to write the current data for page X into the 
43601     ** sub-journal file now (if it is not already there), so that it will
43602     ** be restored to its current value when the "ROLLBACK TO sp" is 
43603     ** executed.
43604     */
43605     if( NEVER(
43606         rc==SQLCIPHER_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
43607     ) ){
43608       rc = subjournalPage(pPg);
43609     }
43610   
43611     /* Write the contents of the page out to the database file. */
43612     if( rc==SQLCIPHER_OK ){
43613       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
43614       rc = pager_write_pagelist(pPager, pPg);
43615     }
43616   }
43617
43618   /* Mark the page as clean. */
43619   if( rc==SQLCIPHER_OK ){
43620     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
43621     sqlcipher3PcacheMakeClean(pPg);
43622   }
43623
43624   return pager_error(pPager, rc); 
43625 }
43626
43627
43628 /*
43629 ** Allocate and initialize a new Pager object and put a pointer to it
43630 ** in *ppPager. The pager should eventually be freed by passing it
43631 ** to sqlcipher3PagerClose().
43632 **
43633 ** The zFilename argument is the path to the database file to open.
43634 ** If zFilename is NULL then a randomly-named temporary file is created
43635 ** and used as the file to be cached. Temporary files are be deleted
43636 ** automatically when they are closed. If zFilename is ":memory:" then 
43637 ** all information is held in cache. It is never written to disk. 
43638 ** This can be used to implement an in-memory database.
43639 **
43640 ** The nExtra parameter specifies the number of bytes of space allocated
43641 ** along with each page reference. This space is available to the user
43642 ** via the sqlcipher3PagerGetExtra() API.
43643 **
43644 ** The flags argument is used to specify properties that affect the
43645 ** operation of the pager. It should be passed some bitwise combination
43646 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
43647 **
43648 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
43649 ** of the xOpen() method of the supplied VFS when opening files. 
43650 **
43651 ** If the pager object is allocated and the specified file opened 
43652 ** successfully, SQLCIPHER_OK is returned and *ppPager set to point to
43653 ** the new pager object. If an error occurs, *ppPager is set to NULL
43654 ** and error code returned. This function may return SQLCIPHER_NOMEM
43655 ** (sqlcipher3Malloc() is used to allocate memory), SQLCIPHER_CANTOPEN or 
43656 ** various SQLCIPHER_IO_XXX errors.
43657 */
43658 SQLCIPHER_PRIVATE int sqlcipher3PagerOpen(
43659   sqlcipher3_vfs *pVfs,       /* The virtual file system to use */
43660   Pager **ppPager,         /* OUT: Return the Pager structure here */
43661   const char *zFilename,   /* Name of the database file to open */
43662   int nExtra,              /* Extra bytes append to each in-memory page */
43663   int flags,               /* flags controlling this file */
43664   int vfsFlags,            /* flags passed through to sqlcipher3_vfs.xOpen() */
43665   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
43666 ){
43667   u8 *pPtr;
43668   Pager *pPager = 0;       /* Pager object to allocate and return */
43669   int rc = SQLCIPHER_OK;      /* Return code */
43670   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
43671   int memDb = 0;           /* True if this is an in-memory file */
43672   int readOnly = 0;        /* True if this is a read-only file */
43673   int journalFileSize;     /* Bytes to allocate for each journal fd */
43674   char *zPathname = 0;     /* Full path to database file */
43675   int nPathname = 0;       /* Number of bytes in zPathname */
43676   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
43677   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
43678   int pcacheSize = sqlcipher3PcacheSize();       /* Bytes to allocate for PCache */
43679   u32 szPageDflt = SQLCIPHER_DEFAULT_PAGE_SIZE;  /* Default page size */
43680   const char *zUri = 0;    /* URI args to copy */
43681   int nUri = 0;            /* Number of bytes of URI args at *zUri */
43682
43683   /* Figure out how much space is required for each journal file-handle
43684   ** (there are two of them, the main journal and the sub-journal). This
43685   ** is the maximum space required for an in-memory journal file handle 
43686   ** and a regular journal file-handle. Note that a "regular journal-handle"
43687   ** may be a wrapper capable of caching the first portion of the journal
43688   ** file in memory to implement the atomic-write optimization (see 
43689   ** source file journal.c).
43690   */
43691   if( sqlcipher3JournalSize(pVfs)>sqlcipher3MemJournalSize() ){
43692     journalFileSize = ROUND8(sqlcipher3JournalSize(pVfs));
43693   }else{
43694     journalFileSize = ROUND8(sqlcipher3MemJournalSize());
43695   }
43696
43697   /* Set the output variable to NULL in case an error occurs. */
43698   *ppPager = 0;
43699
43700 #ifndef SQLCIPHER_OMIT_MEMORYDB
43701   if( flags & PAGER_MEMORY ){
43702     memDb = 1;
43703     zFilename = 0;
43704   }
43705 #endif
43706
43707   /* Compute and store the full pathname in an allocated buffer pointed
43708   ** to by zPathname, length nPathname. Or, if this is a temporary file,
43709   ** leave both nPathname and zPathname set to 0.
43710   */
43711   if( zFilename && zFilename[0] ){
43712     const char *z;
43713     nPathname = pVfs->mxPathname+1;
43714     zPathname = sqlcipher3Malloc(nPathname*2);
43715     if( zPathname==0 ){
43716       return SQLCIPHER_NOMEM;
43717     }
43718     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
43719     rc = sqlcipher3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
43720     nPathname = sqlcipher3Strlen30(zPathname);
43721     z = zUri = &zFilename[sqlcipher3Strlen30(zFilename)+1];
43722     while( *z ){
43723       z += sqlcipher3Strlen30(z)+1;
43724       z += sqlcipher3Strlen30(z)+1;
43725     }
43726     nUri = &z[1] - zUri;
43727     if( rc==SQLCIPHER_OK && nPathname+8>pVfs->mxPathname ){
43728       /* This branch is taken when the journal path required by
43729       ** the database being opened will be more than pVfs->mxPathname
43730       ** bytes in length. This means the database cannot be opened,
43731       ** as it will not be possible to open the journal file or even
43732       ** check for a hot-journal before reading.
43733       */
43734       rc = SQLCIPHER_CANTOPEN_BKPT;
43735     }
43736     if( rc!=SQLCIPHER_OK ){
43737       sqlcipher3_free(zPathname);
43738       return rc;
43739     }
43740   }
43741
43742   /* Allocate memory for the Pager structure, PCache object, the
43743   ** three file descriptors, the database file name and the journal 
43744   ** file name. The layout in memory is as follows:
43745   **
43746   **     Pager object                    (sizeof(Pager) bytes)
43747   **     PCache object                   (sqlcipher3PcacheSize() bytes)
43748   **     Database file handle            (pVfs->szOsFile bytes)
43749   **     Sub-journal file handle         (journalFileSize bytes)
43750   **     Main journal file handle        (journalFileSize bytes)
43751   **     Database file name              (nPathname+1 bytes)
43752   **     Journal file name               (nPathname+8+1 bytes)
43753   */
43754   pPtr = (u8 *)sqlcipher3MallocZero(
43755     ROUND8(sizeof(*pPager)) +      /* Pager structure */
43756     ROUND8(pcacheSize) +           /* PCache object */
43757     ROUND8(pVfs->szOsFile) +       /* The main db file */
43758     journalFileSize * 2 +          /* The two journal files */ 
43759     nPathname + 1 + nUri +         /* zFilename */
43760     nPathname + 8 + 1              /* zJournal */
43761 #ifndef SQLCIPHER_OMIT_WAL
43762     + nPathname + 4 + 1              /* zWal */
43763 #endif
43764   );
43765   assert( EIGHT_BYTE_ALIGNMENT(SQLCIPHER_INT_TO_PTR(journalFileSize)) );
43766   if( !pPtr ){
43767     sqlcipher3_free(zPathname);
43768     return SQLCIPHER_NOMEM;
43769   }
43770   pPager =              (Pager*)(pPtr);
43771   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
43772   pPager->fd =   (sqlcipher3_file*)(pPtr += ROUND8(pcacheSize));
43773   pPager->sjfd = (sqlcipher3_file*)(pPtr += ROUND8(pVfs->szOsFile));
43774   pPager->jfd =  (sqlcipher3_file*)(pPtr += journalFileSize);
43775   pPager->zFilename =    (char*)(pPtr += journalFileSize);
43776   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
43777
43778   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
43779   if( zPathname ){
43780     assert( nPathname>0 );
43781     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
43782     memcpy(pPager->zFilename, zPathname, nPathname);
43783     memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
43784     memcpy(pPager->zJournal, zPathname, nPathname);
43785     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
43786     sqlcipher3FileSuffix3(pPager->zFilename, pPager->zJournal);
43787 #ifndef SQLCIPHER_OMIT_WAL
43788     pPager->zWal = &pPager->zJournal[nPathname+8+1];
43789     memcpy(pPager->zWal, zPathname, nPathname);
43790     memcpy(&pPager->zWal[nPathname], "-wal", 4);
43791     sqlcipher3FileSuffix3(pPager->zFilename, pPager->zWal);
43792 #endif
43793     sqlcipher3_free(zPathname);
43794   }
43795   pPager->pVfs = pVfs;
43796   pPager->vfsFlags = vfsFlags;
43797
43798   /* Open the pager file.
43799   */
43800   if( zFilename && zFilename[0] ){
43801     int fout = 0;                    /* VFS flags returned by xOpen() */
43802     rc = sqlcipher3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
43803     assert( !memDb );
43804     readOnly = (fout&SQLCIPHER_OPEN_READONLY);
43805
43806     /* If the file was successfully opened for read/write access,
43807     ** choose a default page size in case we have to create the
43808     ** database file. The default page size is the maximum of:
43809     **
43810     **    + SQLCIPHER_DEFAULT_PAGE_SIZE,
43811     **    + The value returned by sqlcipher3OsSectorSize()
43812     **    + The largest page size that can be written atomically.
43813     */
43814     if( rc==SQLCIPHER_OK && !readOnly ){
43815       setSectorSize(pPager);
43816       assert(SQLCIPHER_DEFAULT_PAGE_SIZE<=SQLCIPHER_MAX_DEFAULT_PAGE_SIZE);
43817       if( szPageDflt<pPager->sectorSize ){
43818         if( pPager->sectorSize>SQLCIPHER_MAX_DEFAULT_PAGE_SIZE ){
43819           szPageDflt = SQLCIPHER_MAX_DEFAULT_PAGE_SIZE;
43820         }else{
43821           szPageDflt = (u32)pPager->sectorSize;
43822         }
43823       }
43824 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
43825       {
43826         int iDc = sqlcipher3OsDeviceCharacteristics(pPager->fd);
43827         int ii;
43828         assert(SQLCIPHER_IOCAP_ATOMIC512==(512>>8));
43829         assert(SQLCIPHER_IOCAP_ATOMIC64K==(65536>>8));
43830         assert(SQLCIPHER_MAX_DEFAULT_PAGE_SIZE<=65536);
43831         for(ii=szPageDflt; ii<=SQLCIPHER_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
43832           if( iDc&(SQLCIPHER_IOCAP_ATOMIC|(ii>>8)) ){
43833             szPageDflt = ii;
43834           }
43835         }
43836       }
43837 #endif
43838     }
43839   }else{
43840     /* If a temporary file is requested, it is not opened immediately.
43841     ** In this case we accept the default page size and delay actually
43842     ** opening the file until the first call to OsWrite().
43843     **
43844     ** This branch is also run for an in-memory database. An in-memory
43845     ** database is the same as a temp-file that is never written out to
43846     ** disk and uses an in-memory rollback journal.
43847     */ 
43848     tempFile = 1;
43849     pPager->eState = PAGER_READER;
43850     pPager->eLock = EXCLUSIVE_LOCK;
43851     readOnly = (vfsFlags&SQLCIPHER_OPEN_READONLY);
43852   }
43853
43854   /* The following call to PagerSetPagesize() serves to set the value of 
43855   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
43856   */
43857   if( rc==SQLCIPHER_OK ){
43858     assert( pPager->memDb==0 );
43859     rc = sqlcipher3PagerSetPagesize(pPager, &szPageDflt, -1);
43860     testcase( rc!=SQLCIPHER_OK );
43861   }
43862
43863   /* If an error occurred in either of the blocks above, free the 
43864   ** Pager structure and close the file.
43865   */
43866   if( rc!=SQLCIPHER_OK ){
43867     assert( !pPager->pTmpSpace );
43868     sqlcipher3OsClose(pPager->fd);
43869     sqlcipher3_free(pPager);
43870     return rc;
43871   }
43872
43873   /* Initialize the PCache object. */
43874   assert( nExtra<1000 );
43875   nExtra = ROUND8(nExtra);
43876   sqlcipher3PcacheOpen(szPageDflt, nExtra, !memDb,
43877                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
43878
43879   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
43880   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
43881
43882   pPager->useJournal = (u8)useJournal;
43883   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
43884   /* pPager->stmtOpen = 0; */
43885   /* pPager->stmtInUse = 0; */
43886   /* pPager->nRef = 0; */
43887   /* pPager->stmtSize = 0; */
43888   /* pPager->stmtJSize = 0; */
43889   /* pPager->nPage = 0; */
43890   pPager->mxPgno = SQLCIPHER_MAX_PAGE_COUNT;
43891   /* pPager->state = PAGER_UNLOCK; */
43892 #if 0
43893   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
43894 #endif
43895   /* pPager->errMask = 0; */
43896   pPager->tempFile = (u8)tempFile;
43897   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
43898           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
43899   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
43900   pPager->exclusiveMode = (u8)tempFile; 
43901   pPager->changeCountDone = pPager->tempFile;
43902   pPager->memDb = (u8)memDb;
43903   pPager->readOnly = (u8)readOnly;
43904   assert( useJournal || pPager->tempFile );
43905   pPager->noSync = pPager->tempFile;
43906   pPager->fullSync = pPager->noSync ?0:1;
43907   pPager->syncFlags = pPager->noSync ? 0 : SQLCIPHER_SYNC_NORMAL;
43908   pPager->ckptSyncFlags = pPager->syncFlags;
43909   /* pPager->pFirst = 0; */
43910   /* pPager->pFirstSynced = 0; */
43911   /* pPager->pLast = 0; */
43912   pPager->nExtra = (u16)nExtra;
43913   pPager->journalSizeLimit = SQLCIPHER_DEFAULT_JOURNAL_SIZE_LIMIT;
43914   assert( isOpen(pPager->fd) || tempFile );
43915   setSectorSize(pPager);
43916   if( !useJournal ){
43917     pPager->journalMode = PAGER_JOURNALMODE_OFF;
43918   }else if( memDb ){
43919     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43920   }
43921   /* pPager->xBusyHandler = 0; */
43922   /* pPager->pBusyHandlerArg = 0; */
43923   pPager->xReiniter = xReinit;
43924   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43925
43926   *ppPager = pPager;
43927   return SQLCIPHER_OK;
43928 }
43929
43930
43931
43932 /*
43933 ** This function is called after transitioning from PAGER_UNLOCK to
43934 ** PAGER_SHARED state. It tests if there is a hot journal present in
43935 ** the file-system for the given pager. A hot journal is one that 
43936 ** needs to be played back. According to this function, a hot-journal
43937 ** file exists if the following criteria are met:
43938 **
43939 **   * The journal file exists in the file system, and
43940 **   * No process holds a RESERVED or greater lock on the database file, and
43941 **   * The database file itself is greater than 0 bytes in size, and
43942 **   * The first byte of the journal file exists and is not 0x00.
43943 **
43944 ** If the current size of the database file is 0 but a journal file
43945 ** exists, that is probably an old journal left over from a prior
43946 ** database with the same name. In this case the journal file is
43947 ** just deleted using OsDelete, *pExists is set to 0 and SQLCIPHER_OK
43948 ** is returned.
43949 **
43950 ** This routine does not check if there is a master journal filename
43951 ** at the end of the file. If there is, and that master journal file
43952 ** does not exist, then the journal file is not really hot. In this
43953 ** case this routine will return a false-positive. The pager_playback()
43954 ** routine will discover that the journal file is not really hot and 
43955 ** will not roll it back. 
43956 **
43957 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
43958 ** SQLCIPHER_OK returned. If no hot-journal file is present, *pExists is
43959 ** set to 0 and SQLCIPHER_OK returned. If an IO error occurs while trying
43960 ** to determine whether or not a hot-journal file exists, the IO error
43961 ** code is returned and the value of *pExists is undefined.
43962 */
43963 static int hasHotJournal(Pager *pPager, int *pExists){
43964   sqlcipher3_vfs * const pVfs = pPager->pVfs;
43965   int rc = SQLCIPHER_OK;           /* Return code */
43966   int exists = 1;               /* True if a journal file is present */
43967   int jrnlOpen = !!isOpen(pPager->jfd);
43968
43969   assert( pPager->useJournal );
43970   assert( isOpen(pPager->fd) );
43971   assert( pPager->eState==PAGER_OPEN );
43972
43973   assert( jrnlOpen==0 || ( sqlcipher3OsDeviceCharacteristics(pPager->jfd) &
43974     SQLCIPHER_IOCAP_UNDELETABLE_WHEN_OPEN
43975   ));
43976
43977   *pExists = 0;
43978   if( !jrnlOpen ){
43979     rc = sqlcipher3OsAccess(pVfs, pPager->zJournal, SQLCIPHER_ACCESS_EXISTS, &exists);
43980   }
43981   if( rc==SQLCIPHER_OK && exists ){
43982     int locked = 0;             /* True if some process holds a RESERVED lock */
43983
43984     /* Race condition here:  Another process might have been holding the
43985     ** the RESERVED lock and have a journal open at the sqlcipher3OsAccess() 
43986     ** call above, but then delete the journal and drop the lock before
43987     ** we get to the following sqlcipher3OsCheckReservedLock() call.  If that
43988     ** is the case, this routine might think there is a hot journal when
43989     ** in fact there is none.  This results in a false-positive which will
43990     ** be dealt with by the playback routine.  Ticket #3883.
43991     */
43992     rc = sqlcipher3OsCheckReservedLock(pPager->fd, &locked);
43993     if( rc==SQLCIPHER_OK && !locked ){
43994       Pgno nPage;                 /* Number of pages in database file */
43995
43996       /* Check the size of the database file. If it consists of 0 pages,
43997       ** then delete the journal file. See the header comment above for 
43998       ** the reasoning here.  Delete the obsolete journal file under
43999       ** a RESERVED lock to avoid race conditions and to avoid violating
44000       ** [H33020].
44001       */
44002       rc = pagerPagecount(pPager, &nPage);
44003       if( rc==SQLCIPHER_OK ){
44004         if( nPage==0 ){
44005           sqlcipher3BeginBenignMalloc();
44006           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLCIPHER_OK ){
44007             sqlcipher3OsDelete(pVfs, pPager->zJournal, 0);
44008             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
44009           }
44010           sqlcipher3EndBenignMalloc();
44011         }else{
44012           /* The journal file exists and no other connection has a reserved
44013           ** or greater lock on the database file. Now check that there is
44014           ** at least one non-zero bytes at the start of the journal file.
44015           ** If there is, then we consider this journal to be hot. If not, 
44016           ** it can be ignored.
44017           */
44018           if( !jrnlOpen ){
44019             int f = SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_MAIN_JOURNAL;
44020             rc = sqlcipher3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
44021           }
44022           if( rc==SQLCIPHER_OK ){
44023             u8 first = 0;
44024             rc = sqlcipher3OsRead(pPager->jfd, (void *)&first, 1, 0);
44025             if( rc==SQLCIPHER_IOERR_SHORT_READ ){
44026               rc = SQLCIPHER_OK;
44027             }
44028             if( !jrnlOpen ){
44029               sqlcipher3OsClose(pPager->jfd);
44030             }
44031             *pExists = (first!=0);
44032           }else if( rc==SQLCIPHER_CANTOPEN ){
44033             /* If we cannot open the rollback journal file in order to see if
44034             ** its has a zero header, that might be due to an I/O error, or
44035             ** it might be due to the race condition described above and in
44036             ** ticket #3883.  Either way, assume that the journal is hot.
44037             ** This might be a false positive.  But if it is, then the
44038             ** automatic journal playback and recovery mechanism will deal
44039             ** with it under an EXCLUSIVE lock where we do not need to
44040             ** worry so much with race conditions.
44041             */
44042             *pExists = 1;
44043             rc = SQLCIPHER_OK;
44044           }
44045         }
44046       }
44047     }
44048   }
44049
44050   return rc;
44051 }
44052
44053 /*
44054 ** This function is called to obtain a shared lock on the database file.
44055 ** It is illegal to call sqlcipher3PagerAcquire() until after this function
44056 ** has been successfully called. If a shared-lock is already held when
44057 ** this function is called, it is a no-op.
44058 **
44059 ** The following operations are also performed by this function.
44060 **
44061 **   1) If the pager is currently in PAGER_OPEN state (no lock held
44062 **      on the database file), then an attempt is made to obtain a
44063 **      SHARED lock on the database file. Immediately after obtaining
44064 **      the SHARED lock, the file-system is checked for a hot-journal,
44065 **      which is played back if present. Following any hot-journal 
44066 **      rollback, the contents of the cache are validated by checking
44067 **      the 'change-counter' field of the database file header and
44068 **      discarded if they are found to be invalid.
44069 **
44070 **   2) If the pager is running in exclusive-mode, and there are currently
44071 **      no outstanding references to any pages, and is in the error state,
44072 **      then an attempt is made to clear the error state by discarding
44073 **      the contents of the page cache and rolling back any open journal
44074 **      file.
44075 **
44076 ** If everything is successful, SQLCIPHER_OK is returned. If an IO error 
44077 ** occurs while locking the database, checking for a hot-journal file or 
44078 ** rolling back a journal file, the IO error code is returned.
44079 */
44080 SQLCIPHER_PRIVATE int sqlcipher3PagerSharedLock(Pager *pPager){
44081   int rc = SQLCIPHER_OK;                /* Return code */
44082
44083   /* This routine is only called from b-tree and only when there are no
44084   ** outstanding pages. This implies that the pager state should either
44085   ** be OPEN or READER. READER is only possible if the pager is or was in 
44086   ** exclusive access mode.
44087   */
44088   assert( sqlcipher3PcacheRefCount(pPager->pPCache)==0 );
44089   assert( assert_pager_state(pPager) );
44090   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44091   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
44092
44093   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
44094     int bHotJournal = 1;          /* True if there exists a hot journal-file */
44095
44096     assert( !MEMDB );
44097     assert( pPager->noReadlock==0 || pPager->readOnly );
44098
44099     if( pPager->noReadlock==0 ){
44100       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
44101       if( rc!=SQLCIPHER_OK ){
44102         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
44103         goto failed;
44104       }
44105     }
44106
44107     /* If a journal file exists, and there is no RESERVED lock on the
44108     ** database file, then it either needs to be played back or deleted.
44109     */
44110     if( pPager->eLock<=SHARED_LOCK ){
44111       rc = hasHotJournal(pPager, &bHotJournal);
44112     }
44113     if( rc!=SQLCIPHER_OK ){
44114       goto failed;
44115     }
44116     if( bHotJournal ){
44117       /* Get an EXCLUSIVE lock on the database file. At this point it is
44118       ** important that a RESERVED lock is not obtained on the way to the
44119       ** EXCLUSIVE lock. If it were, another process might open the
44120       ** database file, detect the RESERVED lock, and conclude that the
44121       ** database is safe to read while this process is still rolling the 
44122       ** hot-journal back.
44123       ** 
44124       ** Because the intermediate RESERVED lock is not requested, any
44125       ** other process attempting to access the database file will get to 
44126       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
44127       ** on the database file.
44128       **
44129       ** Unless the pager is in locking_mode=exclusive mode, the lock is
44130       ** downgraded to SHARED_LOCK before this function returns.
44131       */
44132       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44133       if( rc!=SQLCIPHER_OK ){
44134         goto failed;
44135       }
44136  
44137       /* If it is not already open and the file exists on disk, open the 
44138       ** journal for read/write access. Write access is required because 
44139       ** in exclusive-access mode the file descriptor will be kept open 
44140       ** and possibly used for a transaction later on. Also, write-access 
44141       ** is usually required to finalize the journal in journal_mode=persist 
44142       ** mode (and also for journal_mode=truncate on some systems).
44143       **
44144       ** If the journal does not exist, it usually means that some 
44145       ** other connection managed to get in and roll it back before 
44146       ** this connection obtained the exclusive lock above. Or, it 
44147       ** may mean that the pager was in the error-state when this
44148       ** function was called and the journal file does not exist.
44149       */
44150       if( !isOpen(pPager->jfd) ){
44151         sqlcipher3_vfs * const pVfs = pPager->pVfs;
44152         int bExists;              /* True if journal file exists */
44153         rc = sqlcipher3OsAccess(
44154             pVfs, pPager->zJournal, SQLCIPHER_ACCESS_EXISTS, &bExists);
44155         if( rc==SQLCIPHER_OK && bExists ){
44156           int fout = 0;
44157           int f = SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_MAIN_JOURNAL;
44158           assert( !pPager->tempFile );
44159           rc = sqlcipher3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
44160           assert( rc!=SQLCIPHER_OK || isOpen(pPager->jfd) );
44161           if( rc==SQLCIPHER_OK && fout&SQLCIPHER_OPEN_READONLY ){
44162             rc = SQLCIPHER_CANTOPEN_BKPT;
44163             sqlcipher3OsClose(pPager->jfd);
44164           }
44165         }
44166       }
44167  
44168       /* Playback and delete the journal.  Drop the database write
44169       ** lock and reacquire the read lock. Purge the cache before
44170       ** playing back the hot-journal so that we don't end up with
44171       ** an inconsistent cache.  Sync the hot journal before playing
44172       ** it back since the process that crashed and left the hot journal
44173       ** probably did not sync it and we are required to always sync
44174       ** the journal before playing it back.
44175       */
44176       if( isOpen(pPager->jfd) ){
44177         assert( rc==SQLCIPHER_OK );
44178         rc = pagerSyncHotJournal(pPager);
44179         if( rc==SQLCIPHER_OK ){
44180           rc = pager_playback(pPager, 1);
44181           pPager->eState = PAGER_OPEN;
44182         }
44183       }else if( !pPager->exclusiveMode ){
44184         pagerUnlockDb(pPager, SHARED_LOCK);
44185       }
44186
44187       if( rc!=SQLCIPHER_OK ){
44188         /* This branch is taken if an error occurs while trying to open
44189         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
44190         ** pager_unlock() routine will be called before returning to unlock
44191         ** the file. If the unlock attempt fails, then Pager.eLock must be
44192         ** set to UNKNOWN_LOCK (see the comment above the #define for 
44193         ** UNKNOWN_LOCK above for an explanation). 
44194         **
44195         ** In order to get pager_unlock() to do this, set Pager.eState to
44196         ** PAGER_ERROR now. This is not actually counted as a transition
44197         ** to ERROR state in the state diagram at the top of this file,
44198         ** since we know that the same call to pager_unlock() will very
44199         ** shortly transition the pager object to the OPEN state. Calling
44200         ** assert_pager_state() would fail now, as it should not be possible
44201         ** to be in ERROR state when there are zero outstanding page 
44202         ** references.
44203         */
44204         pager_error(pPager, rc);
44205         goto failed;
44206       }
44207
44208       assert( pPager->eState==PAGER_OPEN );
44209       assert( (pPager->eLock==SHARED_LOCK)
44210            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
44211       );
44212     }
44213
44214     if( !pPager->tempFile 
44215      && (pPager->pBackup || sqlcipher3PcachePagecount(pPager->pPCache)>0) 
44216     ){
44217       /* The shared-lock has just been acquired on the database file
44218       ** and there are already pages in the cache (from a previous
44219       ** read or write transaction).  Check to see if the database
44220       ** has been modified.  If the database has changed, flush the
44221       ** cache.
44222       **
44223       ** Database changes is detected by looking at 15 bytes beginning
44224       ** at offset 24 into the file.  The first 4 of these 16 bytes are
44225       ** a 32-bit counter that is incremented with each change.  The
44226       ** other bytes change randomly with each file change when
44227       ** a codec is in use.
44228       ** 
44229       ** There is a vanishingly small chance that a change will not be 
44230       ** detected.  The chance of an undetected change is so small that
44231       ** it can be neglected.
44232       */
44233       Pgno nPage = 0;
44234       char dbFileVers[sizeof(pPager->dbFileVers)];
44235
44236       rc = pagerPagecount(pPager, &nPage);
44237       if( rc ) goto failed;
44238
44239       if( nPage>0 ){
44240         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
44241         rc = sqlcipher3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
44242         if( rc!=SQLCIPHER_OK ){
44243           goto failed;
44244         }
44245       }else{
44246         memset(dbFileVers, 0, sizeof(dbFileVers));
44247       }
44248
44249       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
44250         pager_reset(pPager);
44251       }
44252     }
44253
44254     /* If there is a WAL file in the file-system, open this database in WAL
44255     ** mode. Otherwise, the following function call is a no-op.
44256     */
44257     rc = pagerOpenWalIfPresent(pPager);
44258 #ifndef SQLCIPHER_OMIT_WAL
44259     assert( pPager->pWal==0 || rc==SQLCIPHER_OK );
44260 #endif
44261   }
44262
44263   if( pagerUseWal(pPager) ){
44264     assert( rc==SQLCIPHER_OK );
44265     rc = pagerBeginReadTransaction(pPager);
44266   }
44267
44268   if( pPager->eState==PAGER_OPEN && rc==SQLCIPHER_OK ){
44269     rc = pagerPagecount(pPager, &pPager->dbSize);
44270   }
44271
44272  failed:
44273   if( rc!=SQLCIPHER_OK ){
44274     assert( !MEMDB );
44275     pager_unlock(pPager);
44276     assert( pPager->eState==PAGER_OPEN );
44277   }else{
44278     pPager->eState = PAGER_READER;
44279   }
44280   return rc;
44281 }
44282
44283 /*
44284 ** If the reference count has reached zero, rollback any active
44285 ** transaction and unlock the pager.
44286 **
44287 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
44288 ** the rollback journal, the unlock is not performed and there is
44289 ** nothing to rollback, so this routine is a no-op.
44290 */ 
44291 static void pagerUnlockIfUnused(Pager *pPager){
44292   if( (sqlcipher3PcacheRefCount(pPager->pPCache)==0) ){
44293     pagerUnlockAndRollback(pPager);
44294   }
44295 }
44296
44297 /*
44298 ** Acquire a reference to page number pgno in pager pPager (a page
44299 ** reference has type DbPage*). If the requested reference is 
44300 ** successfully obtained, it is copied to *ppPage and SQLCIPHER_OK returned.
44301 **
44302 ** If the requested page is already in the cache, it is returned. 
44303 ** Otherwise, a new page object is allocated and populated with data
44304 ** read from the database file. In some cases, the pcache module may
44305 ** choose not to allocate a new page object and may reuse an existing
44306 ** object with no outstanding references.
44307 **
44308 ** The extra data appended to a page is always initialized to zeros the 
44309 ** first time a page is loaded into memory. If the page requested is 
44310 ** already in the cache when this function is called, then the extra
44311 ** data is left as it was when the page object was last used.
44312 **
44313 ** If the database image is smaller than the requested page or if a 
44314 ** non-zero value is passed as the noContent parameter and the 
44315 ** requested page is not already stored in the cache, then no 
44316 ** actual disk read occurs. In this case the memory image of the 
44317 ** page is initialized to all zeros. 
44318 **
44319 ** If noContent is true, it means that we do not care about the contents
44320 ** of the page. This occurs in two seperate scenarios:
44321 **
44322 **   a) When reading a free-list leaf page from the database, and
44323 **
44324 **   b) When a savepoint is being rolled back and we need to load
44325 **      a new page into the cache to be filled with the data read
44326 **      from the savepoint journal.
44327 **
44328 ** If noContent is true, then the data returned is zeroed instead of
44329 ** being read from the database. Additionally, the bits corresponding
44330 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
44331 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
44332 ** savepoints are set. This means if the page is made writable at any
44333 ** point in the future, using a call to sqlcipher3PagerWrite(), its contents
44334 ** will not be journaled. This saves IO.
44335 **
44336 ** The acquisition might fail for several reasons.  In all cases,
44337 ** an appropriate error code is returned and *ppPage is set to NULL.
44338 **
44339 ** See also sqlcipher3PagerLookup().  Both this routine and Lookup() attempt
44340 ** to find a page in the in-memory cache first.  If the page is not already
44341 ** in memory, this routine goes to disk to read it in whereas Lookup()
44342 ** just returns 0.  This routine acquires a read-lock the first time it
44343 ** has to go to disk, and could also playback an old journal if necessary.
44344 ** Since Lookup() never goes to disk, it never has to deal with locks
44345 ** or journal files.
44346 */
44347 SQLCIPHER_PRIVATE int sqlcipher3PagerAcquire(
44348   Pager *pPager,      /* The pager open on the database file */
44349   Pgno pgno,          /* Page number to fetch */
44350   DbPage **ppPage,    /* Write a pointer to the page here */
44351   int noContent       /* Do not bother reading content from disk if true */
44352 ){
44353   int rc;
44354   PgHdr *pPg;
44355
44356   assert( pPager->eState>=PAGER_READER );
44357   assert( assert_pager_state(pPager) );
44358
44359   if( pgno==0 ){
44360     return SQLCIPHER_CORRUPT_BKPT;
44361   }
44362
44363   /* If the pager is in the error state, return an error immediately. 
44364   ** Otherwise, request the page from the PCache layer. */
44365   if( pPager->errCode!=SQLCIPHER_OK ){
44366     rc = pPager->errCode;
44367   }else{
44368     rc = sqlcipher3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
44369   }
44370
44371   if( rc!=SQLCIPHER_OK ){
44372     /* Either the call to sqlcipher3PcacheFetch() returned an error or the
44373     ** pager was already in the error-state when this function was called.
44374     ** Set pPg to 0 and jump to the exception handler.  */
44375     pPg = 0;
44376     goto pager_acquire_err;
44377   }
44378   assert( (*ppPage)->pgno==pgno );
44379   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
44380
44381   if( (*ppPage)->pPager && !noContent ){
44382     /* In this case the pcache already contains an initialized copy of
44383     ** the page. Return without further ado.  */
44384     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
44385     pPager->nHit++;
44386     return SQLCIPHER_OK;
44387
44388   }else{
44389     /* The pager cache has created a new page. Its content needs to 
44390     ** be initialized.  */
44391
44392     pPg = *ppPage;
44393     pPg->pPager = pPager;
44394
44395     /* The maximum page number is 2^31. Return SQLCIPHER_CORRUPT if a page
44396     ** number greater than this, or the unused locking-page, is requested. */
44397     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
44398       rc = SQLCIPHER_CORRUPT_BKPT;
44399       goto pager_acquire_err;
44400     }
44401
44402     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
44403       if( pgno>pPager->mxPgno ){
44404         rc = SQLCIPHER_FULL;
44405         goto pager_acquire_err;
44406       }
44407       if( noContent ){
44408         /* Failure to set the bits in the InJournal bit-vectors is benign.
44409         ** It merely means that we might do some extra work to journal a 
44410         ** page that does not need to be journaled.  Nevertheless, be sure 
44411         ** to test the case where a malloc error occurs while trying to set 
44412         ** a bit in a bit vector.
44413         */
44414         sqlcipher3BeginBenignMalloc();
44415         if( pgno<=pPager->dbOrigSize ){
44416           TESTONLY( rc = ) sqlcipher3BitvecSet(pPager->pInJournal, pgno);
44417           testcase( rc==SQLCIPHER_NOMEM );
44418         }
44419         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
44420         testcase( rc==SQLCIPHER_NOMEM );
44421         sqlcipher3EndBenignMalloc();
44422       }
44423       memset(pPg->pData, 0, pPager->pageSize);
44424       IOTRACE(("ZERO %p %d\n", pPager, pgno));
44425     }else{
44426       assert( pPg->pPager==pPager );
44427       pPager->nMiss++;
44428       rc = readDbPage(pPg);
44429       if( rc!=SQLCIPHER_OK ){
44430         goto pager_acquire_err;
44431       }
44432     }
44433     pager_set_pagehash(pPg);
44434   }
44435
44436   return SQLCIPHER_OK;
44437
44438 pager_acquire_err:
44439   assert( rc!=SQLCIPHER_OK );
44440   if( pPg ){
44441     sqlcipher3PcacheDrop(pPg);
44442   }
44443   pagerUnlockIfUnused(pPager);
44444
44445   *ppPage = 0;
44446   return rc;
44447 }
44448
44449 /*
44450 ** Acquire a page if it is already in the in-memory cache.  Do
44451 ** not read the page from disk.  Return a pointer to the page,
44452 ** or 0 if the page is not in cache. 
44453 **
44454 ** See also sqlcipher3PagerGet().  The difference between this routine
44455 ** and sqlcipher3PagerGet() is that _get() will go to the disk and read
44456 ** in the page if the page is not already in cache.  This routine
44457 ** returns NULL if the page is not in cache or if a disk I/O error 
44458 ** has ever happened.
44459 */
44460 SQLCIPHER_PRIVATE DbPage *sqlcipher3PagerLookup(Pager *pPager, Pgno pgno){
44461   PgHdr *pPg = 0;
44462   assert( pPager!=0 );
44463   assert( pgno!=0 );
44464   assert( pPager->pPCache!=0 );
44465   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
44466   sqlcipher3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
44467   return pPg;
44468 }
44469
44470 /*
44471 ** Release a page reference.
44472 **
44473 ** If the number of references to the page drop to zero, then the
44474 ** page is added to the LRU list.  When all references to all pages
44475 ** are released, a rollback occurs and the lock on the database is
44476 ** removed.
44477 */
44478 SQLCIPHER_PRIVATE void sqlcipher3PagerUnref(DbPage *pPg){
44479   if( pPg ){
44480     Pager *pPager = pPg->pPager;
44481     sqlcipher3PcacheRelease(pPg);
44482     pagerUnlockIfUnused(pPager);
44483   }
44484 }
44485
44486 /*
44487 ** This function is called at the start of every write transaction.
44488 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
44489 ** file when this routine is called.
44490 **
44491 ** Open the journal file for pager pPager and write a journal header
44492 ** to the start of it. If there are active savepoints, open the sub-journal
44493 ** as well. This function is only used when the journal file is being 
44494 ** opened to write a rollback log for a transaction. It is not used 
44495 ** when opening a hot journal file to roll it back.
44496 **
44497 ** If the journal file is already open (as it may be in exclusive mode),
44498 ** then this function just writes a journal header to the start of the
44499 ** already open file. 
44500 **
44501 ** Whether or not the journal file is opened by this function, the
44502 ** Pager.pInJournal bitvec structure is allocated.
44503 **
44504 ** Return SQLCIPHER_OK if everything is successful. Otherwise, return 
44505 ** SQLCIPHER_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
44506 ** an IO error code if opening or writing the journal file fails.
44507 */
44508 static int pager_open_journal(Pager *pPager){
44509   int rc = SQLCIPHER_OK;                        /* Return code */
44510   sqlcipher3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
44511
44512   assert( pPager->eState==PAGER_WRITER_LOCKED );
44513   assert( assert_pager_state(pPager) );
44514   assert( pPager->pInJournal==0 );
44515   
44516   /* If already in the error state, this function is a no-op.  But on
44517   ** the other hand, this routine is never called if we are already in
44518   ** an error state. */
44519   if( NEVER(pPager->errCode) ) return pPager->errCode;
44520
44521   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
44522     pPager->pInJournal = sqlcipher3BitvecCreate(pPager->dbSize);
44523     if( pPager->pInJournal==0 ){
44524       return SQLCIPHER_NOMEM;
44525     }
44526   
44527     /* Open the journal file if it is not already open. */
44528     if( !isOpen(pPager->jfd) ){
44529       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
44530         sqlcipher3MemJournalOpen(pPager->jfd);
44531       }else{
44532         const int flags =                   /* VFS flags to open journal file */
44533           SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE|
44534           (pPager->tempFile ? 
44535             (SQLCIPHER_OPEN_DELETEONCLOSE|SQLCIPHER_OPEN_TEMP_JOURNAL):
44536             (SQLCIPHER_OPEN_MAIN_JOURNAL)
44537           );
44538   #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
44539         rc = sqlcipher3JournalOpen(
44540             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
44541         );
44542   #else
44543         rc = sqlcipher3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
44544   #endif
44545       }
44546       assert( rc!=SQLCIPHER_OK || isOpen(pPager->jfd) );
44547     }
44548   
44549   
44550     /* Write the first journal header to the journal file and open 
44551     ** the sub-journal if necessary.
44552     */
44553     if( rc==SQLCIPHER_OK ){
44554       /* TODO: Check if all of these are really required. */
44555       pPager->nRec = 0;
44556       pPager->journalOff = 0;
44557       pPager->setMaster = 0;
44558       pPager->journalHdr = 0;
44559       rc = writeJournalHdr(pPager);
44560     }
44561   }
44562
44563   if( rc!=SQLCIPHER_OK ){
44564     sqlcipher3BitvecDestroy(pPager->pInJournal);
44565     pPager->pInJournal = 0;
44566   }else{
44567     assert( pPager->eState==PAGER_WRITER_LOCKED );
44568     pPager->eState = PAGER_WRITER_CACHEMOD;
44569   }
44570
44571   return rc;
44572 }
44573
44574 /*
44575 ** Begin a write-transaction on the specified pager object. If a 
44576 ** write-transaction has already been opened, this function is a no-op.
44577 **
44578 ** If the exFlag argument is false, then acquire at least a RESERVED
44579 ** lock on the database file. If exFlag is true, then acquire at least
44580 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
44581 ** functions need be called.
44582 **
44583 ** If the subjInMemory argument is non-zero, then any sub-journal opened
44584 ** within this transaction will be opened as an in-memory file. This
44585 ** has no effect if the sub-journal is already opened (as it may be when
44586 ** running in exclusive mode) or if the transaction does not require a
44587 ** sub-journal. If the subjInMemory argument is zero, then any required
44588 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
44589 ** or using a temporary file otherwise.
44590 */
44591 SQLCIPHER_PRIVATE int sqlcipher3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
44592   int rc = SQLCIPHER_OK;
44593
44594   if( pPager->errCode ) return pPager->errCode;
44595   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
44596   pPager->subjInMemory = (u8)subjInMemory;
44597
44598   if( ALWAYS(pPager->eState==PAGER_READER) ){
44599     assert( pPager->pInJournal==0 );
44600
44601     if( pagerUseWal(pPager) ){
44602       /* If the pager is configured to use locking_mode=exclusive, and an
44603       ** exclusive lock on the database is not already held, obtain it now.
44604       */
44605       if( pPager->exclusiveMode && sqlcipher3WalExclusiveMode(pPager->pWal, -1) ){
44606         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44607         if( rc!=SQLCIPHER_OK ){
44608           return rc;
44609         }
44610         sqlcipher3WalExclusiveMode(pPager->pWal, 1);
44611       }
44612
44613       /* Grab the write lock on the log file. If successful, upgrade to
44614       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
44615       ** The busy-handler is not invoked if another connection already
44616       ** holds the write-lock. If possible, the upper layer will call it.
44617       */
44618       rc = sqlcipher3WalBeginWriteTransaction(pPager->pWal);
44619     }else{
44620       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
44621       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
44622       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
44623       ** lock, but not when obtaining the RESERVED lock.
44624       */
44625       rc = pagerLockDb(pPager, RESERVED_LOCK);
44626       if( rc==SQLCIPHER_OK && exFlag ){
44627         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44628       }
44629     }
44630
44631     if( rc==SQLCIPHER_OK ){
44632       /* Change to WRITER_LOCKED state.
44633       **
44634       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
44635       ** when it has an open transaction, but never to DBMOD or FINISHED.
44636       ** This is because in those states the code to roll back savepoint 
44637       ** transactions may copy data from the sub-journal into the database 
44638       ** file as well as into the page cache. Which would be incorrect in 
44639       ** WAL mode.
44640       */
44641       pPager->eState = PAGER_WRITER_LOCKED;
44642       pPager->dbHintSize = pPager->dbSize;
44643       pPager->dbFileSize = pPager->dbSize;
44644       pPager->dbOrigSize = pPager->dbSize;
44645       pPager->journalOff = 0;
44646     }
44647
44648     assert( rc==SQLCIPHER_OK || pPager->eState==PAGER_READER );
44649     assert( rc!=SQLCIPHER_OK || pPager->eState==PAGER_WRITER_LOCKED );
44650     assert( assert_pager_state(pPager) );
44651   }
44652
44653   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
44654   return rc;
44655 }
44656
44657 /*
44658 ** Mark a single data page as writeable. The page is written into the 
44659 ** main journal or sub-journal as required. If the page is written into
44660 ** one of the journals, the corresponding bit is set in the 
44661 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
44662 ** of any open savepoints as appropriate.
44663 */
44664 static int pager_write(PgHdr *pPg){
44665   void *pData = pPg->pData;
44666   Pager *pPager = pPg->pPager;
44667   int rc = SQLCIPHER_OK;
44668
44669   /* This routine is not called unless a write-transaction has already 
44670   ** been started. The journal file may or may not be open at this point.
44671   ** It is never called in the ERROR state.
44672   */
44673   assert( pPager->eState==PAGER_WRITER_LOCKED
44674        || pPager->eState==PAGER_WRITER_CACHEMOD
44675        || pPager->eState==PAGER_WRITER_DBMOD
44676   );
44677   assert( assert_pager_state(pPager) );
44678
44679   /* If an error has been previously detected, report the same error
44680   ** again. This should not happen, but the check provides robustness. */
44681   if( NEVER(pPager->errCode) )  return pPager->errCode;
44682
44683   /* Higher-level routines never call this function if database is not
44684   ** writable.  But check anyway, just for robustness. */
44685   if( NEVER(pPager->readOnly) ) return SQLCIPHER_PERM;
44686
44687   CHECK_PAGE(pPg);
44688
44689   /* The journal file needs to be opened. Higher level routines have already
44690   ** obtained the necessary locks to begin the write-transaction, but the
44691   ** rollback journal might not yet be open. Open it now if this is the case.
44692   **
44693   ** This is done before calling sqlcipher3PcacheMakeDirty() on the page. 
44694   ** Otherwise, if it were done after calling sqlcipher3PcacheMakeDirty(), then
44695   ** an error might occur and the pager would end up in WRITER_LOCKED state
44696   ** with pages marked as dirty in the cache.
44697   */
44698   if( pPager->eState==PAGER_WRITER_LOCKED ){
44699     rc = pager_open_journal(pPager);
44700     if( rc!=SQLCIPHER_OK ) return rc;
44701   }
44702   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
44703   assert( assert_pager_state(pPager) );
44704
44705   /* Mark the page as dirty.  If the page has already been written
44706   ** to the journal then we can return right away.
44707   */
44708   sqlcipher3PcacheMakeDirty(pPg);
44709   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
44710     assert( !pagerUseWal(pPager) );
44711   }else{
44712   
44713     /* The transaction journal now exists and we have a RESERVED or an
44714     ** EXCLUSIVE lock on the main database file.  Write the current page to
44715     ** the transaction journal if it is not there already.
44716     */
44717     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
44718       assert( pagerUseWal(pPager)==0 );
44719       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
44720         u32 cksum;
44721         char *pData2;
44722         i64 iOff = pPager->journalOff;
44723
44724         /* We should never write to the journal file the page that
44725         ** contains the database locks.  The following assert verifies
44726         ** that we do not. */
44727         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
44728
44729         assert( pPager->journalHdr<=pPager->journalOff );
44730         CODEC2(pPager, pData, pPg->pgno, 7, return SQLCIPHER_NOMEM, pData2);
44731         cksum = pager_cksum(pPager, (u8*)pData2);
44732
44733         /* Even if an IO or diskfull error occurs while journalling the
44734         ** page in the block above, set the need-sync flag for the page.
44735         ** Otherwise, when the transaction is rolled back, the logic in
44736         ** playback_one_page() will think that the page needs to be restored
44737         ** in the database file. And if an IO error occurs while doing so,
44738         ** then corruption may follow.
44739         */
44740         pPg->flags |= PGHDR_NEED_SYNC;
44741
44742         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
44743         if( rc!=SQLCIPHER_OK ) return rc;
44744         rc = sqlcipher3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
44745         if( rc!=SQLCIPHER_OK ) return rc;
44746         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
44747         if( rc!=SQLCIPHER_OK ) return rc;
44748
44749         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
44750                  pPager->journalOff, pPager->pageSize));
44751         PAGER_INCR(sqlcipher3_pager_writej_count);
44752         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
44753              PAGERID(pPager), pPg->pgno, 
44754              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
44755
44756         pPager->journalOff += 8 + pPager->pageSize;
44757         pPager->nRec++;
44758         assert( pPager->pInJournal!=0 );
44759         rc = sqlcipher3BitvecSet(pPager->pInJournal, pPg->pgno);
44760         testcase( rc==SQLCIPHER_NOMEM );
44761         assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_NOMEM );
44762         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
44763         if( rc!=SQLCIPHER_OK ){
44764           assert( rc==SQLCIPHER_NOMEM );
44765           return rc;
44766         }
44767       }else{
44768         if( pPager->eState!=PAGER_WRITER_DBMOD ){
44769           pPg->flags |= PGHDR_NEED_SYNC;
44770         }
44771         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
44772                 PAGERID(pPager), pPg->pgno,
44773                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
44774       }
44775     }
44776   
44777     /* If the statement journal is open and the page is not in it,
44778     ** then write the current page to the statement journal.  Note that
44779     ** the statement journal format differs from the standard journal format
44780     ** in that it omits the checksums and the header.
44781     */
44782     if( subjRequiresPage(pPg) ){
44783       rc = subjournalPage(pPg);
44784     }
44785   }
44786
44787   /* Update the database size and return.
44788   */
44789   if( pPager->dbSize<pPg->pgno ){
44790     pPager->dbSize = pPg->pgno;
44791   }
44792   return rc;
44793 }
44794
44795 /*
44796 ** Mark a data page as writeable. This routine must be called before 
44797 ** making changes to a page. The caller must check the return value 
44798 ** of this function and be careful not to change any page data unless 
44799 ** this routine returns SQLCIPHER_OK.
44800 **
44801 ** The difference between this function and pager_write() is that this
44802 ** function also deals with the special case where 2 or more pages
44803 ** fit on a single disk sector. In this case all co-resident pages
44804 ** must have been written to the journal file before returning.
44805 **
44806 ** If an error occurs, SQLCIPHER_NOMEM or an IO error code is returned
44807 ** as appropriate. Otherwise, SQLCIPHER_OK.
44808 */
44809 SQLCIPHER_PRIVATE int sqlcipher3PagerWrite(DbPage *pDbPage){
44810   int rc = SQLCIPHER_OK;
44811
44812   PgHdr *pPg = pDbPage;
44813   Pager *pPager = pPg->pPager;
44814   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
44815
44816   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44817   assert( pPager->eState!=PAGER_ERROR );
44818   assert( assert_pager_state(pPager) );
44819
44820   if( nPagePerSector>1 ){
44821     Pgno nPageCount;          /* Total number of pages in database file */
44822     Pgno pg1;                 /* First page of the sector pPg is located on. */
44823     int nPage = 0;            /* Number of pages starting at pg1 to journal */
44824     int ii;                   /* Loop counter */
44825     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
44826
44827     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
44828     ** a journal header to be written between the pages journaled by
44829     ** this function.
44830     */
44831     assert( !MEMDB );
44832     assert( pPager->doNotSyncSpill==0 );
44833     pPager->doNotSyncSpill++;
44834
44835     /* This trick assumes that both the page-size and sector-size are
44836     ** an integer power of 2. It sets variable pg1 to the identifier
44837     ** of the first page of the sector pPg is located on.
44838     */
44839     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
44840
44841     nPageCount = pPager->dbSize;
44842     if( pPg->pgno>nPageCount ){
44843       nPage = (pPg->pgno - pg1)+1;
44844     }else if( (pg1+nPagePerSector-1)>nPageCount ){
44845       nPage = nPageCount+1-pg1;
44846     }else{
44847       nPage = nPagePerSector;
44848     }
44849     assert(nPage>0);
44850     assert(pg1<=pPg->pgno);
44851     assert((pg1+nPage)>pPg->pgno);
44852
44853     for(ii=0; ii<nPage && rc==SQLCIPHER_OK; ii++){
44854       Pgno pg = pg1+ii;
44855       PgHdr *pPage;
44856       if( pg==pPg->pgno || !sqlcipher3BitvecTest(pPager->pInJournal, pg) ){
44857         if( pg!=PAGER_MJ_PGNO(pPager) ){
44858           rc = sqlcipher3PagerGet(pPager, pg, &pPage);
44859           if( rc==SQLCIPHER_OK ){
44860             rc = pager_write(pPage);
44861             if( pPage->flags&PGHDR_NEED_SYNC ){
44862               needSync = 1;
44863             }
44864             sqlcipher3PagerUnref(pPage);
44865           }
44866         }
44867       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
44868         if( pPage->flags&PGHDR_NEED_SYNC ){
44869           needSync = 1;
44870         }
44871         sqlcipher3PagerUnref(pPage);
44872       }
44873     }
44874
44875     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
44876     ** starting at pg1, then it needs to be set for all of them. Because
44877     ** writing to any of these nPage pages may damage the others, the
44878     ** journal file must contain sync()ed copies of all of them
44879     ** before any of them can be written out to the database file.
44880     */
44881     if( rc==SQLCIPHER_OK && needSync ){
44882       assert( !MEMDB );
44883       for(ii=0; ii<nPage; ii++){
44884         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
44885         if( pPage ){
44886           pPage->flags |= PGHDR_NEED_SYNC;
44887           sqlcipher3PagerUnref(pPage);
44888         }
44889       }
44890     }
44891
44892     assert( pPager->doNotSyncSpill==1 );
44893     pPager->doNotSyncSpill--;
44894   }else{
44895     rc = pager_write(pDbPage);
44896   }
44897   return rc;
44898 }
44899
44900 /*
44901 ** Return TRUE if the page given in the argument was previously passed
44902 ** to sqlcipher3PagerWrite().  In other words, return TRUE if it is ok
44903 ** to change the content of the page.
44904 */
44905 #ifndef NDEBUG
44906 SQLCIPHER_PRIVATE int sqlcipher3PagerIswriteable(DbPage *pPg){
44907   return pPg->flags&PGHDR_DIRTY;
44908 }
44909 #endif
44910
44911 /*
44912 ** A call to this routine tells the pager that it is not necessary to
44913 ** write the information on page pPg back to the disk, even though
44914 ** that page might be marked as dirty.  This happens, for example, when
44915 ** the page has been added as a leaf of the freelist and so its
44916 ** content no longer matters.
44917 **
44918 ** The overlying software layer calls this routine when all of the data
44919 ** on the given page is unused. The pager marks the page as clean so
44920 ** that it does not get written to disk.
44921 **
44922 ** Tests show that this optimization can quadruple the speed of large 
44923 ** DELETE operations.
44924 */
44925 SQLCIPHER_PRIVATE void sqlcipher3PagerDontWrite(PgHdr *pPg){
44926   Pager *pPager = pPg->pPager;
44927   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44928     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44929     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44930     pPg->flags |= PGHDR_DONT_WRITE;
44931     pager_set_pagehash(pPg);
44932   }
44933 }
44934
44935 /*
44936 ** This routine is called to increment the value of the database file 
44937 ** change-counter, stored as a 4-byte big-endian integer starting at 
44938 ** byte offset 24 of the pager file.  The secondary change counter at
44939 ** 92 is also updated, as is the SQLite version number at offset 96.
44940 **
44941 ** But this only happens if the pPager->changeCountDone flag is false.
44942 ** To avoid excess churning of page 1, the update only happens once.
44943 ** See also the pager_write_changecounter() routine that does an 
44944 ** unconditional update of the change counters.
44945 **
44946 ** If the isDirectMode flag is zero, then this is done by calling 
44947 ** sqlcipher3PagerWrite() on page 1, then modifying the contents of the
44948 ** page data. In this case the file will be updated when the current
44949 ** transaction is committed.
44950 **
44951 ** The isDirectMode flag may only be non-zero if the library was compiled
44952 ** with the SQLCIPHER_ENABLE_ATOMIC_WRITE macro defined. In this case,
44953 ** if isDirect is non-zero, then the database file is updated directly
44954 ** by writing an updated version of page 1 using a call to the 
44955 ** sqlcipher3OsWrite() function.
44956 */
44957 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44958   int rc = SQLCIPHER_OK;
44959
44960   assert( pPager->eState==PAGER_WRITER_CACHEMOD
44961        || pPager->eState==PAGER_WRITER_DBMOD
44962   );
44963   assert( assert_pager_state(pPager) );
44964
44965   /* Declare and initialize constant integer 'isDirect'. If the
44966   ** atomic-write optimization is enabled in this build, then isDirect
44967   ** is initialized to the value passed as the isDirectMode parameter
44968   ** to this function. Otherwise, it is always set to zero.
44969   **
44970   ** The idea is that if the atomic-write optimization is not
44971   ** enabled at compile time, the compiler can omit the tests of
44972   ** 'isDirect' below, as well as the block enclosed in the
44973   ** "if( isDirect )" condition.
44974   */
44975 #ifndef SQLCIPHER_ENABLE_ATOMIC_WRITE
44976 # define DIRECT_MODE 0
44977   assert( isDirectMode==0 );
44978   UNUSED_PARAMETER(isDirectMode);
44979 #else
44980 # define DIRECT_MODE isDirectMode
44981 #endif
44982
44983   if( !pPager->changeCountDone && pPager->dbSize>0 ){
44984     PgHdr *pPgHdr;                /* Reference to page 1 */
44985
44986     assert( !pPager->tempFile && isOpen(pPager->fd) );
44987
44988     /* Open page 1 of the file for writing. */
44989     rc = sqlcipher3PagerGet(pPager, 1, &pPgHdr);
44990     assert( pPgHdr==0 || rc==SQLCIPHER_OK );
44991
44992     /* If page one was fetched successfully, and this function is not
44993     ** operating in direct-mode, make page 1 writable.  When not in 
44994     ** direct mode, page 1 is always held in cache and hence the PagerGet()
44995     ** above is always successful - hence the ALWAYS on rc==SQLCIPHER_OK.
44996     */
44997     if( !DIRECT_MODE && ALWAYS(rc==SQLCIPHER_OK) ){
44998       rc = sqlcipher3PagerWrite(pPgHdr);
44999     }
45000
45001     if( rc==SQLCIPHER_OK ){
45002       /* Actually do the update of the change counter */
45003       pager_write_changecounter(pPgHdr);
45004
45005       /* If running in direct mode, write the contents of page 1 to the file. */
45006       if( DIRECT_MODE ){
45007         const void *zBuf;
45008         assert( pPager->dbFileSize>0 );
45009         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLCIPHER_NOMEM, zBuf);
45010         if( rc==SQLCIPHER_OK ){
45011           rc = sqlcipher3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
45012         }
45013         if( rc==SQLCIPHER_OK ){
45014           pPager->changeCountDone = 1;
45015         }
45016       }else{
45017         pPager->changeCountDone = 1;
45018       }
45019     }
45020
45021     /* Release the page reference. */
45022     sqlcipher3PagerUnref(pPgHdr);
45023   }
45024   return rc;
45025 }
45026
45027 /*
45028 ** Sync the database file to disk. This is a no-op for in-memory databases
45029 ** or pages with the Pager.noSync flag set.
45030 **
45031 ** If successful, or if called on a pager for which it is a no-op, this
45032 ** function returns SQLCIPHER_OK. Otherwise, an IO error code is returned.
45033 */
45034 SQLCIPHER_PRIVATE int sqlcipher3PagerSync(Pager *pPager){
45035   int rc = SQLCIPHER_OK;
45036   if( !pPager->noSync ){
45037     assert( !MEMDB );
45038     rc = sqlcipher3OsSync(pPager->fd, pPager->syncFlags);
45039   }else if( isOpen(pPager->fd) ){
45040     assert( !MEMDB );
45041     sqlcipher3OsFileControl(pPager->fd, SQLCIPHER_FCNTL_SYNC_OMITTED, (void *)&rc);
45042   }
45043   return rc;
45044 }
45045
45046 /*
45047 ** This function may only be called while a write-transaction is active in
45048 ** rollback. If the connection is in WAL mode, this call is a no-op. 
45049 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
45050 ** the database file, an attempt is made to obtain one.
45051 **
45052 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
45053 ** successful, or the connection is in WAL mode, SQLCIPHER_OK is returned.
45054 ** Otherwise, either SQLCIPHER_BUSY or an SQLCIPHER_IOERR_XXX error code is 
45055 ** returned.
45056 */
45057 SQLCIPHER_PRIVATE int sqlcipher3PagerExclusiveLock(Pager *pPager){
45058   int rc = SQLCIPHER_OK;
45059   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
45060        || pPager->eState==PAGER_WRITER_DBMOD 
45061        || pPager->eState==PAGER_WRITER_LOCKED 
45062   );
45063   assert( assert_pager_state(pPager) );
45064   if( 0==pagerUseWal(pPager) ){
45065     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45066   }
45067   return rc;
45068 }
45069
45070 /*
45071 ** Sync the database file for the pager pPager. zMaster points to the name
45072 ** of a master journal file that should be written into the individual
45073 ** journal file. zMaster may be NULL, which is interpreted as no master
45074 ** journal (a single database transaction).
45075 **
45076 ** This routine ensures that:
45077 **
45078 **   * The database file change-counter is updated,
45079 **   * the journal is synced (unless the atomic-write optimization is used),
45080 **   * all dirty pages are written to the database file, 
45081 **   * the database file is truncated (if required), and
45082 **   * the database file synced. 
45083 **
45084 ** The only thing that remains to commit the transaction is to finalize 
45085 ** (delete, truncate or zero the first part of) the journal file (or 
45086 ** delete the master journal file if specified).
45087 **
45088 ** Note that if zMaster==NULL, this does not overwrite a previous value
45089 ** passed to an sqlcipher3PagerCommitPhaseOne() call.
45090 **
45091 ** If the final parameter - noSync - is true, then the database file itself
45092 ** is not synced. The caller must call sqlcipher3PagerSync() directly to
45093 ** sync the database file before calling CommitPhaseTwo() to delete the
45094 ** journal file in this case.
45095 */
45096 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseOne(
45097   Pager *pPager,                  /* Pager object */
45098   const char *zMaster,            /* If not NULL, the master journal name */
45099   int noSync                      /* True to omit the xSync on the db file */
45100 ){
45101   int rc = SQLCIPHER_OK;             /* Return code */
45102
45103   assert( pPager->eState==PAGER_WRITER_LOCKED
45104        || pPager->eState==PAGER_WRITER_CACHEMOD
45105        || pPager->eState==PAGER_WRITER_DBMOD
45106        || pPager->eState==PAGER_ERROR
45107   );
45108   assert( assert_pager_state(pPager) );
45109
45110   /* If a prior error occurred, report that error again. */
45111   if( NEVER(pPager->errCode) ) return pPager->errCode;
45112
45113   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
45114       pPager->zFilename, zMaster, pPager->dbSize));
45115
45116   /* If no database changes have been made, return early. */
45117   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLCIPHER_OK;
45118
45119   if( MEMDB ){
45120     /* If this is an in-memory db, or no pages have been written to, or this
45121     ** function has already been called, it is mostly a no-op.  However, any
45122     ** backup in progress needs to be restarted.
45123     */
45124     sqlcipher3BackupRestart(pPager->pBackup);
45125   }else{
45126     if( pagerUseWal(pPager) ){
45127       PgHdr *pList = sqlcipher3PcacheDirtyList(pPager->pPCache);
45128       PgHdr *pPageOne = 0;
45129       if( pList==0 ){
45130         /* Must have at least one page for the WAL commit flag.
45131         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
45132         rc = sqlcipher3PagerGet(pPager, 1, &pPageOne);
45133         pList = pPageOne;
45134         pList->pDirty = 0;
45135       }
45136       assert( rc==SQLCIPHER_OK );
45137       if( ALWAYS(pList) ){
45138         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
45139             (pPager->fullSync ? pPager->syncFlags : 0)
45140         );
45141       }
45142       sqlcipher3PagerUnref(pPageOne);
45143       if( rc==SQLCIPHER_OK ){
45144         sqlcipher3PcacheCleanAll(pPager->pPCache);
45145       }
45146     }else{
45147       /* The following block updates the change-counter. Exactly how it
45148       ** does this depends on whether or not the atomic-update optimization
45149       ** was enabled at compile time, and if this transaction meets the 
45150       ** runtime criteria to use the operation: 
45151       **
45152       **    * The file-system supports the atomic-write property for
45153       **      blocks of size page-size, and 
45154       **    * This commit is not part of a multi-file transaction, and
45155       **    * Exactly one page has been modified and store in the journal file.
45156       **
45157       ** If the optimization was not enabled at compile time, then the
45158       ** pager_incr_changecounter() function is called to update the change
45159       ** counter in 'indirect-mode'. If the optimization is compiled in but
45160       ** is not applicable to this transaction, call sqlcipher3JournalCreate()
45161       ** to make sure the journal file has actually been created, then call
45162       ** pager_incr_changecounter() to update the change-counter in indirect
45163       ** mode. 
45164       **
45165       ** Otherwise, if the optimization is both enabled and applicable,
45166       ** then call pager_incr_changecounter() to update the change-counter
45167       ** in 'direct' mode. In this case the journal file will never be
45168       ** created for this transaction.
45169       */
45170   #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
45171       PgHdr *pPg;
45172       assert( isOpen(pPager->jfd) 
45173            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
45174            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
45175       );
45176       if( !zMaster && isOpen(pPager->jfd) 
45177        && pPager->journalOff==jrnlBufferSize(pPager) 
45178        && pPager->dbSize>=pPager->dbOrigSize
45179        && (0==(pPg = sqlcipher3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
45180       ){
45181         /* Update the db file change counter via the direct-write method. The 
45182         ** following call will modify the in-memory representation of page 1 
45183         ** to include the updated change counter and then write page 1 
45184         ** directly to the database file. Because of the atomic-write 
45185         ** property of the host file-system, this is safe.
45186         */
45187         rc = pager_incr_changecounter(pPager, 1);
45188       }else{
45189         rc = sqlcipher3JournalCreate(pPager->jfd);
45190         if( rc==SQLCIPHER_OK ){
45191           rc = pager_incr_changecounter(pPager, 0);
45192         }
45193       }
45194   #else
45195       rc = pager_incr_changecounter(pPager, 0);
45196   #endif
45197       if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45198   
45199       /* If this transaction has made the database smaller, then all pages
45200       ** being discarded by the truncation must be written to the journal
45201       ** file. This can only happen in auto-vacuum mode.
45202       **
45203       ** Before reading the pages with page numbers larger than the 
45204       ** current value of Pager.dbSize, set dbSize back to the value
45205       ** that it took at the start of the transaction. Otherwise, the
45206       ** calls to sqlcipher3PagerGet() return zeroed pages instead of 
45207       ** reading data from the database file.
45208       */
45209   #ifndef SQLCIPHER_OMIT_AUTOVACUUM
45210       if( pPager->dbSize<pPager->dbOrigSize 
45211        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
45212       ){
45213         Pgno i;                                   /* Iterator variable */
45214         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
45215         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
45216         pPager->dbSize = pPager->dbOrigSize;
45217         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
45218           if( !sqlcipher3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
45219             PgHdr *pPage;             /* Page to journal */
45220             rc = sqlcipher3PagerGet(pPager, i, &pPage);
45221             if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45222             rc = sqlcipher3PagerWrite(pPage);
45223             sqlcipher3PagerUnref(pPage);
45224             if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45225           }
45226         }
45227         pPager->dbSize = dbSize;
45228       } 
45229   #endif
45230   
45231       /* Write the master journal name into the journal file. If a master 
45232       ** journal file name has already been written to the journal file, 
45233       ** or if zMaster is NULL (no master journal), then this call is a no-op.
45234       */
45235       rc = writeMasterJournal(pPager, zMaster);
45236       if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45237   
45238       /* Sync the journal file and write all dirty pages to the database.
45239       ** If the atomic-update optimization is being used, this sync will not 
45240       ** create the journal file or perform any real IO.
45241       **
45242       ** Because the change-counter page was just modified, unless the
45243       ** atomic-update optimization is used it is almost certain that the
45244       ** journal requires a sync here. However, in locking_mode=exclusive
45245       ** on a system under memory pressure it is just possible that this is 
45246       ** not the case. In this case it is likely enough that the redundant
45247       ** xSync() call will be changed to a no-op by the OS anyhow. 
45248       */
45249       rc = syncJournal(pPager, 0);
45250       if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45251   
45252       rc = pager_write_pagelist(pPager,sqlcipher3PcacheDirtyList(pPager->pPCache));
45253       if( rc!=SQLCIPHER_OK ){
45254         assert( rc!=SQLCIPHER_IOERR_BLOCKED );
45255         goto commit_phase_one_exit;
45256       }
45257       sqlcipher3PcacheCleanAll(pPager->pPCache);
45258   
45259       /* If the file on disk is not the same size as the database image,
45260       ** then use pager_truncate to grow or shrink the file here.
45261       */
45262       if( pPager->dbSize!=pPager->dbFileSize ){
45263         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
45264         assert( pPager->eState==PAGER_WRITER_DBMOD );
45265         rc = pager_truncate(pPager, nNew);
45266         if( rc!=SQLCIPHER_OK ) goto commit_phase_one_exit;
45267       }
45268   
45269       /* Finally, sync the database file. */
45270       if( !noSync ){
45271         rc = sqlcipher3PagerSync(pPager);
45272       }
45273       IOTRACE(("DBSYNC %p\n", pPager))
45274     }
45275   }
45276
45277 commit_phase_one_exit:
45278   if( rc==SQLCIPHER_OK && !pagerUseWal(pPager) ){
45279     pPager->eState = PAGER_WRITER_FINISHED;
45280   }
45281   return rc;
45282 }
45283
45284
45285 /*
45286 ** When this function is called, the database file has been completely
45287 ** updated to reflect the changes made by the current transaction and
45288 ** synced to disk. The journal file still exists in the file-system 
45289 ** though, and if a failure occurs at this point it will eventually
45290 ** be used as a hot-journal and the current transaction rolled back.
45291 **
45292 ** This function finalizes the journal file, either by deleting, 
45293 ** truncating or partially zeroing it, so that it cannot be used 
45294 ** for hot-journal rollback. Once this is done the transaction is
45295 ** irrevocably committed.
45296 **
45297 ** If an error occurs, an IO error code is returned and the pager
45298 ** moves into the error state. Otherwise, SQLCIPHER_OK is returned.
45299 */
45300 SQLCIPHER_PRIVATE int sqlcipher3PagerCommitPhaseTwo(Pager *pPager){
45301   int rc = SQLCIPHER_OK;                  /* Return code */
45302
45303   /* This routine should not be called if a prior error has occurred.
45304   ** But if (due to a coding error elsewhere in the system) it does get
45305   ** called, just return the same error code without doing anything. */
45306   if( NEVER(pPager->errCode) ) return pPager->errCode;
45307
45308   assert( pPager->eState==PAGER_WRITER_LOCKED
45309        || pPager->eState==PAGER_WRITER_FINISHED
45310        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
45311   );
45312   assert( assert_pager_state(pPager) );
45313
45314   /* An optimization. If the database was not actually modified during
45315   ** this transaction, the pager is running in exclusive-mode and is
45316   ** using persistent journals, then this function is a no-op.
45317   **
45318   ** The start of the journal file currently contains a single journal 
45319   ** header with the nRec field set to 0. If such a journal is used as
45320   ** a hot-journal during hot-journal rollback, 0 changes will be made
45321   ** to the database file. So there is no need to zero the journal 
45322   ** header. Since the pager is in exclusive mode, there is no need
45323   ** to drop any locks either.
45324   */
45325   if( pPager->eState==PAGER_WRITER_LOCKED 
45326    && pPager->exclusiveMode 
45327    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
45328   ){
45329     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
45330     pPager->eState = PAGER_READER;
45331     return SQLCIPHER_OK;
45332   }
45333
45334   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
45335   rc = pager_end_transaction(pPager, pPager->setMaster);
45336   return pager_error(pPager, rc);
45337 }
45338
45339 /*
45340 ** If a write transaction is open, then all changes made within the 
45341 ** transaction are reverted and the current write-transaction is closed.
45342 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
45343 ** state if an error occurs.
45344 **
45345 ** If the pager is already in PAGER_ERROR state when this function is called,
45346 ** it returns Pager.errCode immediately. No work is performed in this case.
45347 **
45348 ** Otherwise, in rollback mode, this function performs two functions:
45349 **
45350 **   1) It rolls back the journal file, restoring all database file and 
45351 **      in-memory cache pages to the state they were in when the transaction
45352 **      was opened, and
45353 **
45354 **   2) It finalizes the journal file, so that it is not used for hot
45355 **      rollback at any point in the future.
45356 **
45357 ** Finalization of the journal file (task 2) is only performed if the 
45358 ** rollback is successful.
45359 **
45360 ** In WAL mode, all cache-entries containing data modified within the
45361 ** current transaction are either expelled from the cache or reverted to
45362 ** their pre-transaction state by re-reading data from the database or
45363 ** WAL files. The WAL transaction is then closed.
45364 */
45365 SQLCIPHER_PRIVATE int sqlcipher3PagerRollback(Pager *pPager){
45366   int rc = SQLCIPHER_OK;                  /* Return code */
45367   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
45368
45369   /* PagerRollback() is a no-op if called in READER or OPEN state. If
45370   ** the pager is already in the ERROR state, the rollback is not 
45371   ** attempted here. Instead, the error code is returned to the caller.
45372   */
45373   assert( assert_pager_state(pPager) );
45374   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
45375   if( pPager->eState<=PAGER_READER ) return SQLCIPHER_OK;
45376
45377   if( pagerUseWal(pPager) ){
45378     int rc2;
45379     rc = sqlcipher3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
45380     rc2 = pager_end_transaction(pPager, pPager->setMaster);
45381     if( rc==SQLCIPHER_OK ) rc = rc2;
45382   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
45383     int eState = pPager->eState;
45384     rc = pager_end_transaction(pPager, 0);
45385     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
45386       /* This can happen using journal_mode=off. Move the pager to the error 
45387       ** state to indicate that the contents of the cache may not be trusted.
45388       ** Any active readers will get SQLCIPHER_ABORT.
45389       */
45390       pPager->errCode = SQLCIPHER_ABORT;
45391       pPager->eState = PAGER_ERROR;
45392       return rc;
45393     }
45394   }else{
45395     rc = pager_playback(pPager, 0);
45396   }
45397
45398   assert( pPager->eState==PAGER_READER || rc!=SQLCIPHER_OK );
45399   assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_FULL || (rc&0xFF)==SQLCIPHER_IOERR );
45400
45401   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
45402   ** cache. So call pager_error() on the way out to make any error persistent.
45403   */
45404   return pager_error(pPager, rc);
45405 }
45406
45407 /*
45408 ** Return TRUE if the database file is opened read-only.  Return FALSE
45409 ** if the database is (in theory) writable.
45410 */
45411 SQLCIPHER_PRIVATE u8 sqlcipher3PagerIsreadonly(Pager *pPager){
45412   return pPager->readOnly;
45413 }
45414
45415 /*
45416 ** Return the number of references to the pager.
45417 */
45418 SQLCIPHER_PRIVATE int sqlcipher3PagerRefcount(Pager *pPager){
45419   return sqlcipher3PcacheRefCount(pPager->pPCache);
45420 }
45421
45422 /*
45423 ** Return the approximate number of bytes of memory currently
45424 ** used by the pager and its associated cache.
45425 */
45426 SQLCIPHER_PRIVATE int sqlcipher3PagerMemUsed(Pager *pPager){
45427   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
45428                                      + 5*sizeof(void*);
45429   return perPageSize*sqlcipher3PcachePagecount(pPager->pPCache)
45430            + sqlcipher3MallocSize(pPager)
45431            + pPager->pageSize;
45432 }
45433
45434 /*
45435 ** Return the number of references to the specified page.
45436 */
45437 SQLCIPHER_PRIVATE int sqlcipher3PagerPageRefcount(DbPage *pPage){
45438   return sqlcipher3PcachePageRefcount(pPage);
45439 }
45440
45441 #ifdef SQLCIPHER_TEST
45442 /*
45443 ** This routine is used for testing and analysis only.
45444 */
45445 SQLCIPHER_PRIVATE int *sqlcipher3PagerStats(Pager *pPager){
45446   static int a[11];
45447   a[0] = sqlcipher3PcacheRefCount(pPager->pPCache);
45448   a[1] = sqlcipher3PcachePagecount(pPager->pPCache);
45449   a[2] = sqlcipher3PcacheGetCachesize(pPager->pPCache);
45450   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
45451   a[4] = pPager->eState;
45452   a[5] = pPager->errCode;
45453   a[6] = pPager->nHit;
45454   a[7] = pPager->nMiss;
45455   a[8] = 0;  /* Used to be pPager->nOvfl */
45456   a[9] = pPager->nRead;
45457   a[10] = pPager->nWrite;
45458   return a;
45459 }
45460 #endif
45461
45462 /*
45463 ** Parameter eStat must be either SQLCIPHER_DBSTATUS_CACHE_HIT or
45464 ** SQLCIPHER_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
45465 ** current cache hit or miss count, according to the value of eStat. If the 
45466 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
45467 ** returning.
45468 */
45469 SQLCIPHER_PRIVATE void sqlcipher3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
45470   int *piStat;
45471
45472   assert( eStat==SQLCIPHER_DBSTATUS_CACHE_HIT
45473        || eStat==SQLCIPHER_DBSTATUS_CACHE_MISS
45474   );
45475   if( eStat==SQLCIPHER_DBSTATUS_CACHE_HIT ){
45476     piStat = &pPager->nHit;
45477   }else{
45478     piStat = &pPager->nMiss;
45479   }
45480
45481   *pnVal += *piStat;
45482   if( reset ){
45483     *piStat = 0;
45484   }
45485 }
45486
45487 /*
45488 ** Return true if this is an in-memory pager.
45489 */
45490 SQLCIPHER_PRIVATE int sqlcipher3PagerIsMemdb(Pager *pPager){
45491   return MEMDB;
45492 }
45493
45494 /*
45495 ** Check that there are at least nSavepoint savepoints open. If there are
45496 ** currently less than nSavepoints open, then open one or more savepoints
45497 ** to make up the difference. If the number of savepoints is already
45498 ** equal to nSavepoint, then this function is a no-op.
45499 **
45500 ** If a memory allocation fails, SQLCIPHER_NOMEM is returned. If an error 
45501 ** occurs while opening the sub-journal file, then an IO error code is
45502 ** returned. Otherwise, SQLCIPHER_OK.
45503 */
45504 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
45505   int rc = SQLCIPHER_OK;                       /* Return code */
45506   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
45507
45508   assert( pPager->eState>=PAGER_WRITER_LOCKED );
45509   assert( assert_pager_state(pPager) );
45510
45511   if( nSavepoint>nCurrent && pPager->useJournal ){
45512     int ii;                                 /* Iterator variable */
45513     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
45514
45515     /* Grow the Pager.aSavepoint array using realloc(). Return SQLCIPHER_NOMEM
45516     ** if the allocation fails. Otherwise, zero the new portion in case a 
45517     ** malloc failure occurs while populating it in the for(...) loop below.
45518     */
45519     aNew = (PagerSavepoint *)sqlcipher3Realloc(
45520         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
45521     );
45522     if( !aNew ){
45523       return SQLCIPHER_NOMEM;
45524     }
45525     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
45526     pPager->aSavepoint = aNew;
45527
45528     /* Populate the PagerSavepoint structures just allocated. */
45529     for(ii=nCurrent; ii<nSavepoint; ii++){
45530       aNew[ii].nOrig = pPager->dbSize;
45531       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
45532         aNew[ii].iOffset = pPager->journalOff;
45533       }else{
45534         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
45535       }
45536       aNew[ii].iSubRec = pPager->nSubRec;
45537       aNew[ii].pInSavepoint = sqlcipher3BitvecCreate(pPager->dbSize);
45538       if( !aNew[ii].pInSavepoint ){
45539         return SQLCIPHER_NOMEM;
45540       }
45541       if( pagerUseWal(pPager) ){
45542         sqlcipher3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
45543       }
45544       pPager->nSavepoint = ii+1;
45545     }
45546     assert( pPager->nSavepoint==nSavepoint );
45547     assertTruncateConstraint(pPager);
45548   }
45549
45550   return rc;
45551 }
45552
45553 /*
45554 ** This function is called to rollback or release (commit) a savepoint.
45555 ** The savepoint to release or rollback need not be the most recently 
45556 ** created savepoint.
45557 **
45558 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
45559 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
45560 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
45561 ** that have occurred since the specified savepoint was created.
45562 **
45563 ** The savepoint to rollback or release is identified by parameter 
45564 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
45565 ** (the first created). A value of (Pager.nSavepoint-1) means operate
45566 ** on the most recently created savepoint. If iSavepoint is greater than
45567 ** (Pager.nSavepoint-1), then this function is a no-op.
45568 **
45569 ** If a negative value is passed to this function, then the current
45570 ** transaction is rolled back. This is different to calling 
45571 ** sqlcipher3PagerRollback() because this function does not terminate
45572 ** the transaction or unlock the database, it just restores the 
45573 ** contents of the database to its original state. 
45574 **
45575 ** In any case, all savepoints with an index greater than iSavepoint 
45576 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
45577 ** then savepoint iSavepoint is also destroyed.
45578 **
45579 ** This function may return SQLCIPHER_NOMEM if a memory allocation fails,
45580 ** or an IO error code if an IO error occurs while rolling back a 
45581 ** savepoint. If no errors occur, SQLCIPHER_OK is returned.
45582 */ 
45583 SQLCIPHER_PRIVATE int sqlcipher3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
45584   int rc = pPager->errCode;       /* Return code */
45585
45586   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
45587   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
45588
45589   if( rc==SQLCIPHER_OK && iSavepoint<pPager->nSavepoint ){
45590     int ii;            /* Iterator variable */
45591     int nNew;          /* Number of remaining savepoints after this op. */
45592
45593     /* Figure out how many savepoints will still be active after this
45594     ** operation. Store this value in nNew. Then free resources associated 
45595     ** with any savepoints that are destroyed by this operation.
45596     */
45597     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
45598     for(ii=nNew; ii<pPager->nSavepoint; ii++){
45599       sqlcipher3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
45600     }
45601     pPager->nSavepoint = nNew;
45602
45603     /* If this is a release of the outermost savepoint, truncate 
45604     ** the sub-journal to zero bytes in size. */
45605     if( op==SAVEPOINT_RELEASE ){
45606       if( nNew==0 && isOpen(pPager->sjfd) ){
45607         /* Only truncate if it is an in-memory sub-journal. */
45608         if( sqlcipher3IsMemJournal(pPager->sjfd) ){
45609           rc = sqlcipher3OsTruncate(pPager->sjfd, 0);
45610           assert( rc==SQLCIPHER_OK );
45611         }
45612         pPager->nSubRec = 0;
45613       }
45614     }
45615     /* Else this is a rollback operation, playback the specified savepoint.
45616     ** If this is a temp-file, it is possible that the journal file has
45617     ** not yet been opened. In this case there have been no changes to
45618     ** the database file, so the playback operation can be skipped.
45619     */
45620     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
45621       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
45622       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
45623       assert(rc!=SQLCIPHER_DONE);
45624     }
45625   }
45626
45627   return rc;
45628 }
45629
45630 /*
45631 ** Return the full pathname of the database file.
45632 */
45633 SQLCIPHER_PRIVATE const char *sqlcipher3PagerFilename(Pager *pPager){
45634   return pPager->zFilename;
45635 }
45636
45637 /*
45638 ** Return the VFS structure for the pager.
45639 */
45640 SQLCIPHER_PRIVATE const sqlcipher3_vfs *sqlcipher3PagerVfs(Pager *pPager){
45641   return pPager->pVfs;
45642 }
45643
45644 /*
45645 ** Return the file handle for the database file associated
45646 ** with the pager.  This might return NULL if the file has
45647 ** not yet been opened.
45648 */
45649 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3PagerFile(Pager *pPager){
45650   return pPager->fd;
45651 }
45652
45653 /*
45654 ** Return the full pathname of the journal file.
45655 */
45656 SQLCIPHER_PRIVATE const char *sqlcipher3PagerJournalname(Pager *pPager){
45657   return pPager->zJournal;
45658 }
45659
45660 /*
45661 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
45662 ** if fsync()s are executed normally.
45663 */
45664 SQLCIPHER_PRIVATE int sqlcipher3PagerNosync(Pager *pPager){
45665   return pPager->noSync;
45666 }
45667
45668 #ifdef SQLCIPHER_HAS_CODEC
45669 /*
45670 ** Set or retrieve the codec for this pager
45671 */
45672 SQLCIPHER_PRIVATE void sqlcipher3PagerSetCodec(
45673   Pager *pPager,
45674   void *(*xCodec)(void*,void*,Pgno,int),
45675   void (*xCodecSizeChng)(void*,int,int),
45676   void (*xCodecFree)(void*),
45677   void *pCodec
45678 ){
45679   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
45680   pPager->xCodec = pPager->memDb ? 0 : xCodec;
45681   pPager->xCodecSizeChng = xCodecSizeChng;
45682   pPager->xCodecFree = xCodecFree;
45683   pPager->pCodec = pCodec;
45684   pagerReportSize(pPager);
45685 }
45686 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetCodec(Pager *pPager){
45687   return pPager->pCodec;
45688 }
45689 #endif
45690
45691 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
45692 /*
45693 ** Move the page pPg to location pgno in the file.
45694 **
45695 ** There must be no references to the page previously located at
45696 ** pgno (which we call pPgOld) though that page is allowed to be
45697 ** in cache.  If the page previously located at pgno is not already
45698 ** in the rollback journal, it is not put there by by this routine.
45699 **
45700 ** References to the page pPg remain valid. Updating any
45701 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
45702 ** allocated along with the page) is the responsibility of the caller.
45703 **
45704 ** A transaction must be active when this routine is called. It used to be
45705 ** required that a statement transaction was not active, but this restriction
45706 ** has been removed (CREATE INDEX needs to move a page when a statement
45707 ** transaction is active).
45708 **
45709 ** If the fourth argument, isCommit, is non-zero, then this page is being
45710 ** moved as part of a database reorganization just before the transaction 
45711 ** is being committed. In this case, it is guaranteed that the database page 
45712 ** pPg refers to will not be written to again within this transaction.
45713 **
45714 ** This function may return SQLCIPHER_NOMEM or an IO error code if an error
45715 ** occurs. Otherwise, it returns SQLCIPHER_OK.
45716 */
45717 SQLCIPHER_PRIVATE int sqlcipher3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
45718   PgHdr *pPgOld;               /* The page being overwritten. */
45719   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
45720   int rc;                      /* Return code */
45721   Pgno origPgno;               /* The original page number */
45722
45723   assert( pPg->nRef>0 );
45724   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45725        || pPager->eState==PAGER_WRITER_DBMOD
45726   );
45727   assert( assert_pager_state(pPager) );
45728
45729   /* In order to be able to rollback, an in-memory database must journal
45730   ** the page we are moving from.
45731   */
45732   if( MEMDB ){
45733     rc = sqlcipher3PagerWrite(pPg);
45734     if( rc ) return rc;
45735   }
45736
45737   /* If the page being moved is dirty and has not been saved by the latest
45738   ** savepoint, then save the current contents of the page into the 
45739   ** sub-journal now. This is required to handle the following scenario:
45740   **
45741   **   BEGIN;
45742   **     <journal page X, then modify it in memory>
45743   **     SAVEPOINT one;
45744   **       <Move page X to location Y>
45745   **     ROLLBACK TO one;
45746   **
45747   ** If page X were not written to the sub-journal here, it would not
45748   ** be possible to restore its contents when the "ROLLBACK TO one"
45749   ** statement were is processed.
45750   **
45751   ** subjournalPage() may need to allocate space to store pPg->pgno into
45752   ** one or more savepoint bitvecs. This is the reason this function
45753   ** may return SQLCIPHER_NOMEM.
45754   */
45755   if( pPg->flags&PGHDR_DIRTY
45756    && subjRequiresPage(pPg)
45757    && SQLCIPHER_OK!=(rc = subjournalPage(pPg))
45758   ){
45759     return rc;
45760   }
45761
45762   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
45763       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
45764   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
45765
45766   /* If the journal needs to be sync()ed before page pPg->pgno can
45767   ** be written to, store pPg->pgno in local variable needSyncPgno.
45768   **
45769   ** If the isCommit flag is set, there is no need to remember that
45770   ** the journal needs to be sync()ed before database page pPg->pgno 
45771   ** can be written to. The caller has already promised not to write to it.
45772   */
45773   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
45774     needSyncPgno = pPg->pgno;
45775     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
45776     assert( pPg->flags&PGHDR_DIRTY );
45777   }
45778
45779   /* If the cache contains a page with page-number pgno, remove it
45780   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
45781   ** page pgno before the 'move' operation, it needs to be retained 
45782   ** for the page moved there.
45783   */
45784   pPg->flags &= ~PGHDR_NEED_SYNC;
45785   pPgOld = pager_lookup(pPager, pgno);
45786   assert( !pPgOld || pPgOld->nRef==1 );
45787   if( pPgOld ){
45788     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
45789     if( MEMDB ){
45790       /* Do not discard pages from an in-memory database since we might
45791       ** need to rollback later.  Just move the page out of the way. */
45792       sqlcipher3PcacheMove(pPgOld, pPager->dbSize+1);
45793     }else{
45794       sqlcipher3PcacheDrop(pPgOld);
45795     }
45796   }
45797
45798   origPgno = pPg->pgno;
45799   sqlcipher3PcacheMove(pPg, pgno);
45800   sqlcipher3PcacheMakeDirty(pPg);
45801
45802   /* For an in-memory database, make sure the original page continues
45803   ** to exist, in case the transaction needs to roll back.  Use pPgOld
45804   ** as the original page since it has already been allocated.
45805   */
45806   if( MEMDB ){
45807     assert( pPgOld );
45808     sqlcipher3PcacheMove(pPgOld, origPgno);
45809     sqlcipher3PagerUnref(pPgOld);
45810   }
45811
45812   if( needSyncPgno ){
45813     /* If needSyncPgno is non-zero, then the journal file needs to be 
45814     ** sync()ed before any data is written to database file page needSyncPgno.
45815     ** Currently, no such page exists in the page-cache and the 
45816     ** "is journaled" bitvec flag has been set. This needs to be remedied by
45817     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
45818     ** flag.
45819     **
45820     ** If the attempt to load the page into the page-cache fails, (due
45821     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
45822     ** array. Otherwise, if the page is loaded and written again in
45823     ** this transaction, it may be written to the database file before
45824     ** it is synced into the journal file. This way, it may end up in
45825     ** the journal file twice, but that is not a problem.
45826     */
45827     PgHdr *pPgHdr;
45828     rc = sqlcipher3PagerGet(pPager, needSyncPgno, &pPgHdr);
45829     if( rc!=SQLCIPHER_OK ){
45830       if( needSyncPgno<=pPager->dbOrigSize ){
45831         assert( pPager->pTmpSpace!=0 );
45832         sqlcipher3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
45833       }
45834       return rc;
45835     }
45836     pPgHdr->flags |= PGHDR_NEED_SYNC;
45837     sqlcipher3PcacheMakeDirty(pPgHdr);
45838     sqlcipher3PagerUnref(pPgHdr);
45839   }
45840
45841   return SQLCIPHER_OK;
45842 }
45843 #endif
45844
45845 /*
45846 ** Return a pointer to the data for the specified page.
45847 */
45848 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetData(DbPage *pPg){
45849   assert( pPg->nRef>0 || pPg->pPager->memDb );
45850   return pPg->pData;
45851 }
45852
45853 /*
45854 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
45855 ** allocated along with the specified page.
45856 */
45857 SQLCIPHER_PRIVATE void *sqlcipher3PagerGetExtra(DbPage *pPg){
45858   return pPg->pExtra;
45859 }
45860
45861 /*
45862 ** Get/set the locking-mode for this pager. Parameter eMode must be one
45863 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
45864 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
45865 ** the locking-mode is set to the value specified.
45866 **
45867 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
45868 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
45869 ** locking-mode.
45870 */
45871 SQLCIPHER_PRIVATE int sqlcipher3PagerLockingMode(Pager *pPager, int eMode){
45872   assert( eMode==PAGER_LOCKINGMODE_QUERY
45873             || eMode==PAGER_LOCKINGMODE_NORMAL
45874             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
45875   assert( PAGER_LOCKINGMODE_QUERY<0 );
45876   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
45877   assert( pPager->exclusiveMode || 0==sqlcipher3WalHeapMemory(pPager->pWal) );
45878   if( eMode>=0 && !pPager->tempFile && !sqlcipher3WalHeapMemory(pPager->pWal) ){
45879     pPager->exclusiveMode = (u8)eMode;
45880   }
45881   return (int)pPager->exclusiveMode;
45882 }
45883
45884 /*
45885 ** Set the journal-mode for this pager. Parameter eMode must be one of:
45886 **
45887 **    PAGER_JOURNALMODE_DELETE
45888 **    PAGER_JOURNALMODE_TRUNCATE
45889 **    PAGER_JOURNALMODE_PERSIST
45890 **    PAGER_JOURNALMODE_OFF
45891 **    PAGER_JOURNALMODE_MEMORY
45892 **    PAGER_JOURNALMODE_WAL
45893 **
45894 ** The journalmode is set to the value specified if the change is allowed.
45895 ** The change may be disallowed for the following reasons:
45896 **
45897 **   *  An in-memory database can only have its journal_mode set to _OFF
45898 **      or _MEMORY.
45899 **
45900 **   *  Temporary databases cannot have _WAL journalmode.
45901 **
45902 ** The returned indicate the current (possibly updated) journal-mode.
45903 */
45904 SQLCIPHER_PRIVATE int sqlcipher3PagerSetJournalMode(Pager *pPager, int eMode){
45905   u8 eOld = pPager->journalMode;    /* Prior journalmode */
45906
45907 #ifdef SQLCIPHER_DEBUG
45908   /* The print_pager_state() routine is intended to be used by the debugger
45909   ** only.  We invoke it once here to suppress a compiler warning. */
45910   print_pager_state(pPager);
45911 #endif
45912
45913
45914   /* The eMode parameter is always valid */
45915   assert(      eMode==PAGER_JOURNALMODE_DELETE
45916             || eMode==PAGER_JOURNALMODE_TRUNCATE
45917             || eMode==PAGER_JOURNALMODE_PERSIST
45918             || eMode==PAGER_JOURNALMODE_OFF 
45919             || eMode==PAGER_JOURNALMODE_WAL 
45920             || eMode==PAGER_JOURNALMODE_MEMORY );
45921
45922   /* This routine is only called from the OP_JournalMode opcode, and
45923   ** the logic there will never allow a temporary file to be changed
45924   ** to WAL mode.
45925   */
45926   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45927
45928   /* Do allow the journalmode of an in-memory database to be set to
45929   ** anything other than MEMORY or OFF
45930   */
45931   if( MEMDB ){
45932     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45933     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45934       eMode = eOld;
45935     }
45936   }
45937
45938   if( eMode!=eOld ){
45939
45940     /* Change the journal mode. */
45941     assert( pPager->eState!=PAGER_ERROR );
45942     pPager->journalMode = (u8)eMode;
45943
45944     /* When transistioning from TRUNCATE or PERSIST to any other journal
45945     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45946     ** delete the journal file.
45947     */
45948     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45949     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45950     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45951     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45952     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45953     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45954
45955     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45956     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45957
45958       /* In this case we would like to delete the journal file. If it is
45959       ** not possible, then that is not a problem. Deleting the journal file
45960       ** here is an optimization only.
45961       **
45962       ** Before deleting the journal file, obtain a RESERVED lock on the
45963       ** database file. This ensures that the journal file is not deleted
45964       ** while it is in use by some other client.
45965       */
45966       sqlcipher3OsClose(pPager->jfd);
45967       if( pPager->eLock>=RESERVED_LOCK ){
45968         sqlcipher3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45969       }else{
45970         int rc = SQLCIPHER_OK;
45971         int state = pPager->eState;
45972         assert( state==PAGER_OPEN || state==PAGER_READER );
45973         if( state==PAGER_OPEN ){
45974           rc = sqlcipher3PagerSharedLock(pPager);
45975         }
45976         if( pPager->eState==PAGER_READER ){
45977           assert( rc==SQLCIPHER_OK );
45978           rc = pagerLockDb(pPager, RESERVED_LOCK);
45979         }
45980         if( rc==SQLCIPHER_OK ){
45981           sqlcipher3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45982         }
45983         if( rc==SQLCIPHER_OK && state==PAGER_READER ){
45984           pagerUnlockDb(pPager, SHARED_LOCK);
45985         }else if( state==PAGER_OPEN ){
45986           pager_unlock(pPager);
45987         }
45988         assert( state==pPager->eState );
45989       }
45990     }
45991   }
45992
45993   /* Return the new journal mode */
45994   return (int)pPager->journalMode;
45995 }
45996
45997 /*
45998 ** Return the current journal mode.
45999 */
46000 SQLCIPHER_PRIVATE int sqlcipher3PagerGetJournalMode(Pager *pPager){
46001   return (int)pPager->journalMode;
46002 }
46003
46004 /*
46005 ** Return TRUE if the pager is in a state where it is OK to change the
46006 ** journalmode.  Journalmode changes can only happen when the database
46007 ** is unmodified.
46008 */
46009 SQLCIPHER_PRIVATE int sqlcipher3PagerOkToChangeJournalMode(Pager *pPager){
46010   assert( assert_pager_state(pPager) );
46011   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
46012   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
46013   return 1;
46014 }
46015
46016 /*
46017 ** Get/set the size-limit used for persistent journal files.
46018 **
46019 ** Setting the size limit to -1 means no limit is enforced.
46020 ** An attempt to set a limit smaller than -1 is a no-op.
46021 */
46022 SQLCIPHER_PRIVATE i64 sqlcipher3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
46023   if( iLimit>=-1 ){
46024     pPager->journalSizeLimit = iLimit;
46025     sqlcipher3WalLimit(pPager->pWal, iLimit);
46026   }
46027   return pPager->journalSizeLimit;
46028 }
46029
46030 /*
46031 ** Return a pointer to the pPager->pBackup variable. The backup module
46032 ** in backup.c maintains the content of this variable. This module
46033 ** uses it opaquely as an argument to sqlcipher3BackupRestart() and
46034 ** sqlcipher3BackupUpdate() only.
46035 */
46036 SQLCIPHER_PRIVATE sqlcipher3_backup **sqlcipher3PagerBackupPtr(Pager *pPager){
46037   return &pPager->pBackup;
46038 }
46039
46040 #ifndef SQLCIPHER_OMIT_WAL
46041 /*
46042 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
46043 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlcipher3_wal_checkpoint()
46044 ** or wal_blocking_checkpoint() API functions.
46045 **
46046 ** Parameter eMode is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL or RESTART.
46047 */
46048 SQLCIPHER_PRIVATE int sqlcipher3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
46049   int rc = SQLCIPHER_OK;
46050   if( pPager->pWal ){
46051     rc = sqlcipher3WalCheckpoint(pPager->pWal, eMode,
46052         pPager->xBusyHandler, pPager->pBusyHandlerArg,
46053         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
46054         pnLog, pnCkpt
46055     );
46056   }
46057   return rc;
46058 }
46059
46060 SQLCIPHER_PRIVATE int sqlcipher3PagerWalCallback(Pager *pPager){
46061   return sqlcipher3WalCallback(pPager->pWal);
46062 }
46063
46064 /*
46065 ** Return true if the underlying VFS for the given pager supports the
46066 ** primitives necessary for write-ahead logging.
46067 */
46068 SQLCIPHER_PRIVATE int sqlcipher3PagerWalSupported(Pager *pPager){
46069   const sqlcipher3_io_methods *pMethods = pPager->fd->pMethods;
46070   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
46071 }
46072
46073 /*
46074 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
46075 ** is obtained instead, immediately release it.
46076 */
46077 static int pagerExclusiveLock(Pager *pPager){
46078   int rc;                         /* Return code */
46079
46080   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46081   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46082   if( rc!=SQLCIPHER_OK ){
46083     /* If the attempt to grab the exclusive lock failed, release the 
46084     ** pending lock that may have been obtained instead.  */
46085     pagerUnlockDb(pPager, SHARED_LOCK);
46086   }
46087
46088   return rc;
46089 }
46090
46091 /*
46092 ** Call sqlcipher3WalOpen() to open the WAL handle. If the pager is in 
46093 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
46094 ** lock on the database file and use heap-memory to store the wal-index
46095 ** in. Otherwise, use the normal shared-memory.
46096 */
46097 static int pagerOpenWal(Pager *pPager){
46098   int rc = SQLCIPHER_OK;
46099
46100   assert( pPager->pWal==0 && pPager->tempFile==0 );
46101   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
46102
46103   /* If the pager is already in exclusive-mode, the WAL module will use 
46104   ** heap-memory for the wal-index instead of the VFS shared-memory 
46105   ** implementation. Take the exclusive lock now, before opening the WAL
46106   ** file, to make sure this is safe.
46107   */
46108   if( pPager->exclusiveMode ){
46109     rc = pagerExclusiveLock(pPager);
46110   }
46111
46112   /* Open the connection to the log file. If this operation fails, 
46113   ** (e.g. due to malloc() failure), return an error code.
46114   */
46115   if( rc==SQLCIPHER_OK ){
46116     rc = sqlcipher3WalOpen(pPager->pVfs, 
46117         pPager->fd, pPager->zWal, pPager->exclusiveMode,
46118         pPager->journalSizeLimit, &pPager->pWal
46119     );
46120   }
46121
46122   return rc;
46123 }
46124
46125
46126 /*
46127 ** The caller must be holding a SHARED lock on the database file to call
46128 ** this function.
46129 **
46130 ** If the pager passed as the first argument is open on a real database
46131 ** file (not a temp file or an in-memory database), and the WAL file
46132 ** is not already open, make an attempt to open it now. If successful,
46133 ** return SQLCIPHER_OK. If an error occurs or the VFS used by the pager does 
46134 ** not support the xShmXXX() methods, return an error code. *pbOpen is
46135 ** not modified in either case.
46136 **
46137 ** If the pager is open on a temp-file (or in-memory database), or if
46138 ** the WAL file is already open, set *pbOpen to 1 and return SQLCIPHER_OK
46139 ** without doing anything.
46140 */
46141 SQLCIPHER_PRIVATE int sqlcipher3PagerOpenWal(
46142   Pager *pPager,                  /* Pager object */
46143   int *pbOpen                     /* OUT: Set to true if call is a no-op */
46144 ){
46145   int rc = SQLCIPHER_OK;             /* Return code */
46146
46147   assert( assert_pager_state(pPager) );
46148   assert( pPager->eState==PAGER_OPEN   || pbOpen );
46149   assert( pPager->eState==PAGER_READER || !pbOpen );
46150   assert( pbOpen==0 || *pbOpen==0 );
46151   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
46152
46153   if( !pPager->tempFile && !pPager->pWal ){
46154     if( !sqlcipher3PagerWalSupported(pPager) ) return SQLCIPHER_CANTOPEN;
46155
46156     /* Close any rollback journal previously open */
46157     sqlcipher3OsClose(pPager->jfd);
46158
46159     rc = pagerOpenWal(pPager);
46160     if( rc==SQLCIPHER_OK ){
46161       pPager->journalMode = PAGER_JOURNALMODE_WAL;
46162       pPager->eState = PAGER_OPEN;
46163     }
46164   }else{
46165     *pbOpen = 1;
46166   }
46167
46168   return rc;
46169 }
46170
46171 /*
46172 ** This function is called to close the connection to the log file prior
46173 ** to switching from WAL to rollback mode.
46174 **
46175 ** Before closing the log file, this function attempts to take an 
46176 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
46177 ** error (SQLCIPHER_BUSY) is returned and the log connection is not closed.
46178 ** If successful, the EXCLUSIVE lock is not released before returning.
46179 */
46180 SQLCIPHER_PRIVATE int sqlcipher3PagerCloseWal(Pager *pPager){
46181   int rc = SQLCIPHER_OK;
46182
46183   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
46184
46185   /* If the log file is not already open, but does exist in the file-system,
46186   ** it may need to be checkpointed before the connection can switch to
46187   ** rollback mode. Open it now so this can happen.
46188   */
46189   if( !pPager->pWal ){
46190     int logexists = 0;
46191     rc = pagerLockDb(pPager, SHARED_LOCK);
46192     if( rc==SQLCIPHER_OK ){
46193       rc = sqlcipher3OsAccess(
46194           pPager->pVfs, pPager->zWal, SQLCIPHER_ACCESS_EXISTS, &logexists
46195       );
46196     }
46197     if( rc==SQLCIPHER_OK && logexists ){
46198       rc = pagerOpenWal(pPager);
46199     }
46200   }
46201     
46202   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
46203   ** the database file, the log and log-summary files will be deleted.
46204   */
46205   if( rc==SQLCIPHER_OK && pPager->pWal ){
46206     rc = pagerExclusiveLock(pPager);
46207     if( rc==SQLCIPHER_OK ){
46208       rc = sqlcipher3WalClose(pPager->pWal, pPager->ckptSyncFlags,
46209                            pPager->pageSize, (u8*)pPager->pTmpSpace);
46210       pPager->pWal = 0;
46211     }
46212   }
46213   return rc;
46214 }
46215
46216 /*
46217 ** Unless this is an in-memory or temporary database, clear the pager cache.
46218 */
46219 SQLCIPHER_PRIVATE void sqlcipher3PagerClearCache(Pager *pPager){
46220   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
46221 }
46222
46223 #ifdef SQLCIPHER_HAS_CODEC
46224 /*
46225 ** This function is called by the wal module when writing page content
46226 ** into the log file.
46227 **
46228 ** This function returns a pointer to a buffer containing the encrypted
46229 ** page content. If a malloc fails, this function may return NULL.
46230 */
46231 SQLCIPHER_PRIVATE void *sqlcipher3PagerCodec(PgHdr *pPg){
46232   void *aData = 0;
46233   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
46234   return aData;
46235 }
46236 #endif /* SQLCIPHER_HAS_CODEC */
46237
46238 #endif /* !SQLCIPHER_OMIT_WAL */
46239
46240 #endif /* SQLCIPHER_OMIT_DISKIO */
46241
46242 /* BEGIN CRYPTO */
46243 #ifdef SQLCIPHER_HAS_CODEC
46244 SQLCIPHER_PRIVATE void sqlcipher3pager_get_codec(Pager *pPager, void **ctx) {
46245   *ctx = pPager->pCodec;
46246 }
46247
46248 SQLCIPHER_PRIVATE int sqlcipher3pager_is_mj_pgno(Pager *pPager, Pgno pgno) {
46249   return (PAGER_MJ_PGNO(pPager) == pgno) ? 1 : 0;
46250 }
46251
46252 SQLCIPHER_PRIVATE sqlcipher3_file *sqlcipher3Pager_get_fd(Pager *pPager) {
46253   return (isOpen(pPager->fd)) ? pPager->fd : NULL;
46254 }
46255
46256 SQLCIPHER_PRIVATE void sqlcipher3pager_sqlcipher3PagerSetCodec(
46257   Pager *pPager,
46258   void *(*xCodec)(void*,void*,Pgno,int),
46259   void (*xCodecSizeChng)(void*,int,int),
46260   void (*xCodecFree)(void*),
46261   void *pCodec
46262 ){
46263   sqlcipher3PagerSetCodec(pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec); 
46264 }
46265
46266
46267 #endif
46268 /* END CRYPTO */
46269
46270
46271 /************** End of pager.c ***********************************************/
46272 /************** Begin file wal.c *********************************************/
46273 /*
46274 ** 2010 February 1
46275 **
46276 ** The author disclaims copyright to this source code.  In place of
46277 ** a legal notice, here is a blessing:
46278 **
46279 **    May you do good and not evil.
46280 **    May you find forgiveness for yourself and forgive others.
46281 **    May you share freely, never taking more than you give.
46282 **
46283 *************************************************************************
46284 **
46285 ** This file contains the implementation of a write-ahead log (WAL) used in 
46286 ** "journal_mode=WAL" mode.
46287 **
46288 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
46289 **
46290 ** A WAL file consists of a header followed by zero or more "frames".
46291 ** Each frame records the revised content of a single page from the
46292 ** database file.  All changes to the database are recorded by writing
46293 ** frames into the WAL.  Transactions commit when a frame is written that
46294 ** contains a commit marker.  A single WAL can and usually does record 
46295 ** multiple transactions.  Periodically, the content of the WAL is
46296 ** transferred back into the database file in an operation called a
46297 ** "checkpoint".
46298 **
46299 ** A single WAL file can be used multiple times.  In other words, the
46300 ** WAL can fill up with frames and then be checkpointed and then new
46301 ** frames can overwrite the old ones.  A WAL always grows from beginning
46302 ** toward the end.  Checksums and counters attached to each frame are
46303 ** used to determine which frames within the WAL are valid and which
46304 ** are leftovers from prior checkpoints.
46305 **
46306 ** The WAL header is 32 bytes in size and consists of the following eight
46307 ** big-endian 32-bit unsigned integer values:
46308 **
46309 **     0: Magic number.  0x377f0682 or 0x377f0683
46310 **     4: File format version.  Currently 3007000
46311 **     8: Database page size.  Example: 1024
46312 **    12: Checkpoint sequence number
46313 **    16: Salt-1, random integer incremented with each checkpoint
46314 **    20: Salt-2, a different random integer changing with each ckpt
46315 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
46316 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
46317 **
46318 ** Immediately following the wal-header are zero or more frames. Each
46319 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
46320 ** of page data. The frame-header is six big-endian 32-bit unsigned 
46321 ** integer values, as follows:
46322 **
46323 **     0: Page number.
46324 **     4: For commit records, the size of the database image in pages 
46325 **        after the commit. For all other records, zero.
46326 **     8: Salt-1 (copied from the header)
46327 **    12: Salt-2 (copied from the header)
46328 **    16: Checksum-1.
46329 **    20: Checksum-2.
46330 **
46331 ** A frame is considered valid if and only if the following conditions are
46332 ** true:
46333 **
46334 **    (1) The salt-1 and salt-2 values in the frame-header match
46335 **        salt values in the wal-header
46336 **
46337 **    (2) The checksum values in the final 8 bytes of the frame-header
46338 **        exactly match the checksum computed consecutively on the
46339 **        WAL header and the first 8 bytes and the content of all frames
46340 **        up to and including the current frame.
46341 **
46342 ** The checksum is computed using 32-bit big-endian integers if the
46343 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
46344 ** is computed using little-endian if the magic number is 0x377f0682.
46345 ** The checksum values are always stored in the frame header in a
46346 ** big-endian format regardless of which byte order is used to compute
46347 ** the checksum.  The checksum is computed by interpreting the input as
46348 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
46349 ** algorithm used for the checksum is as follows:
46350 ** 
46351 **   for i from 0 to n-1 step 2:
46352 **     s0 += x[i] + s1;
46353 **     s1 += x[i+1] + s0;
46354 **   endfor
46355 **
46356 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
46357 ** in reverse order (the largest fibonacci weight occurs on the first element
46358 ** of the sequence being summed.)  The s1 value spans all 32-bit 
46359 ** terms of the sequence whereas s0 omits the final term.
46360 **
46361 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
46362 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
46363 ** The VFS.xSync operations serve as write barriers - all writes launched
46364 ** before the xSync must complete before any write that launches after the
46365 ** xSync begins.
46366 **
46367 ** After each checkpoint, the salt-1 value is incremented and the salt-2
46368 ** value is randomized.  This prevents old and new frames in the WAL from
46369 ** being considered valid at the same time and being checkpointing together
46370 ** following a crash.
46371 **
46372 ** READER ALGORITHM
46373 **
46374 ** To read a page from the database (call it page number P), a reader
46375 ** first checks the WAL to see if it contains page P.  If so, then the
46376 ** last valid instance of page P that is a followed by a commit frame
46377 ** or is a commit frame itself becomes the value read.  If the WAL
46378 ** contains no copies of page P that are valid and which are a commit
46379 ** frame or are followed by a commit frame, then page P is read from
46380 ** the database file.
46381 **
46382 ** To start a read transaction, the reader records the index of the last
46383 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
46384 ** for all subsequent read operations.  New transactions can be appended
46385 ** to the WAL, but as long as the reader uses its original mxFrame value
46386 ** and ignores the newly appended content, it will see a consistent snapshot
46387 ** of the database from a single point in time.  This technique allows
46388 ** multiple concurrent readers to view different versions of the database
46389 ** content simultaneously.
46390 **
46391 ** The reader algorithm in the previous paragraphs works correctly, but 
46392 ** because frames for page P can appear anywhere within the WAL, the
46393 ** reader has to scan the entire WAL looking for page P frames.  If the
46394 ** WAL is large (multiple megabytes is typical) that scan can be slow,
46395 ** and read performance suffers.  To overcome this problem, a separate
46396 ** data structure called the wal-index is maintained to expedite the
46397 ** search for frames of a particular page.
46398 ** 
46399 ** WAL-INDEX FORMAT
46400 **
46401 ** Conceptually, the wal-index is shared memory, though VFS implementations
46402 ** might choose to implement the wal-index using a mmapped file.  Because
46403 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
46404 ** on a network filesystem.  All users of the database must be able to
46405 ** share memory.
46406 **
46407 ** The wal-index is transient.  After a crash, the wal-index can (and should
46408 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
46409 ** to either truncate or zero the header of the wal-index when the last
46410 ** connection to it closes.  Because the wal-index is transient, it can
46411 ** use an architecture-specific format; it does not have to be cross-platform.
46412 ** Hence, unlike the database and WAL file formats which store all values
46413 ** as big endian, the wal-index can store multi-byte values in the native
46414 ** byte order of the host computer.
46415 **
46416 ** The purpose of the wal-index is to answer this question quickly:  Given
46417 ** a page number P, return the index of the last frame for page P in the WAL,
46418 ** or return NULL if there are no frames for page P in the WAL.
46419 **
46420 ** The wal-index consists of a header region, followed by an one or
46421 ** more index blocks.  
46422 **
46423 ** The wal-index header contains the total number of frames within the WAL
46424 ** in the the mxFrame field.  
46425 **
46426 ** Each index block except for the first contains information on 
46427 ** HASHTABLE_NPAGE frames. The first index block contains information on
46428 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
46429 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
46430 ** first index block are the same size as all other index blocks in the
46431 ** wal-index.
46432 **
46433 ** Each index block contains two sections, a page-mapping that contains the
46434 ** database page number associated with each wal frame, and a hash-table 
46435 ** that allows readers to query an index block for a specific page number.
46436 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
46437 ** for the first index block) 32-bit page numbers. The first entry in the 
46438 ** first index-block contains the database page number corresponding to the
46439 ** first frame in the WAL file. The first entry in the second index block
46440 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
46441 ** the log, and so on.
46442 **
46443 ** The last index block in a wal-index usually contains less than the full
46444 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
46445 ** depending on the contents of the WAL file. This does not change the
46446 ** allocated size of the page-mapping array - the page-mapping array merely
46447 ** contains unused entries.
46448 **
46449 ** Even without using the hash table, the last frame for page P
46450 ** can be found by scanning the page-mapping sections of each index block
46451 ** starting with the last index block and moving toward the first, and
46452 ** within each index block, starting at the end and moving toward the
46453 ** beginning.  The first entry that equals P corresponds to the frame
46454 ** holding the content for that page.
46455 **
46456 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
46457 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
46458 ** hash table for each page number in the mapping section, so the hash 
46459 ** table is never more than half full.  The expected number of collisions 
46460 ** prior to finding a match is 1.  Each entry of the hash table is an
46461 ** 1-based index of an entry in the mapping section of the same
46462 ** index block.   Let K be the 1-based index of the largest entry in
46463 ** the mapping section.  (For index blocks other than the last, K will
46464 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
46465 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
46466 ** contain a value of 0.
46467 **
46468 ** To look for page P in the hash table, first compute a hash iKey on
46469 ** P as follows:
46470 **
46471 **      iKey = (P * 383) % HASHTABLE_NSLOT
46472 **
46473 ** Then start scanning entries of the hash table, starting with iKey
46474 ** (wrapping around to the beginning when the end of the hash table is
46475 ** reached) until an unused hash slot is found. Let the first unused slot
46476 ** be at index iUnused.  (iUnused might be less than iKey if there was
46477 ** wrap-around.) Because the hash table is never more than half full,
46478 ** the search is guaranteed to eventually hit an unused entry.  Let 
46479 ** iMax be the value between iKey and iUnused, closest to iUnused,
46480 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
46481 ** no hash slot such that aHash[i]==p) then page P is not in the
46482 ** current index block.  Otherwise the iMax-th mapping entry of the
46483 ** current index block corresponds to the last entry that references 
46484 ** page P.
46485 **
46486 ** A hash search begins with the last index block and moves toward the
46487 ** first index block, looking for entries corresponding to page P.  On
46488 ** average, only two or three slots in each index block need to be
46489 ** examined in order to either find the last entry for page P, or to
46490 ** establish that no such entry exists in the block.  Each index block
46491 ** holds over 4000 entries.  So two or three index blocks are sufficient
46492 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
46493 ** comparisons (on average) suffice to either locate a frame in the
46494 ** WAL or to establish that the frame does not exist in the WAL.  This
46495 ** is much faster than scanning the entire 10MB WAL.
46496 **
46497 ** Note that entries are added in order of increasing K.  Hence, one
46498 ** reader might be using some value K0 and a second reader that started
46499 ** at a later time (after additional transactions were added to the WAL
46500 ** and to the wal-index) might be using a different value K1, where K1>K0.
46501 ** Both readers can use the same hash table and mapping section to get
46502 ** the correct result.  There may be entries in the hash table with
46503 ** K>K0 but to the first reader, those entries will appear to be unused
46504 ** slots in the hash table and so the first reader will get an answer as
46505 ** if no values greater than K0 had ever been inserted into the hash table
46506 ** in the first place - which is what reader one wants.  Meanwhile, the
46507 ** second reader using K1 will see additional values that were inserted
46508 ** later, which is exactly what reader two wants.  
46509 **
46510 ** When a rollback occurs, the value of K is decreased. Hash table entries
46511 ** that correspond to frames greater than the new K value are removed
46512 ** from the hash table at this point.
46513 */
46514 #ifndef SQLCIPHER_OMIT_WAL
46515
46516
46517 /*
46518 ** Trace output macros
46519 */
46520 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
46521 SQLCIPHER_PRIVATE int sqlcipher3WalTrace = 0;
46522 # define WALTRACE(X)  if(sqlcipher3WalTrace) sqlcipher3DebugPrintf X
46523 #else
46524 # define WALTRACE(X)
46525 #endif
46526
46527 /*
46528 ** The maximum (and only) versions of the wal and wal-index formats
46529 ** that may be interpreted by this version of SQLite.
46530 **
46531 ** If a client begins recovering a WAL file and finds that (a) the checksum
46532 ** values in the wal-header are correct and (b) the version field is not
46533 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLCIPHER_CANTOPEN.
46534 **
46535 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
46536 ** checksum test is successful) and finds that the version field is not
46537 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
46538 ** returns SQLCIPHER_CANTOPEN.
46539 */
46540 #define WAL_MAX_VERSION      3007000
46541 #define WALINDEX_MAX_VERSION 3007000
46542
46543 /*
46544 ** Indices of various locking bytes.   WAL_NREADER is the number
46545 ** of available reader locks and should be at least 3.
46546 */
46547 #define WAL_WRITE_LOCK         0
46548 #define WAL_ALL_BUT_WRITE      1
46549 #define WAL_CKPT_LOCK          1
46550 #define WAL_RECOVER_LOCK       2
46551 #define WAL_READ_LOCK(I)       (3+(I))
46552 #define WAL_NREADER            (SQLCIPHER_SHM_NLOCK-3)
46553
46554
46555 /* Object declarations */
46556 typedef struct WalIndexHdr WalIndexHdr;
46557 typedef struct WalIterator WalIterator;
46558 typedef struct WalCkptInfo WalCkptInfo;
46559
46560
46561 /*
46562 ** The following object holds a copy of the wal-index header content.
46563 **
46564 ** The actual header in the wal-index consists of two copies of this
46565 ** object.
46566 **
46567 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
46568 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
46569 ** added in 3.7.1 when support for 64K pages was added.  
46570 */
46571 struct WalIndexHdr {
46572   u32 iVersion;                   /* Wal-index version */
46573   u32 unused;                     /* Unused (padding) field */
46574   u32 iChange;                    /* Counter incremented each transaction */
46575   u8 isInit;                      /* 1 when initialized */
46576   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
46577   u16 szPage;                     /* Database page size in bytes. 1==64K */
46578   u32 mxFrame;                    /* Index of last valid frame in the WAL */
46579   u32 nPage;                      /* Size of database in pages */
46580   u32 aFrameCksum[2];             /* Checksum of last frame in log */
46581   u32 aSalt[2];                   /* Two salt values copied from WAL header */
46582   u32 aCksum[2];                  /* Checksum over all prior fields */
46583 };
46584
46585 /*
46586 ** A copy of the following object occurs in the wal-index immediately
46587 ** following the second copy of the WalIndexHdr.  This object stores
46588 ** information used by checkpoint.
46589 **
46590 ** nBackfill is the number of frames in the WAL that have been written
46591 ** back into the database. (We call the act of moving content from WAL to
46592 ** database "backfilling".)  The nBackfill number is never greater than
46593 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
46594 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
46595 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
46596 ** mxFrame back to zero when the WAL is reset.
46597 **
46598 ** There is one entry in aReadMark[] for each reader lock.  If a reader
46599 ** holds read-lock K, then the value in aReadMark[K] is no greater than
46600 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
46601 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
46602 ** a special case; its value is never used and it exists as a place-holder
46603 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
46604 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
46605 ** directly from the database.
46606 **
46607 ** The value of aReadMark[K] may only be changed by a thread that
46608 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
46609 ** aReadMark[K] cannot changed while there is a reader is using that mark
46610 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
46611 **
46612 ** The checkpointer may only transfer frames from WAL to database where
46613 ** the frame numbers are less than or equal to every aReadMark[] that is
46614 ** in use (that is, every aReadMark[j] for which there is a corresponding
46615 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
46616 ** largest value and will increase an unused aReadMark[] to mxFrame if there
46617 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
46618 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
46619 ** in the WAL has been backfilled into the database) then new readers
46620 ** will choose aReadMark[0] which has value 0 and hence such reader will
46621 ** get all their all content directly from the database file and ignore 
46622 ** the WAL.
46623 **
46624 ** Writers normally append new frames to the end of the WAL.  However,
46625 ** if nBackfill equals mxFrame (meaning that all WAL content has been
46626 ** written back into the database) and if no readers are using the WAL
46627 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
46628 ** the writer will first "reset" the WAL back to the beginning and start
46629 ** writing new content beginning at frame 1.
46630 **
46631 ** We assume that 32-bit loads are atomic and so no locks are needed in
46632 ** order to read from any aReadMark[] entries.
46633 */
46634 struct WalCkptInfo {
46635   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
46636   u32 aReadMark[WAL_NREADER];     /* Reader marks */
46637 };
46638 #define READMARK_NOT_USED  0xffffffff
46639
46640
46641 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
46642 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
46643 ** only support mandatory file-locks, we do not read or write data
46644 ** from the region of the file on which locks are applied.
46645 */
46646 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
46647 #define WALINDEX_LOCK_RESERVED 16
46648 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
46649
46650 /* Size of header before each frame in wal */
46651 #define WAL_FRAME_HDRSIZE 24
46652
46653 /* Size of write ahead log header, including checksum. */
46654 /* #define WAL_HDRSIZE 24 */
46655 #define WAL_HDRSIZE 32
46656
46657 /* WAL magic value. Either this value, or the same value with the least
46658 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
46659 ** big-endian format in the first 4 bytes of a WAL file.
46660 **
46661 ** If the LSB is set, then the checksums for each frame within the WAL
46662 ** file are calculated by treating all data as an array of 32-bit 
46663 ** big-endian words. Otherwise, they are calculated by interpreting 
46664 ** all data as 32-bit little-endian words.
46665 */
46666 #define WAL_MAGIC 0x377f0682
46667
46668 /*
46669 ** Return the offset of frame iFrame in the write-ahead log file, 
46670 ** assuming a database page size of szPage bytes. The offset returned
46671 ** is to the start of the write-ahead log frame-header.
46672 */
46673 #define walFrameOffset(iFrame, szPage) (                               \
46674   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
46675 )
46676
46677 /*
46678 ** An open write-ahead log file is represented by an instance of the
46679 ** following object.
46680 */
46681 struct Wal {
46682   sqlcipher3_vfs *pVfs;         /* The VFS used to create pDbFd */
46683   sqlcipher3_file *pDbFd;       /* File handle for the database file */
46684   sqlcipher3_file *pWalFd;      /* File handle for WAL file */
46685   u32 iCallback;             /* Value to pass to log callback (or 0) */
46686   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
46687   int nWiData;               /* Size of array apWiData */
46688   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
46689   u32 szPage;                /* Database page size */
46690   i16 readLock;              /* Which read lock is being held.  -1 for none */
46691   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
46692   u8 writeLock;              /* True if in a write transaction */
46693   u8 ckptLock;               /* True if holding a checkpoint lock */
46694   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
46695   WalIndexHdr hdr;           /* Wal-index header for current transaction */
46696   const char *zWalName;      /* Name of WAL file */
46697   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
46698 #ifdef SQLCIPHER_DEBUG
46699   u8 lockError;              /* True if a locking error has occurred */
46700 #endif
46701 };
46702
46703 /*
46704 ** Candidate values for Wal.exclusiveMode.
46705 */
46706 #define WAL_NORMAL_MODE     0
46707 #define WAL_EXCLUSIVE_MODE  1     
46708 #define WAL_HEAPMEMORY_MODE 2
46709
46710 /*
46711 ** Possible values for WAL.readOnly
46712 */
46713 #define WAL_RDWR        0    /* Normal read/write connection */
46714 #define WAL_RDONLY      1    /* The WAL file is readonly */
46715 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
46716
46717 /*
46718 ** Each page of the wal-index mapping contains a hash-table made up of
46719 ** an array of HASHTABLE_NSLOT elements of the following type.
46720 */
46721 typedef u16 ht_slot;
46722
46723 /*
46724 ** This structure is used to implement an iterator that loops through
46725 ** all frames in the WAL in database page order. Where two or more frames
46726 ** correspond to the same database page, the iterator visits only the 
46727 ** frame most recently written to the WAL (in other words, the frame with
46728 ** the largest index).
46729 **
46730 ** The internals of this structure are only accessed by:
46731 **
46732 **   walIteratorInit() - Create a new iterator,
46733 **   walIteratorNext() - Step an iterator,
46734 **   walIteratorFree() - Free an iterator.
46735 **
46736 ** This functionality is used by the checkpoint code (see walCheckpoint()).
46737 */
46738 struct WalIterator {
46739   int iPrior;                     /* Last result returned from the iterator */
46740   int nSegment;                   /* Number of entries in aSegment[] */
46741   struct WalSegment {
46742     int iNext;                    /* Next slot in aIndex[] not yet returned */
46743     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
46744     u32 *aPgno;                   /* Array of page numbers. */
46745     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
46746     int iZero;                    /* Frame number associated with aPgno[0] */
46747   } aSegment[1];                  /* One for every 32KB page in the wal-index */
46748 };
46749
46750 /*
46751 ** Define the parameters of the hash tables in the wal-index file. There
46752 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
46753 ** wal-index.
46754 **
46755 ** Changing any of these constants will alter the wal-index format and
46756 ** create incompatibilities.
46757 */
46758 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
46759 #define HASHTABLE_HASH_1     383                  /* Should be prime */
46760 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
46761
46762 /* 
46763 ** The block of page numbers associated with the first hash-table in a
46764 ** wal-index is smaller than usual. This is so that there is a complete
46765 ** hash-table on each aligned 32KB page of the wal-index.
46766 */
46767 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
46768
46769 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
46770 #define WALINDEX_PGSZ   (                                         \
46771     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
46772 )
46773
46774 /*
46775 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
46776 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
46777 ** numbered from zero.
46778 **
46779 ** If this call is successful, *ppPage is set to point to the wal-index
46780 ** page and SQLCIPHER_OK is returned. If an error (an OOM or VFS error) occurs,
46781 ** then an SQLite error code is returned and *ppPage is set to 0.
46782 */
46783 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
46784   int rc = SQLCIPHER_OK;
46785
46786   /* Enlarge the pWal->apWiData[] array if required */
46787   if( pWal->nWiData<=iPage ){
46788     int nByte = sizeof(u32*)*(iPage+1);
46789     volatile u32 **apNew;
46790     apNew = (volatile u32 **)sqlcipher3_realloc((void *)pWal->apWiData, nByte);
46791     if( !apNew ){
46792       *ppPage = 0;
46793       return SQLCIPHER_NOMEM;
46794     }
46795     memset((void*)&apNew[pWal->nWiData], 0,
46796            sizeof(u32*)*(iPage+1-pWal->nWiData));
46797     pWal->apWiData = apNew;
46798     pWal->nWiData = iPage+1;
46799   }
46800
46801   /* Request a pointer to the required page from the VFS */
46802   if( pWal->apWiData[iPage]==0 ){
46803     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46804       pWal->apWiData[iPage] = (u32 volatile *)sqlcipher3MallocZero(WALINDEX_PGSZ);
46805       if( !pWal->apWiData[iPage] ) rc = SQLCIPHER_NOMEM;
46806     }else{
46807       rc = sqlcipher3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
46808           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
46809       );
46810       if( rc==SQLCIPHER_READONLY ){
46811         pWal->readOnly |= WAL_SHM_RDONLY;
46812         rc = SQLCIPHER_OK;
46813       }
46814     }
46815   }
46816
46817   *ppPage = pWal->apWiData[iPage];
46818   assert( iPage==0 || *ppPage || rc!=SQLCIPHER_OK );
46819   return rc;
46820 }
46821
46822 /*
46823 ** Return a pointer to the WalCkptInfo structure in the wal-index.
46824 */
46825 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
46826   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46827   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
46828 }
46829
46830 /*
46831 ** Return a pointer to the WalIndexHdr structure in the wal-index.
46832 */
46833 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
46834   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46835   return (volatile WalIndexHdr*)pWal->apWiData[0];
46836 }
46837
46838 /*
46839 ** The argument to this macro must be of type u32. On a little-endian
46840 ** architecture, it returns the u32 value that results from interpreting
46841 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
46842 ** returns the value that would be produced by intepreting the 4 bytes
46843 ** of the input value as a little-endian integer.
46844 */
46845 #define BYTESWAP32(x) ( \
46846     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
46847   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
46848 )
46849
46850 /*
46851 ** Generate or extend an 8 byte checksum based on the data in 
46852 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
46853 ** initial values of 0 and 0 if aIn==NULL).
46854 **
46855 ** The checksum is written back into aOut[] before returning.
46856 **
46857 ** nByte must be a positive multiple of 8.
46858 */
46859 static void walChecksumBytes(
46860   int nativeCksum, /* True for native byte-order, false for non-native */
46861   u8 *a,           /* Content to be checksummed */
46862   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
46863   const u32 *aIn,  /* Initial checksum value input */
46864   u32 *aOut        /* OUT: Final checksum value output */
46865 ){
46866   u32 s1, s2;
46867   u32 *aData = (u32 *)a;
46868   u32 *aEnd = (u32 *)&a[nByte];
46869
46870   if( aIn ){
46871     s1 = aIn[0];
46872     s2 = aIn[1];
46873   }else{
46874     s1 = s2 = 0;
46875   }
46876
46877   assert( nByte>=8 );
46878   assert( (nByte&0x00000007)==0 );
46879
46880   if( nativeCksum ){
46881     do {
46882       s1 += *aData++ + s2;
46883       s2 += *aData++ + s1;
46884     }while( aData<aEnd );
46885   }else{
46886     do {
46887       s1 += BYTESWAP32(aData[0]) + s2;
46888       s2 += BYTESWAP32(aData[1]) + s1;
46889       aData += 2;
46890     }while( aData<aEnd );
46891   }
46892
46893   aOut[0] = s1;
46894   aOut[1] = s2;
46895 }
46896
46897 static void walShmBarrier(Wal *pWal){
46898   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
46899     sqlcipher3OsShmBarrier(pWal->pDbFd);
46900   }
46901 }
46902
46903 /*
46904 ** Write the header information in pWal->hdr into the wal-index.
46905 **
46906 ** The checksum on pWal->hdr is updated before it is written.
46907 */
46908 static void walIndexWriteHdr(Wal *pWal){
46909   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
46910   const int nCksum = offsetof(WalIndexHdr, aCksum);
46911
46912   assert( pWal->writeLock );
46913   pWal->hdr.isInit = 1;
46914   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
46915   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
46916   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46917   walShmBarrier(pWal);
46918   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46919 }
46920
46921 /*
46922 ** This function encodes a single frame header and writes it to a buffer
46923 ** supplied by the caller. A frame-header is made up of a series of 
46924 ** 4-byte big-endian integers, as follows:
46925 **
46926 **     0: Page number.
46927 **     4: For commit records, the size of the database image in pages 
46928 **        after the commit. For all other records, zero.
46929 **     8: Salt-1 (copied from the wal-header)
46930 **    12: Salt-2 (copied from the wal-header)
46931 **    16: Checksum-1.
46932 **    20: Checksum-2.
46933 */
46934 static void walEncodeFrame(
46935   Wal *pWal,                      /* The write-ahead log */
46936   u32 iPage,                      /* Database page number for frame */
46937   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46938   u8 *aData,                      /* Pointer to page data */
46939   u8 *aFrame                      /* OUT: Write encoded frame here */
46940 ){
46941   int nativeCksum;                /* True for native byte-order checksums */
46942   u32 *aCksum = pWal->hdr.aFrameCksum;
46943   assert( WAL_FRAME_HDRSIZE==24 );
46944   sqlcipher3Put4byte(&aFrame[0], iPage);
46945   sqlcipher3Put4byte(&aFrame[4], nTruncate);
46946   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46947
46948   nativeCksum = (pWal->hdr.bigEndCksum==SQLCIPHER_BIGENDIAN);
46949   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46950   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46951
46952   sqlcipher3Put4byte(&aFrame[16], aCksum[0]);
46953   sqlcipher3Put4byte(&aFrame[20], aCksum[1]);
46954 }
46955
46956 /*
46957 ** Check to see if the frame with header in aFrame[] and content
46958 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
46959 ** *pnTruncate and return true.  Return if the frame is not valid.
46960 */
46961 static int walDecodeFrame(
46962   Wal *pWal,                      /* The write-ahead log */
46963   u32 *piPage,                    /* OUT: Database page number for frame */
46964   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46965   u8 *aData,                      /* Pointer to page data (for checksum) */
46966   u8 *aFrame                      /* Frame data */
46967 ){
46968   int nativeCksum;                /* True for native byte-order checksums */
46969   u32 *aCksum = pWal->hdr.aFrameCksum;
46970   u32 pgno;                       /* Page number of the frame */
46971   assert( WAL_FRAME_HDRSIZE==24 );
46972
46973   /* A frame is only valid if the salt values in the frame-header
46974   ** match the salt values in the wal-header. 
46975   */
46976   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46977     return 0;
46978   }
46979
46980   /* A frame is only valid if the page number is creater than zero.
46981   */
46982   pgno = sqlcipher3Get4byte(&aFrame[0]);
46983   if( pgno==0 ){
46984     return 0;
46985   }
46986
46987   /* A frame is only valid if a checksum of the WAL header,
46988   ** all prior frams, the first 16 bytes of this frame-header, 
46989   ** and the frame-data matches the checksum in the last 8 
46990   ** bytes of this frame-header.
46991   */
46992   nativeCksum = (pWal->hdr.bigEndCksum==SQLCIPHER_BIGENDIAN);
46993   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46994   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46995   if( aCksum[0]!=sqlcipher3Get4byte(&aFrame[16]) 
46996    || aCksum[1]!=sqlcipher3Get4byte(&aFrame[20]) 
46997   ){
46998     /* Checksum failed. */
46999     return 0;
47000   }
47001
47002   /* If we reach this point, the frame is valid.  Return the page number
47003   ** and the new database size.
47004   */
47005   *piPage = pgno;
47006   *pnTruncate = sqlcipher3Get4byte(&aFrame[4]);
47007   return 1;
47008 }
47009
47010
47011 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
47012 /*
47013 ** Names of locks.  This routine is used to provide debugging output and is not
47014 ** a part of an ordinary build.
47015 */
47016 static const char *walLockName(int lockIdx){
47017   if( lockIdx==WAL_WRITE_LOCK ){
47018     return "WRITE-LOCK";
47019   }else if( lockIdx==WAL_CKPT_LOCK ){
47020     return "CKPT-LOCK";
47021   }else if( lockIdx==WAL_RECOVER_LOCK ){
47022     return "RECOVER-LOCK";
47023   }else{
47024     static char zName[15];
47025     sqlcipher3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
47026                      lockIdx-WAL_READ_LOCK(0));
47027     return zName;
47028   }
47029 }
47030 #endif /*defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG) */
47031     
47032
47033 /*
47034 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
47035 ** A lock cannot be moved directly between shared and exclusive - it must go
47036 ** through the unlocked state first.
47037 **
47038 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
47039 */
47040 static int walLockShared(Wal *pWal, int lockIdx){
47041   int rc;
47042   if( pWal->exclusiveMode ) return SQLCIPHER_OK;
47043   rc = sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, 1,
47044                         SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_SHARED);
47045   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
47046             walLockName(lockIdx), rc ? "failed" : "ok"));
47047   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY); )
47048   return rc;
47049 }
47050 static void walUnlockShared(Wal *pWal, int lockIdx){
47051   if( pWal->exclusiveMode ) return;
47052   (void)sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, 1,
47053                          SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_SHARED);
47054   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
47055 }
47056 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
47057   int rc;
47058   if( pWal->exclusiveMode ) return SQLCIPHER_OK;
47059   rc = sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, n,
47060                         SQLCIPHER_SHM_LOCK | SQLCIPHER_SHM_EXCLUSIVE);
47061   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
47062             walLockName(lockIdx), n, rc ? "failed" : "ok"));
47063   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY); )
47064   return rc;
47065 }
47066 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
47067   if( pWal->exclusiveMode ) return;
47068   (void)sqlcipher3OsShmLock(pWal->pDbFd, lockIdx, n,
47069                          SQLCIPHER_SHM_UNLOCK | SQLCIPHER_SHM_EXCLUSIVE);
47070   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
47071              walLockName(lockIdx), n));
47072 }
47073
47074 /*
47075 ** Compute a hash on a page number.  The resulting hash value must land
47076 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
47077 ** the hash to the next value in the event of a collision.
47078 */
47079 static int walHash(u32 iPage){
47080   assert( iPage>0 );
47081   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
47082   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
47083 }
47084 static int walNextHash(int iPriorHash){
47085   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
47086 }
47087
47088 /* 
47089 ** Return pointers to the hash table and page number array stored on
47090 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
47091 ** numbered starting from 0.
47092 **
47093 ** Set output variable *paHash to point to the start of the hash table
47094 ** in the wal-index file. Set *piZero to one less than the frame 
47095 ** number of the first frame indexed by this hash table. If a
47096 ** slot in the hash table is set to N, it refers to frame number 
47097 ** (*piZero+N) in the log.
47098 **
47099 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
47100 ** first frame indexed by the hash table, frame (*piZero+1).
47101 */
47102 static int walHashGet(
47103   Wal *pWal,                      /* WAL handle */
47104   int iHash,                      /* Find the iHash'th table */
47105   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
47106   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
47107   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
47108 ){
47109   int rc;                         /* Return code */
47110   volatile u32 *aPgno;
47111
47112   rc = walIndexPage(pWal, iHash, &aPgno);
47113   assert( rc==SQLCIPHER_OK || iHash>0 );
47114
47115   if( rc==SQLCIPHER_OK ){
47116     u32 iZero;
47117     volatile ht_slot *aHash;
47118
47119     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
47120     if( iHash==0 ){
47121       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
47122       iZero = 0;
47123     }else{
47124       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
47125     }
47126   
47127     *paPgno = &aPgno[-1];
47128     *paHash = aHash;
47129     *piZero = iZero;
47130   }
47131   return rc;
47132 }
47133
47134 /*
47135 ** Return the number of the wal-index page that contains the hash-table
47136 ** and page-number array that contain entries corresponding to WAL frame
47137 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
47138 ** are numbered starting from 0.
47139 */
47140 static int walFramePage(u32 iFrame){
47141   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
47142   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
47143        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
47144        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
47145        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
47146        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
47147   );
47148   return iHash;
47149 }
47150
47151 /*
47152 ** Return the page number associated with frame iFrame in this WAL.
47153 */
47154 static u32 walFramePgno(Wal *pWal, u32 iFrame){
47155   int iHash = walFramePage(iFrame);
47156   if( iHash==0 ){
47157     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
47158   }
47159   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
47160 }
47161
47162 /*
47163 ** Remove entries from the hash table that point to WAL slots greater
47164 ** than pWal->hdr.mxFrame.
47165 **
47166 ** This function is called whenever pWal->hdr.mxFrame is decreased due
47167 ** to a rollback or savepoint.
47168 **
47169 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
47170 ** updated.  Any later hash tables will be automatically cleared when
47171 ** pWal->hdr.mxFrame advances to the point where those hash tables are
47172 ** actually needed.
47173 */
47174 static void walCleanupHash(Wal *pWal){
47175   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
47176   volatile u32 *aPgno = 0;        /* Page number array for hash table */
47177   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
47178   int iLimit = 0;                 /* Zero values greater than this */
47179   int nByte;                      /* Number of bytes to zero in aPgno[] */
47180   int i;                          /* Used to iterate through aHash[] */
47181
47182   assert( pWal->writeLock );
47183   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
47184   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
47185   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
47186
47187   if( pWal->hdr.mxFrame==0 ) return;
47188
47189   /* Obtain pointers to the hash-table and page-number array containing 
47190   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
47191   ** that the page said hash-table and array reside on is already mapped.
47192   */
47193   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
47194   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
47195   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
47196
47197   /* Zero all hash-table entries that correspond to frame numbers greater
47198   ** than pWal->hdr.mxFrame.
47199   */
47200   iLimit = pWal->hdr.mxFrame - iZero;
47201   assert( iLimit>0 );
47202   for(i=0; i<HASHTABLE_NSLOT; i++){
47203     if( aHash[i]>iLimit ){
47204       aHash[i] = 0;
47205     }
47206   }
47207   
47208   /* Zero the entries in the aPgno array that correspond to frames with
47209   ** frame numbers greater than pWal->hdr.mxFrame. 
47210   */
47211   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
47212   memset((void *)&aPgno[iLimit+1], 0, nByte);
47213
47214 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
47215   /* Verify that the every entry in the mapping region is still reachable
47216   ** via the hash table even after the cleanup.
47217   */
47218   if( iLimit ){
47219     int i;           /* Loop counter */
47220     int iKey;        /* Hash key */
47221     for(i=1; i<=iLimit; i++){
47222       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47223         if( aHash[iKey]==i ) break;
47224       }
47225       assert( aHash[iKey]==i );
47226     }
47227   }
47228 #endif /* SQLCIPHER_ENABLE_EXPENSIVE_ASSERT */
47229 }
47230
47231
47232 /*
47233 ** Set an entry in the wal-index that will map database page number
47234 ** pPage into WAL frame iFrame.
47235 */
47236 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
47237   int rc;                         /* Return code */
47238   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
47239   volatile u32 *aPgno = 0;        /* Page number array */
47240   volatile ht_slot *aHash = 0;    /* Hash table */
47241
47242   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
47243
47244   /* Assuming the wal-index file was successfully mapped, populate the
47245   ** page number array and hash table entry.
47246   */
47247   if( rc==SQLCIPHER_OK ){
47248     int iKey;                     /* Hash table key */
47249     int idx;                      /* Value to write to hash-table slot */
47250     int nCollide;                 /* Number of hash collisions */
47251
47252     idx = iFrame - iZero;
47253     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
47254     
47255     /* If this is the first entry to be added to this hash-table, zero the
47256     ** entire hash table and aPgno[] array before proceding. 
47257     */
47258     if( idx==1 ){
47259       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
47260       memset((void*)&aPgno[1], 0, nByte);
47261     }
47262
47263     /* If the entry in aPgno[] is already set, then the previous writer
47264     ** must have exited unexpectedly in the middle of a transaction (after
47265     ** writing one or more dirty pages to the WAL to free up memory). 
47266     ** Remove the remnants of that writers uncommitted transaction from 
47267     ** the hash-table before writing any new entries.
47268     */
47269     if( aPgno[idx] ){
47270       walCleanupHash(pWal);
47271       assert( !aPgno[idx] );
47272     }
47273
47274     /* Write the aPgno[] array entry and the hash-table slot. */
47275     nCollide = idx;
47276     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
47277       if( (nCollide--)==0 ) return SQLCIPHER_CORRUPT_BKPT;
47278     }
47279     aPgno[idx] = iPage;
47280     aHash[iKey] = (ht_slot)idx;
47281
47282 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
47283     /* Verify that the number of entries in the hash table exactly equals
47284     ** the number of entries in the mapping region.
47285     */
47286     {
47287       int i;           /* Loop counter */
47288       int nEntry = 0;  /* Number of entries in the hash table */
47289       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
47290       assert( nEntry==idx );
47291     }
47292
47293     /* Verify that the every entry in the mapping region is reachable
47294     ** via the hash table.  This turns out to be a really, really expensive
47295     ** thing to check, so only do this occasionally - not on every
47296     ** iteration.
47297     */
47298     if( (idx&0x3ff)==0 ){
47299       int i;           /* Loop counter */
47300       for(i=1; i<=idx; i++){
47301         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47302           if( aHash[iKey]==i ) break;
47303         }
47304         assert( aHash[iKey]==i );
47305       }
47306     }
47307 #endif /* SQLCIPHER_ENABLE_EXPENSIVE_ASSERT */
47308   }
47309
47310
47311   return rc;
47312 }
47313
47314
47315 /*
47316 ** Recover the wal-index by reading the write-ahead log file. 
47317 **
47318 ** This routine first tries to establish an exclusive lock on the
47319 ** wal-index to prevent other threads/processes from doing anything
47320 ** with the WAL or wal-index while recovery is running.  The
47321 ** WAL_RECOVER_LOCK is also held so that other threads will know
47322 ** that this thread is running recovery.  If unable to establish
47323 ** the necessary locks, this routine returns SQLCIPHER_BUSY.
47324 */
47325 static int walIndexRecover(Wal *pWal){
47326   int rc;                         /* Return Code */
47327   i64 nSize;                      /* Size of log file */
47328   u32 aFrameCksum[2] = {0, 0};
47329   int iLock;                      /* Lock offset to lock for checkpoint */
47330   int nLock;                      /* Number of locks to hold */
47331
47332   /* Obtain an exclusive lock on all byte in the locking range not already
47333   ** locked by the caller. The caller is guaranteed to have locked the
47334   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
47335   ** If successful, the same bytes that are locked here are unlocked before
47336   ** this function returns.
47337   */
47338   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
47339   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
47340   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
47341   assert( pWal->writeLock );
47342   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
47343   nLock = SQLCIPHER_SHM_NLOCK - iLock;
47344   rc = walLockExclusive(pWal, iLock, nLock);
47345   if( rc ){
47346     return rc;
47347   }
47348   WALTRACE(("WAL%p: recovery begin...\n", pWal));
47349
47350   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47351
47352   rc = sqlcipher3OsFileSize(pWal->pWalFd, &nSize);
47353   if( rc!=SQLCIPHER_OK ){
47354     goto recovery_error;
47355   }
47356
47357   if( nSize>WAL_HDRSIZE ){
47358     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
47359     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
47360     int szFrame;                  /* Number of bytes in buffer aFrame[] */
47361     u8 *aData;                    /* Pointer to data part of aFrame buffer */
47362     int iFrame;                   /* Index of last frame read */
47363     i64 iOffset;                  /* Next offset to read from log file */
47364     int szPage;                   /* Page size according to the log */
47365     u32 magic;                    /* Magic value read from WAL header */
47366     u32 version;                  /* Magic value read from WAL header */
47367
47368     /* Read in the WAL header. */
47369     rc = sqlcipher3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
47370     if( rc!=SQLCIPHER_OK ){
47371       goto recovery_error;
47372     }
47373
47374     /* If the database page size is not a power of two, or is greater than
47375     ** SQLCIPHER_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
47376     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
47377     ** WAL file.
47378     */
47379     magic = sqlcipher3Get4byte(&aBuf[0]);
47380     szPage = sqlcipher3Get4byte(&aBuf[8]);
47381     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
47382      || szPage&(szPage-1) 
47383      || szPage>SQLCIPHER_MAX_PAGE_SIZE 
47384      || szPage<512 
47385     ){
47386       goto finished;
47387     }
47388     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
47389     pWal->szPage = szPage;
47390     pWal->nCkpt = sqlcipher3Get4byte(&aBuf[12]);
47391     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
47392
47393     /* Verify that the WAL header checksum is correct */
47394     walChecksumBytes(pWal->hdr.bigEndCksum==SQLCIPHER_BIGENDIAN, 
47395         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
47396     );
47397     if( pWal->hdr.aFrameCksum[0]!=sqlcipher3Get4byte(&aBuf[24])
47398      || pWal->hdr.aFrameCksum[1]!=sqlcipher3Get4byte(&aBuf[28])
47399     ){
47400       goto finished;
47401     }
47402
47403     /* Verify that the version number on the WAL format is one that
47404     ** are able to understand */
47405     version = sqlcipher3Get4byte(&aBuf[4]);
47406     if( version!=WAL_MAX_VERSION ){
47407       rc = SQLCIPHER_CANTOPEN_BKPT;
47408       goto finished;
47409     }
47410
47411     /* Malloc a buffer to read frames into. */
47412     szFrame = szPage + WAL_FRAME_HDRSIZE;
47413     aFrame = (u8 *)sqlcipher3_malloc(szFrame);
47414     if( !aFrame ){
47415       rc = SQLCIPHER_NOMEM;
47416       goto recovery_error;
47417     }
47418     aData = &aFrame[WAL_FRAME_HDRSIZE];
47419
47420     /* Read all frames from the log file. */
47421     iFrame = 0;
47422     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
47423       u32 pgno;                   /* Database page number for frame */
47424       u32 nTruncate;              /* dbsize field from frame header */
47425       int isValid;                /* True if this frame is valid */
47426
47427       /* Read and decode the next log frame. */
47428       rc = sqlcipher3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
47429       if( rc!=SQLCIPHER_OK ) break;
47430       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
47431       if( !isValid ) break;
47432       rc = walIndexAppend(pWal, ++iFrame, pgno);
47433       if( rc!=SQLCIPHER_OK ) break;
47434
47435       /* If nTruncate is non-zero, this is a commit record. */
47436       if( nTruncate ){
47437         pWal->hdr.mxFrame = iFrame;
47438         pWal->hdr.nPage = nTruncate;
47439         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47440         testcase( szPage<=32768 );
47441         testcase( szPage>=65536 );
47442         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
47443         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
47444       }
47445     }
47446
47447     sqlcipher3_free(aFrame);
47448   }
47449
47450 finished:
47451   if( rc==SQLCIPHER_OK ){
47452     volatile WalCkptInfo *pInfo;
47453     int i;
47454     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
47455     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
47456     walIndexWriteHdr(pWal);
47457
47458     /* Reset the checkpoint-header. This is safe because this thread is 
47459     ** currently holding locks that exclude all other readers, writers and
47460     ** checkpointers.
47461     */
47462     pInfo = walCkptInfo(pWal);
47463     pInfo->nBackfill = 0;
47464     pInfo->aReadMark[0] = 0;
47465     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47466
47467     /* If more than one frame was recovered from the log file, report an
47468     ** event via sqlcipher3_log(). This is to help with identifying performance
47469     ** problems caused by applications routinely shutting down without
47470     ** checkpointing the log file.
47471     */
47472     if( pWal->hdr.nPage ){
47473       sqlcipher3_log(SQLCIPHER_OK, "Recovered %d frames from WAL file %s",
47474           pWal->hdr.nPage, pWal->zWalName
47475       );
47476     }
47477   }
47478
47479 recovery_error:
47480   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
47481   walUnlockExclusive(pWal, iLock, nLock);
47482   return rc;
47483 }
47484
47485 /*
47486 ** Close an open wal-index.
47487 */
47488 static void walIndexClose(Wal *pWal, int isDelete){
47489   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47490     int i;
47491     for(i=0; i<pWal->nWiData; i++){
47492       sqlcipher3_free((void *)pWal->apWiData[i]);
47493       pWal->apWiData[i] = 0;
47494     }
47495   }else{
47496     sqlcipher3OsShmUnmap(pWal->pDbFd, isDelete);
47497   }
47498 }
47499
47500 /* 
47501 ** Open a connection to the WAL file zWalName. The database file must 
47502 ** already be opened on connection pDbFd. The buffer that zWalName points
47503 ** to must remain valid for the lifetime of the returned Wal* handle.
47504 **
47505 ** A SHARED lock should be held on the database file when this function
47506 ** is called. The purpose of this SHARED lock is to prevent any other
47507 ** client from unlinking the WAL or wal-index file. If another process
47508 ** were to do this just after this client opened one of these files, the
47509 ** system would be badly broken.
47510 **
47511 ** If the log file is successfully opened, SQLCIPHER_OK is returned and 
47512 ** *ppWal is set to point to a new WAL handle. If an error occurs,
47513 ** an SQLite error code is returned and *ppWal is left unmodified.
47514 */
47515 SQLCIPHER_PRIVATE int sqlcipher3WalOpen(
47516   sqlcipher3_vfs *pVfs,              /* vfs module to open wal and wal-index */
47517   sqlcipher3_file *pDbFd,            /* The open database file */
47518   const char *zWalName,           /* Name of the WAL file */
47519   int bNoShm,                     /* True to run in heap-memory mode */
47520   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
47521   Wal **ppWal                     /* OUT: Allocated Wal handle */
47522 ){
47523   int rc;                         /* Return Code */
47524   Wal *pRet;                      /* Object to allocate and return */
47525   int flags;                      /* Flags passed to OsOpen() */
47526
47527   assert( zWalName && zWalName[0] );
47528   assert( pDbFd );
47529
47530   /* In the amalgamation, the os_unix.c and os_win.c source files come before
47531   ** this source file.  Verify that the #defines of the locking byte offsets
47532   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
47533   */
47534 #ifdef WIN_SHM_BASE
47535   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
47536 #endif
47537 #ifdef UNIX_SHM_BASE
47538   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
47539 #endif
47540
47541
47542   /* Allocate an instance of struct Wal to return. */
47543   *ppWal = 0;
47544   pRet = (Wal*)sqlcipher3MallocZero(sizeof(Wal) + pVfs->szOsFile);
47545   if( !pRet ){
47546     return SQLCIPHER_NOMEM;
47547   }
47548
47549   pRet->pVfs = pVfs;
47550   pRet->pWalFd = (sqlcipher3_file *)&pRet[1];
47551   pRet->pDbFd = pDbFd;
47552   pRet->readLock = -1;
47553   pRet->mxWalSize = mxWalSize;
47554   pRet->zWalName = zWalName;
47555   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
47556
47557   /* Open file handle on the write-ahead log file. */
47558   flags = (SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE|SQLCIPHER_OPEN_WAL);
47559   rc = sqlcipher3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
47560   if( rc==SQLCIPHER_OK && flags&SQLCIPHER_OPEN_READONLY ){
47561     pRet->readOnly = WAL_RDONLY;
47562   }
47563
47564   if( rc!=SQLCIPHER_OK ){
47565     walIndexClose(pRet, 0);
47566     sqlcipher3OsClose(pRet->pWalFd);
47567     sqlcipher3_free(pRet);
47568   }else{
47569     *ppWal = pRet;
47570     WALTRACE(("WAL%d: opened\n", pRet));
47571   }
47572   return rc;
47573 }
47574
47575 /*
47576 ** Change the size to which the WAL file is trucated on each reset.
47577 */
47578 SQLCIPHER_PRIVATE void sqlcipher3WalLimit(Wal *pWal, i64 iLimit){
47579   if( pWal ) pWal->mxWalSize = iLimit;
47580 }
47581
47582 /*
47583 ** Find the smallest page number out of all pages held in the WAL that
47584 ** has not been returned by any prior invocation of this method on the
47585 ** same WalIterator object.   Write into *piFrame the frame index where
47586 ** that page was last written into the WAL.  Write into *piPage the page
47587 ** number.
47588 **
47589 ** Return 0 on success.  If there are no pages in the WAL with a page
47590 ** number larger than *piPage, then return 1.
47591 */
47592 static int walIteratorNext(
47593   WalIterator *p,               /* Iterator */
47594   u32 *piPage,                  /* OUT: The page number of the next page */
47595   u32 *piFrame                  /* OUT: Wal frame index of next page */
47596 ){
47597   u32 iMin;                     /* Result pgno must be greater than iMin */
47598   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
47599   int i;                        /* For looping through segments */
47600
47601   iMin = p->iPrior;
47602   assert( iMin<0xffffffff );
47603   for(i=p->nSegment-1; i>=0; i--){
47604     struct WalSegment *pSegment = &p->aSegment[i];
47605     while( pSegment->iNext<pSegment->nEntry ){
47606       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
47607       if( iPg>iMin ){
47608         if( iPg<iRet ){
47609           iRet = iPg;
47610           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
47611         }
47612         break;
47613       }
47614       pSegment->iNext++;
47615     }
47616   }
47617
47618   *piPage = p->iPrior = iRet;
47619   return (iRet==0xFFFFFFFF);
47620 }
47621
47622 /*
47623 ** This function merges two sorted lists into a single sorted list.
47624 **
47625 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
47626 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
47627 ** is guaranteed for all J<K:
47628 **
47629 **        aContent[aLeft[J]] < aContent[aLeft[K]]
47630 **        aContent[aRight[J]] < aContent[aRight[K]]
47631 **
47632 ** This routine overwrites aRight[] with a new (probably longer) sequence
47633 ** of indices such that the aRight[] contains every index that appears in
47634 ** either aLeft[] or the old aRight[] and such that the second condition
47635 ** above is still met.
47636 **
47637 ** The aContent[aLeft[X]] values will be unique for all X.  And the
47638 ** aContent[aRight[X]] values will be unique too.  But there might be
47639 ** one or more combinations of X and Y such that
47640 **
47641 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
47642 **
47643 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
47644 */
47645 static void walMerge(
47646   const u32 *aContent,            /* Pages in wal - keys for the sort */
47647   ht_slot *aLeft,                 /* IN: Left hand input list */
47648   int nLeft,                      /* IN: Elements in array *paLeft */
47649   ht_slot **paRight,              /* IN/OUT: Right hand input list */
47650   int *pnRight,                   /* IN/OUT: Elements in *paRight */
47651   ht_slot *aTmp                   /* Temporary buffer */
47652 ){
47653   int iLeft = 0;                  /* Current index in aLeft */
47654   int iRight = 0;                 /* Current index in aRight */
47655   int iOut = 0;                   /* Current index in output buffer */
47656   int nRight = *pnRight;
47657   ht_slot *aRight = *paRight;
47658
47659   assert( nLeft>0 && nRight>0 );
47660   while( iRight<nRight || iLeft<nLeft ){
47661     ht_slot logpage;
47662     Pgno dbpage;
47663
47664     if( (iLeft<nLeft) 
47665      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
47666     ){
47667       logpage = aLeft[iLeft++];
47668     }else{
47669       logpage = aRight[iRight++];
47670     }
47671     dbpage = aContent[logpage];
47672
47673     aTmp[iOut++] = logpage;
47674     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
47675
47676     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
47677     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
47678   }
47679
47680   *paRight = aLeft;
47681   *pnRight = iOut;
47682   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
47683 }
47684
47685 /*
47686 ** Sort the elements in list aList using aContent[] as the sort key.
47687 ** Remove elements with duplicate keys, preferring to keep the
47688 ** larger aList[] values.
47689 **
47690 ** The aList[] entries are indices into aContent[].  The values in
47691 ** aList[] are to be sorted so that for all J<K:
47692 **
47693 **      aContent[aList[J]] < aContent[aList[K]]
47694 **
47695 ** For any X and Y such that
47696 **
47697 **      aContent[aList[X]] == aContent[aList[Y]]
47698 **
47699 ** Keep the larger of the two values aList[X] and aList[Y] and discard
47700 ** the smaller.
47701 */
47702 static void walMergesort(
47703   const u32 *aContent,            /* Pages in wal */
47704   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
47705   ht_slot *aList,                 /* IN/OUT: List to sort */
47706   int *pnList                     /* IN/OUT: Number of elements in aList[] */
47707 ){
47708   struct Sublist {
47709     int nList;                    /* Number of elements in aList */
47710     ht_slot *aList;               /* Pointer to sub-list content */
47711   };
47712
47713   const int nList = *pnList;      /* Size of input list */
47714   int nMerge = 0;                 /* Number of elements in list aMerge */
47715   ht_slot *aMerge = 0;            /* List to be merged */
47716   int iList;                      /* Index into input list */
47717   int iSub = 0;                   /* Index into aSub array */
47718   struct Sublist aSub[13];        /* Array of sub-lists */
47719
47720   memset(aSub, 0, sizeof(aSub));
47721   assert( nList<=HASHTABLE_NPAGE && nList>0 );
47722   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
47723
47724   for(iList=0; iList<nList; iList++){
47725     nMerge = 1;
47726     aMerge = &aList[iList];
47727     for(iSub=0; iList & (1<<iSub); iSub++){
47728       struct Sublist *p = &aSub[iSub];
47729       assert( p->aList && p->nList<=(1<<iSub) );
47730       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
47731       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47732     }
47733     aSub[iSub].aList = aMerge;
47734     aSub[iSub].nList = nMerge;
47735   }
47736
47737   for(iSub++; iSub<ArraySize(aSub); iSub++){
47738     if( nList & (1<<iSub) ){
47739       struct Sublist *p = &aSub[iSub];
47740       assert( p->nList<=(1<<iSub) );
47741       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
47742       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
47743     }
47744   }
47745   assert( aMerge==aList );
47746   *pnList = nMerge;
47747
47748 #ifdef SQLCIPHER_DEBUG
47749   {
47750     int i;
47751     for(i=1; i<*pnList; i++){
47752       assert( aContent[aList[i]] > aContent[aList[i-1]] );
47753     }
47754   }
47755 #endif
47756 }
47757
47758 /* 
47759 ** Free an iterator allocated by walIteratorInit().
47760 */
47761 static void walIteratorFree(WalIterator *p){
47762   sqlcipher3ScratchFree(p);
47763 }
47764
47765 /*
47766 ** Construct a WalInterator object that can be used to loop over all 
47767 ** pages in the WAL in ascending order. The caller must hold the checkpoint
47768 ** lock.
47769 **
47770 ** On success, make *pp point to the newly allocated WalInterator object
47771 ** return SQLCIPHER_OK. Otherwise, return an error code. If this routine
47772 ** returns an error, the value of *pp is undefined.
47773 **
47774 ** The calling routine should invoke walIteratorFree() to destroy the
47775 ** WalIterator object when it has finished with it.
47776 */
47777 static int walIteratorInit(Wal *pWal, WalIterator **pp){
47778   WalIterator *p;                 /* Return value */
47779   int nSegment;                   /* Number of segments to merge */
47780   u32 iLast;                      /* Last frame in log */
47781   int nByte;                      /* Number of bytes to allocate */
47782   int i;                          /* Iterator variable */
47783   ht_slot *aTmp;                  /* Temp space used by merge-sort */
47784   int rc = SQLCIPHER_OK;             /* Return Code */
47785
47786   /* This routine only runs while holding the checkpoint lock. And
47787   ** it only runs if there is actually content in the log (mxFrame>0).
47788   */
47789   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
47790   iLast = pWal->hdr.mxFrame;
47791
47792   /* Allocate space for the WalIterator object. */
47793   nSegment = walFramePage(iLast) + 1;
47794   nByte = sizeof(WalIterator) 
47795         + (nSegment-1)*sizeof(struct WalSegment)
47796         + iLast*sizeof(ht_slot);
47797   p = (WalIterator *)sqlcipher3ScratchMalloc(nByte);
47798   if( !p ){
47799     return SQLCIPHER_NOMEM;
47800   }
47801   memset(p, 0, nByte);
47802   p->nSegment = nSegment;
47803
47804   /* Allocate temporary space used by the merge-sort routine. This block
47805   ** of memory will be freed before this function returns.
47806   */
47807   aTmp = (ht_slot *)sqlcipher3ScratchMalloc(
47808       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
47809   );
47810   if( !aTmp ){
47811     rc = SQLCIPHER_NOMEM;
47812   }
47813
47814   for(i=0; rc==SQLCIPHER_OK && i<nSegment; i++){
47815     volatile ht_slot *aHash;
47816     u32 iZero;
47817     volatile u32 *aPgno;
47818
47819     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
47820     if( rc==SQLCIPHER_OK ){
47821       int j;                      /* Counter variable */
47822       int nEntry;                 /* Number of entries in this segment */
47823       ht_slot *aIndex;            /* Sorted index for this segment */
47824
47825       aPgno++;
47826       if( (i+1)==nSegment ){
47827         nEntry = (int)(iLast - iZero);
47828       }else{
47829         nEntry = (int)((u32*)aHash - (u32*)aPgno);
47830       }
47831       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
47832       iZero++;
47833   
47834       for(j=0; j<nEntry; j++){
47835         aIndex[j] = (ht_slot)j;
47836       }
47837       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
47838       p->aSegment[i].iZero = iZero;
47839       p->aSegment[i].nEntry = nEntry;
47840       p->aSegment[i].aIndex = aIndex;
47841       p->aSegment[i].aPgno = (u32 *)aPgno;
47842     }
47843   }
47844   sqlcipher3ScratchFree(aTmp);
47845
47846   if( rc!=SQLCIPHER_OK ){
47847     walIteratorFree(p);
47848   }
47849   *pp = p;
47850   return rc;
47851 }
47852
47853 /*
47854 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
47855 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
47856 ** busy-handler function. Invoke it and retry the lock until either the
47857 ** lock is successfully obtained or the busy-handler returns 0.
47858 */
47859 static int walBusyLock(
47860   Wal *pWal,                      /* WAL connection */
47861   int (*xBusy)(void*),            /* Function to call when busy */
47862   void *pBusyArg,                 /* Context argument for xBusyHandler */
47863   int lockIdx,                    /* Offset of first byte to lock */
47864   int n                           /* Number of bytes to lock */
47865 ){
47866   int rc;
47867   do {
47868     rc = walLockExclusive(pWal, lockIdx, n);
47869   }while( xBusy && rc==SQLCIPHER_BUSY && xBusy(pBusyArg) );
47870   return rc;
47871 }
47872
47873 /*
47874 ** The cache of the wal-index header must be valid to call this function.
47875 ** Return the page-size in bytes used by the database.
47876 */
47877 static int walPagesize(Wal *pWal){
47878   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47879 }
47880
47881 /*
47882 ** Copy as much content as we can from the WAL back into the database file
47883 ** in response to an sqlcipher3_wal_checkpoint() request or the equivalent.
47884 **
47885 ** The amount of information copies from WAL to database might be limited
47886 ** by active readers.  This routine will never overwrite a database page
47887 ** that a concurrent reader might be using.
47888 **
47889 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
47890 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
47891 ** checkpoints are always run by a background thread or background 
47892 ** process, foreground threads will never block on a lengthy fsync call.
47893 **
47894 ** Fsync is called on the WAL before writing content out of the WAL and
47895 ** into the database.  This ensures that if the new content is persistent
47896 ** in the WAL and can be recovered following a power-loss or hard reset.
47897 **
47898 ** Fsync is also called on the database file if (and only if) the entire
47899 ** WAL content is copied into the database file.  This second fsync makes
47900 ** it safe to delete the WAL since the new content will persist in the
47901 ** database file.
47902 **
47903 ** This routine uses and updates the nBackfill field of the wal-index header.
47904 ** This is the only routine tha will increase the value of nBackfill.  
47905 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
47906 ** its value.)
47907 **
47908 ** The caller must be holding sufficient locks to ensure that no other
47909 ** checkpoint is running (in any other thread or process) at the same
47910 ** time.
47911 */
47912 static int walCheckpoint(
47913   Wal *pWal,                      /* Wal connection */
47914   int eMode,                      /* One of PASSIVE, FULL or RESTART */
47915   int (*xBusyCall)(void*),        /* Function to call when busy */
47916   void *pBusyArg,                 /* Context argument for xBusyHandler */
47917   int sync_flags,                 /* Flags for OsSync() (or 0) */
47918   u8 *zBuf                        /* Temporary buffer to use */
47919 ){
47920   int rc;                         /* Return code */
47921   int szPage;                     /* Database page-size */
47922   WalIterator *pIter = 0;         /* Wal iterator context */
47923   u32 iDbpage = 0;                /* Next database page to write */
47924   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47925   u32 mxSafeFrame;                /* Max frame that can be backfilled */
47926   u32 mxPage;                     /* Max database page to write */
47927   int i;                          /* Loop counter */
47928   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47929   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47930
47931   szPage = walPagesize(pWal);
47932   testcase( szPage<=32768 );
47933   testcase( szPage>=65536 );
47934   pInfo = walCkptInfo(pWal);
47935   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLCIPHER_OK;
47936
47937   /* Allocate the iterator */
47938   rc = walIteratorInit(pWal, &pIter);
47939   if( rc!=SQLCIPHER_OK ){
47940     return rc;
47941   }
47942   assert( pIter );
47943
47944   if( eMode!=SQLCIPHER_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47945
47946   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47947   ** safe to write into the database.  Frames beyond mxSafeFrame might
47948   ** overwrite database pages that are in use by active readers and thus
47949   ** cannot be backfilled from the WAL.
47950   */
47951   mxSafeFrame = pWal->hdr.mxFrame;
47952   mxPage = pWal->hdr.nPage;
47953   for(i=1; i<WAL_NREADER; i++){
47954     u32 y = pInfo->aReadMark[i];
47955     if( mxSafeFrame>y ){
47956       assert( y<=pWal->hdr.mxFrame );
47957       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47958       if( rc==SQLCIPHER_OK ){
47959         pInfo->aReadMark[i] = READMARK_NOT_USED;
47960         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47961       }else if( rc==SQLCIPHER_BUSY ){
47962         mxSafeFrame = y;
47963         xBusy = 0;
47964       }else{
47965         goto walcheckpoint_out;
47966       }
47967     }
47968   }
47969
47970   if( pInfo->nBackfill<mxSafeFrame
47971    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLCIPHER_OK
47972   ){
47973     i64 nSize;                    /* Current size of database file */
47974     u32 nBackfill = pInfo->nBackfill;
47975
47976     /* Sync the WAL to disk */
47977     if( sync_flags ){
47978       rc = sqlcipher3OsSync(pWal->pWalFd, sync_flags);
47979     }
47980
47981     /* If the database file may grow as a result of this checkpoint, hint
47982     ** about the eventual size of the db file to the VFS layer. 
47983     */
47984     if( rc==SQLCIPHER_OK ){
47985       i64 nReq = ((i64)mxPage * szPage);
47986       rc = sqlcipher3OsFileSize(pWal->pDbFd, &nSize);
47987       if( rc==SQLCIPHER_OK && nSize<nReq ){
47988         sqlcipher3OsFileControl(pWal->pDbFd, SQLCIPHER_FCNTL_SIZE_HINT, &nReq);
47989       }
47990     }
47991
47992     /* Iterate through the contents of the WAL, copying data to the db file. */
47993     while( rc==SQLCIPHER_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47994       i64 iOffset;
47995       assert( walFramePgno(pWal, iFrame)==iDbpage );
47996       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47997       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47998       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47999       rc = sqlcipher3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
48000       if( rc!=SQLCIPHER_OK ) break;
48001       iOffset = (iDbpage-1)*(i64)szPage;
48002       testcase( IS_BIG_INT(iOffset) );
48003       rc = sqlcipher3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
48004       if( rc!=SQLCIPHER_OK ) break;
48005     }
48006
48007     /* If work was actually accomplished... */
48008     if( rc==SQLCIPHER_OK ){
48009       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
48010         i64 szDb = pWal->hdr.nPage*(i64)szPage;
48011         testcase( IS_BIG_INT(szDb) );
48012         rc = sqlcipher3OsTruncate(pWal->pDbFd, szDb);
48013         if( rc==SQLCIPHER_OK && sync_flags ){
48014           rc = sqlcipher3OsSync(pWal->pDbFd, sync_flags);
48015         }
48016       }
48017       if( rc==SQLCIPHER_OK ){
48018         pInfo->nBackfill = mxSafeFrame;
48019       }
48020     }
48021
48022     /* Release the reader lock held while backfilling */
48023     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
48024   }
48025
48026   if( rc==SQLCIPHER_BUSY ){
48027     /* Reset the return code so as not to report a checkpoint failure
48028     ** just because there are active readers.  */
48029     rc = SQLCIPHER_OK;
48030   }
48031
48032   /* If this is an SQLCIPHER_CHECKPOINT_RESTART operation, and the entire wal
48033   ** file has been copied into the database file, then block until all
48034   ** readers have finished using the wal file. This ensures that the next
48035   ** process to write to the database restarts the wal file.
48036   */
48037   if( rc==SQLCIPHER_OK && eMode!=SQLCIPHER_CHECKPOINT_PASSIVE ){
48038     assert( pWal->writeLock );
48039     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
48040       rc = SQLCIPHER_BUSY;
48041     }else if( eMode==SQLCIPHER_CHECKPOINT_RESTART ){
48042       assert( mxSafeFrame==pWal->hdr.mxFrame );
48043       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
48044       if( rc==SQLCIPHER_OK ){
48045         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48046       }
48047     }
48048   }
48049
48050  walcheckpoint_out:
48051   walIteratorFree(pIter);
48052   return rc;
48053 }
48054
48055 /*
48056 ** Close a connection to a log file.
48057 */
48058 SQLCIPHER_PRIVATE int sqlcipher3WalClose(
48059   Wal *pWal,                      /* Wal to close */
48060   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
48061   int nBuf,
48062   u8 *zBuf                        /* Buffer of at least nBuf bytes */
48063 ){
48064   int rc = SQLCIPHER_OK;
48065   if( pWal ){
48066     int isDelete = 0;             /* True to unlink wal and wal-index files */
48067
48068     /* If an EXCLUSIVE lock can be obtained on the database file (using the
48069     ** ordinary, rollback-mode locking methods, this guarantees that the
48070     ** connection associated with this log file is the only connection to
48071     ** the database. In this case checkpoint the database and unlink both
48072     ** the wal and wal-index files.
48073     **
48074     ** The EXCLUSIVE lock is not released before returning.
48075     */
48076     rc = sqlcipher3OsLock(pWal->pDbFd, SQLCIPHER_LOCK_EXCLUSIVE);
48077     if( rc==SQLCIPHER_OK ){
48078       int bPersistWal = -1;
48079       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
48080         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
48081       }
48082       rc = sqlcipher3WalCheckpoint(
48083           pWal, SQLCIPHER_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
48084       );
48085       sqlcipher3OsFileControl(pWal->pDbFd, SQLCIPHER_FCNTL_PERSIST_WAL, &bPersistWal);
48086       if( rc==SQLCIPHER_OK && bPersistWal!=1 ){
48087         isDelete = 1;
48088       }
48089     }
48090
48091     walIndexClose(pWal, isDelete);
48092     sqlcipher3OsClose(pWal->pWalFd);
48093     if( isDelete ){
48094       sqlcipher3OsDelete(pWal->pVfs, pWal->zWalName, 0);
48095     }
48096     WALTRACE(("WAL%p: closed\n", pWal));
48097     sqlcipher3_free((void *)pWal->apWiData);
48098     sqlcipher3_free(pWal);
48099   }
48100   return rc;
48101 }
48102
48103 /*
48104 ** Try to read the wal-index header.  Return 0 on success and 1 if
48105 ** there is a problem.
48106 **
48107 ** The wal-index is in shared memory.  Another thread or process might
48108 ** be writing the header at the same time this procedure is trying to
48109 ** read it, which might result in inconsistency.  A dirty read is detected
48110 ** by verifying that both copies of the header are the same and also by
48111 ** a checksum on the header.
48112 **
48113 ** If and only if the read is consistent and the header is different from
48114 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
48115 ** and *pChanged is set to 1.
48116 **
48117 ** If the checksum cannot be verified return non-zero. If the header
48118 ** is read successfully and the checksum verified, return zero.
48119 */
48120 static int walIndexTryHdr(Wal *pWal, int *pChanged){
48121   u32 aCksum[2];                  /* Checksum on the header content */
48122   WalIndexHdr h1, h2;             /* Two copies of the header content */
48123   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
48124
48125   /* The first page of the wal-index must be mapped at this point. */
48126   assert( pWal->nWiData>0 && pWal->apWiData[0] );
48127
48128   /* Read the header. This might happen concurrently with a write to the
48129   ** same area of shared memory on a different CPU in a SMP,
48130   ** meaning it is possible that an inconsistent snapshot is read
48131   ** from the file. If this happens, return non-zero.
48132   **
48133   ** There are two copies of the header at the beginning of the wal-index.
48134   ** When reading, read [0] first then [1].  Writes are in the reverse order.
48135   ** Memory barriers are used to prevent the compiler or the hardware from
48136   ** reordering the reads and writes.
48137   */
48138   aHdr = walIndexHdr(pWal);
48139   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
48140   walShmBarrier(pWal);
48141   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
48142
48143   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
48144     return 1;   /* Dirty read */
48145   }  
48146   if( h1.isInit==0 ){
48147     return 1;   /* Malformed header - probably all zeros */
48148   }
48149   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
48150   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
48151     return 1;   /* Checksum does not match */
48152   }
48153
48154   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
48155     *pChanged = 1;
48156     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
48157     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48158     testcase( pWal->szPage<=32768 );
48159     testcase( pWal->szPage>=65536 );
48160   }
48161
48162   /* The header was successfully read. Return zero. */
48163   return 0;
48164 }
48165
48166 /*
48167 ** Read the wal-index header from the wal-index and into pWal->hdr.
48168 ** If the wal-header appears to be corrupt, try to reconstruct the
48169 ** wal-index from the WAL before returning.
48170 **
48171 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
48172 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
48173 ** to 0.
48174 **
48175 ** If the wal-index header is successfully read, return SQLCIPHER_OK. 
48176 ** Otherwise an SQLite error code.
48177 */
48178 static int walIndexReadHdr(Wal *pWal, int *pChanged){
48179   int rc;                         /* Return code */
48180   int badHdr;                     /* True if a header read failed */
48181   volatile u32 *page0;            /* Chunk of wal-index containing header */
48182
48183   /* Ensure that page 0 of the wal-index (the page that contains the 
48184   ** wal-index header) is mapped. Return early if an error occurs here.
48185   */
48186   assert( pChanged );
48187   rc = walIndexPage(pWal, 0, &page0);
48188   if( rc!=SQLCIPHER_OK ){
48189     return rc;
48190   };
48191   assert( page0 || pWal->writeLock==0 );
48192
48193   /* If the first page of the wal-index has been mapped, try to read the
48194   ** wal-index header immediately, without holding any lock. This usually
48195   ** works, but may fail if the wal-index header is corrupt or currently 
48196   ** being modified by another thread or process.
48197   */
48198   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
48199
48200   /* If the first attempt failed, it might have been due to a race
48201   ** with a writer.  So get a WRITE lock and try again.
48202   */
48203   assert( badHdr==0 || pWal->writeLock==0 );
48204   if( badHdr ){
48205     if( pWal->readOnly & WAL_SHM_RDONLY ){
48206       if( SQLCIPHER_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
48207         walUnlockShared(pWal, WAL_WRITE_LOCK);
48208         rc = SQLCIPHER_READONLY_RECOVERY;
48209       }
48210     }else if( SQLCIPHER_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
48211       pWal->writeLock = 1;
48212       if( SQLCIPHER_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
48213         badHdr = walIndexTryHdr(pWal, pChanged);
48214         if( badHdr ){
48215           /* If the wal-index header is still malformed even while holding
48216           ** a WRITE lock, it can only mean that the header is corrupted and
48217           ** needs to be reconstructed.  So run recovery to do exactly that.
48218           */
48219           rc = walIndexRecover(pWal);
48220           *pChanged = 1;
48221         }
48222       }
48223       pWal->writeLock = 0;
48224       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48225     }
48226   }
48227
48228   /* If the header is read successfully, check the version number to make
48229   ** sure the wal-index was not constructed with some future format that
48230   ** this version of SQLite cannot understand.
48231   */
48232   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
48233     rc = SQLCIPHER_CANTOPEN_BKPT;
48234   }
48235
48236   return rc;
48237 }
48238
48239 /*
48240 ** This is the value that walTryBeginRead returns when it needs to
48241 ** be retried.
48242 */
48243 #define WAL_RETRY  (-1)
48244
48245 /*
48246 ** Attempt to start a read transaction.  This might fail due to a race or
48247 ** other transient condition.  When that happens, it returns WAL_RETRY to
48248 ** indicate to the caller that it is safe to retry immediately.
48249 **
48250 ** On success return SQLCIPHER_OK.  On a permanent failure (such an
48251 ** I/O error or an SQLCIPHER_BUSY because another process is running
48252 ** recovery) return a positive error code.
48253 **
48254 ** The useWal parameter is true to force the use of the WAL and disable
48255 ** the case where the WAL is bypassed because it has been completely
48256 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
48257 ** to make a copy of the wal-index header into pWal->hdr.  If the 
48258 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
48259 ** to the caller that the local paget cache is obsolete and needs to be 
48260 ** flushed.)  When useWal==1, the wal-index header is assumed to already
48261 ** be loaded and the pChanged parameter is unused.
48262 **
48263 ** The caller must set the cnt parameter to the number of prior calls to
48264 ** this routine during the current read attempt that returned WAL_RETRY.
48265 ** This routine will start taking more aggressive measures to clear the
48266 ** race conditions after multiple WAL_RETRY returns, and after an excessive
48267 ** number of errors will ultimately return SQLCIPHER_PROTOCOL.  The
48268 ** SQLCIPHER_PROTOCOL return indicates that some other process has gone rogue
48269 ** and is not honoring the locking protocol.  There is a vanishingly small
48270 ** chance that SQLCIPHER_PROTOCOL could be returned because of a run of really
48271 ** bad luck when there is lots of contention for the wal-index, but that
48272 ** possibility is so small that it can be safely neglected, we believe.
48273 **
48274 ** On success, this routine obtains a read lock on 
48275 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
48276 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
48277 ** that means the Wal does not hold any read lock.  The reader must not
48278 ** access any database page that is modified by a WAL frame up to and
48279 ** including frame number aReadMark[pWal->readLock].  The reader will
48280 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
48281 ** Or if pWal->readLock==0, then the reader will ignore the WAL
48282 ** completely and get all content directly from the database file.
48283 ** If the useWal parameter is 1 then the WAL will never be ignored and
48284 ** this routine will always set pWal->readLock>0 on success.
48285 ** When the read transaction is completed, the caller must release the
48286 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
48287 **
48288 ** This routine uses the nBackfill and aReadMark[] fields of the header
48289 ** to select a particular WAL_READ_LOCK() that strives to let the
48290 ** checkpoint process do as much work as possible.  This routine might
48291 ** update values of the aReadMark[] array in the header, but if it does
48292 ** so it takes care to hold an exclusive lock on the corresponding
48293 ** WAL_READ_LOCK() while changing values.
48294 */
48295 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
48296   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
48297   u32 mxReadMark;                 /* Largest aReadMark[] value */
48298   int mxI;                        /* Index of largest aReadMark[] value */
48299   int i;                          /* Loop counter */
48300   int rc = SQLCIPHER_OK;             /* Return code  */
48301
48302   assert( pWal->readLock<0 );     /* Not currently locked */
48303
48304   /* Take steps to avoid spinning forever if there is a protocol error.
48305   **
48306   ** Circumstances that cause a RETRY should only last for the briefest
48307   ** instances of time.  No I/O or other system calls are done while the
48308   ** locks are held, so the locks should not be held for very long. But 
48309   ** if we are unlucky, another process that is holding a lock might get
48310   ** paged out or take a page-fault that is time-consuming to resolve, 
48311   ** during the few nanoseconds that it is holding the lock.  In that case,
48312   ** it might take longer than normal for the lock to free.
48313   **
48314   ** After 5 RETRYs, we begin calling sqlcipher3OsSleep().  The first few
48315   ** calls to sqlcipher3OsSleep() have a delay of 1 microsecond.  Really this
48316   ** is more of a scheduler yield than an actual delay.  But on the 10th
48317   ** an subsequent retries, the delays start becoming longer and longer, 
48318   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
48319   ** The total delay time before giving up is less than 1 second.
48320   */
48321   if( cnt>5 ){
48322     int nDelay = 1;                      /* Pause time in microseconds */
48323     if( cnt>100 ){
48324       VVA_ONLY( pWal->lockError = 1; )
48325       return SQLCIPHER_PROTOCOL;
48326     }
48327     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
48328     sqlcipher3OsSleep(pWal->pVfs, nDelay);
48329   }
48330
48331   if( !useWal ){
48332     rc = walIndexReadHdr(pWal, pChanged);
48333     if( rc==SQLCIPHER_BUSY ){
48334       /* If there is not a recovery running in another thread or process
48335       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
48336       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
48337       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
48338       ** would be technically correct.  But the race is benign since with
48339       ** WAL_RETRY this routine will be called again and will probably be
48340       ** right on the second iteration.
48341       */
48342       if( pWal->apWiData[0]==0 ){
48343         /* This branch is taken when the xShmMap() method returns SQLCIPHER_BUSY.
48344         ** We assume this is a transient condition, so return WAL_RETRY. The
48345         ** xShmMap() implementation used by the default unix and win32 VFS 
48346         ** modules may return SQLCIPHER_BUSY due to a race condition in the 
48347         ** code that determines whether or not the shared-memory region 
48348         ** must be zeroed before the requested page is returned.
48349         */
48350         rc = WAL_RETRY;
48351       }else if( SQLCIPHER_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
48352         walUnlockShared(pWal, WAL_RECOVER_LOCK);
48353         rc = WAL_RETRY;
48354       }else if( rc==SQLCIPHER_BUSY ){
48355         rc = SQLCIPHER_BUSY_RECOVERY;
48356       }
48357     }
48358     if( rc!=SQLCIPHER_OK ){
48359       return rc;
48360     }
48361   }
48362
48363   pInfo = walCkptInfo(pWal);
48364   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
48365     /* The WAL has been completely backfilled (or it is empty).
48366     ** and can be safely ignored.
48367     */
48368     rc = walLockShared(pWal, WAL_READ_LOCK(0));
48369     walShmBarrier(pWal);
48370     if( rc==SQLCIPHER_OK ){
48371       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
48372         /* It is not safe to allow the reader to continue here if frames
48373         ** may have been appended to the log before READ_LOCK(0) was obtained.
48374         ** When holding READ_LOCK(0), the reader ignores the entire log file,
48375         ** which implies that the database file contains a trustworthy
48376         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
48377         ** happening, this is usually correct.
48378         **
48379         ** However, if frames have been appended to the log (or if the log 
48380         ** is wrapped and written for that matter) before the READ_LOCK(0)
48381         ** is obtained, that is not necessarily true. A checkpointer may
48382         ** have started to backfill the appended frames but crashed before
48383         ** it finished. Leaving a corrupt image in the database file.
48384         */
48385         walUnlockShared(pWal, WAL_READ_LOCK(0));
48386         return WAL_RETRY;
48387       }
48388       pWal->readLock = 0;
48389       return SQLCIPHER_OK;
48390     }else if( rc!=SQLCIPHER_BUSY ){
48391       return rc;
48392     }
48393   }
48394
48395   /* If we get this far, it means that the reader will want to use
48396   ** the WAL to get at content from recent commits.  The job now is
48397   ** to select one of the aReadMark[] entries that is closest to
48398   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
48399   */
48400   mxReadMark = 0;
48401   mxI = 0;
48402   for(i=1; i<WAL_NREADER; i++){
48403     u32 thisMark = pInfo->aReadMark[i];
48404     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
48405       assert( thisMark!=READMARK_NOT_USED );
48406       mxReadMark = thisMark;
48407       mxI = i;
48408     }
48409   }
48410   /* There was once an "if" here. The extra "{" is to preserve indentation. */
48411   {
48412     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
48413      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
48414     ){
48415       for(i=1; i<WAL_NREADER; i++){
48416         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
48417         if( rc==SQLCIPHER_OK ){
48418           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
48419           mxI = i;
48420           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48421           break;
48422         }else if( rc!=SQLCIPHER_BUSY ){
48423           return rc;
48424         }
48425       }
48426     }
48427     if( mxI==0 ){
48428       assert( rc==SQLCIPHER_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
48429       return rc==SQLCIPHER_BUSY ? WAL_RETRY : SQLCIPHER_READONLY_CANTLOCK;
48430     }
48431
48432     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
48433     if( rc ){
48434       return rc==SQLCIPHER_BUSY ? WAL_RETRY : rc;
48435     }
48436     /* Now that the read-lock has been obtained, check that neither the
48437     ** value in the aReadMark[] array or the contents of the wal-index
48438     ** header have changed.
48439     **
48440     ** It is necessary to check that the wal-index header did not change
48441     ** between the time it was read and when the shared-lock was obtained
48442     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
48443     ** that the log file may have been wrapped by a writer, or that frames
48444     ** that occur later in the log than pWal->hdr.mxFrame may have been
48445     ** copied into the database by a checkpointer. If either of these things
48446     ** happened, then reading the database with the current value of
48447     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
48448     ** instead.
48449     **
48450     ** This does not guarantee that the copy of the wal-index header is up to
48451     ** date before proceeding. That would not be possible without somehow
48452     ** blocking writers. It only guarantees that a dangerous checkpoint or 
48453     ** log-wrap (either of which would require an exclusive lock on
48454     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
48455     */
48456     walShmBarrier(pWal);
48457     if( pInfo->aReadMark[mxI]!=mxReadMark
48458      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
48459     ){
48460       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
48461       return WAL_RETRY;
48462     }else{
48463       assert( mxReadMark<=pWal->hdr.mxFrame );
48464       pWal->readLock = (i16)mxI;
48465     }
48466   }
48467   return rc;
48468 }
48469
48470 /*
48471 ** Begin a read transaction on the database.
48472 **
48473 ** This routine used to be called sqlcipher3OpenSnapshot() and with good reason:
48474 ** it takes a snapshot of the state of the WAL and wal-index for the current
48475 ** instant in time.  The current thread will continue to use this snapshot.
48476 ** Other threads might append new content to the WAL and wal-index but
48477 ** that extra content is ignored by the current thread.
48478 **
48479 ** If the database contents have changes since the previous read
48480 ** transaction, then *pChanged is set to 1 before returning.  The
48481 ** Pager layer will use this to know that is cache is stale and
48482 ** needs to be flushed.
48483 */
48484 SQLCIPHER_PRIVATE int sqlcipher3WalBeginReadTransaction(Wal *pWal, int *pChanged){
48485   int rc;                         /* Return code */
48486   int cnt = 0;                    /* Number of TryBeginRead attempts */
48487
48488   do{
48489     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
48490   }while( rc==WAL_RETRY );
48491   testcase( (rc&0xff)==SQLCIPHER_BUSY );
48492   testcase( (rc&0xff)==SQLCIPHER_IOERR );
48493   testcase( rc==SQLCIPHER_PROTOCOL );
48494   testcase( rc==SQLCIPHER_OK );
48495   return rc;
48496 }
48497
48498 /*
48499 ** Finish with a read transaction.  All this does is release the
48500 ** read-lock.
48501 */
48502 SQLCIPHER_PRIVATE void sqlcipher3WalEndReadTransaction(Wal *pWal){
48503   sqlcipher3WalEndWriteTransaction(pWal);
48504   if( pWal->readLock>=0 ){
48505     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48506     pWal->readLock = -1;
48507   }
48508 }
48509
48510 /*
48511 ** Read a page from the WAL, if it is present in the WAL and if the 
48512 ** current read transaction is configured to use the WAL.  
48513 **
48514 ** The *pInWal is set to 1 if the requested page is in the WAL and
48515 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
48516 ** the WAL and needs to be read out of the database.
48517 */
48518 SQLCIPHER_PRIVATE int sqlcipher3WalRead(
48519   Wal *pWal,                      /* WAL handle */
48520   Pgno pgno,                      /* Database page number to read data for */
48521   int *pInWal,                    /* OUT: True if data is read from WAL */
48522   int nOut,                       /* Size of buffer pOut in bytes */
48523   u8 *pOut                        /* Buffer to write page data to */
48524 ){
48525   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
48526   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
48527   int iHash;                      /* Used to loop through N hash tables */
48528
48529   /* This routine is only be called from within a read transaction. */
48530   assert( pWal->readLock>=0 || pWal->lockError );
48531
48532   /* If the "last page" field of the wal-index header snapshot is 0, then
48533   ** no data will be read from the wal under any circumstances. Return early
48534   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
48535   ** then the WAL is ignored by the reader so return early, as if the 
48536   ** WAL were empty.
48537   */
48538   if( iLast==0 || pWal->readLock==0 ){
48539     *pInWal = 0;
48540     return SQLCIPHER_OK;
48541   }
48542
48543   /* Search the hash table or tables for an entry matching page number
48544   ** pgno. Each iteration of the following for() loop searches one
48545   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
48546   **
48547   ** This code might run concurrently to the code in walIndexAppend()
48548   ** that adds entries to the wal-index (and possibly to this hash 
48549   ** table). This means the value just read from the hash 
48550   ** slot (aHash[iKey]) may have been added before or after the 
48551   ** current read transaction was opened. Values added after the
48552   ** read transaction was opened may have been written incorrectly -
48553   ** i.e. these slots may contain garbage data. However, we assume
48554   ** that any slots written before the current read transaction was
48555   ** opened remain unmodified.
48556   **
48557   ** For the reasons above, the if(...) condition featured in the inner
48558   ** loop of the following block is more stringent that would be required 
48559   ** if we had exclusive access to the hash-table:
48560   **
48561   **   (aPgno[iFrame]==pgno): 
48562   **     This condition filters out normal hash-table collisions.
48563   **
48564   **   (iFrame<=iLast): 
48565   **     This condition filters out entries that were added to the hash
48566   **     table after the current read-transaction had started.
48567   */
48568   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
48569     volatile ht_slot *aHash;      /* Pointer to hash table */
48570     volatile u32 *aPgno;          /* Pointer to array of page numbers */
48571     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
48572     int iKey;                     /* Hash slot index */
48573     int nCollide;                 /* Number of hash collisions remaining */
48574     int rc;                       /* Error code */
48575
48576     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
48577     if( rc!=SQLCIPHER_OK ){
48578       return rc;
48579     }
48580     nCollide = HASHTABLE_NSLOT;
48581     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
48582       u32 iFrame = aHash[iKey] + iZero;
48583       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
48584         assert( iFrame>iRead );
48585         iRead = iFrame;
48586       }
48587       if( (nCollide--)==0 ){
48588         return SQLCIPHER_CORRUPT_BKPT;
48589       }
48590     }
48591   }
48592
48593 #ifdef SQLCIPHER_ENABLE_EXPENSIVE_ASSERT
48594   /* If expensive assert() statements are available, do a linear search
48595   ** of the wal-index file content. Make sure the results agree with the
48596   ** result obtained using the hash indexes above.  */
48597   {
48598     u32 iRead2 = 0;
48599     u32 iTest;
48600     for(iTest=iLast; iTest>0; iTest--){
48601       if( walFramePgno(pWal, iTest)==pgno ){
48602         iRead2 = iTest;
48603         break;
48604       }
48605     }
48606     assert( iRead==iRead2 );
48607   }
48608 #endif
48609
48610   /* If iRead is non-zero, then it is the log frame number that contains the
48611   ** required page. Read and return data from the log file.
48612   */
48613   if( iRead ){
48614     int sz;
48615     i64 iOffset;
48616     sz = pWal->hdr.szPage;
48617     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
48618     testcase( sz<=32768 );
48619     testcase( sz>=65536 );
48620     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
48621     *pInWal = 1;
48622     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48623     return sqlcipher3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
48624   }
48625
48626   *pInWal = 0;
48627   return SQLCIPHER_OK;
48628 }
48629
48630
48631 /* 
48632 ** Return the size of the database in pages (or zero, if unknown).
48633 */
48634 SQLCIPHER_PRIVATE Pgno sqlcipher3WalDbsize(Wal *pWal){
48635   if( pWal && ALWAYS(pWal->readLock>=0) ){
48636     return pWal->hdr.nPage;
48637   }
48638   return 0;
48639 }
48640
48641
48642 /* 
48643 ** This function starts a write transaction on the WAL.
48644 **
48645 ** A read transaction must have already been started by a prior call
48646 ** to sqlcipher3WalBeginReadTransaction().
48647 **
48648 ** If another thread or process has written into the database since
48649 ** the read transaction was started, then it is not possible for this
48650 ** thread to write as doing so would cause a fork.  So this routine
48651 ** returns SQLCIPHER_BUSY in that case and no write transaction is started.
48652 **
48653 ** There can only be a single writer active at a time.
48654 */
48655 SQLCIPHER_PRIVATE int sqlcipher3WalBeginWriteTransaction(Wal *pWal){
48656   int rc;
48657
48658   /* Cannot start a write transaction without first holding a read
48659   ** transaction. */
48660   assert( pWal->readLock>=0 );
48661
48662   if( pWal->readOnly ){
48663     return SQLCIPHER_READONLY;
48664   }
48665
48666   /* Only one writer allowed at a time.  Get the write lock.  Return
48667   ** SQLCIPHER_BUSY if unable.
48668   */
48669   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
48670   if( rc ){
48671     return rc;
48672   }
48673   pWal->writeLock = 1;
48674
48675   /* If another connection has written to the database file since the
48676   ** time the read transaction on this connection was started, then
48677   ** the write is disallowed.
48678   */
48679   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
48680     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48681     pWal->writeLock = 0;
48682     rc = SQLCIPHER_BUSY;
48683   }
48684
48685   return rc;
48686 }
48687
48688 /*
48689 ** End a write transaction.  The commit has already been done.  This
48690 ** routine merely releases the lock.
48691 */
48692 SQLCIPHER_PRIVATE int sqlcipher3WalEndWriteTransaction(Wal *pWal){
48693   if( pWal->writeLock ){
48694     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48695     pWal->writeLock = 0;
48696   }
48697   return SQLCIPHER_OK;
48698 }
48699
48700 /*
48701 ** If any data has been written (but not committed) to the log file, this
48702 ** function moves the write-pointer back to the start of the transaction.
48703 **
48704 ** Additionally, the callback function is invoked for each frame written
48705 ** to the WAL since the start of the transaction. If the callback returns
48706 ** other than SQLCIPHER_OK, it is not invoked again and the error code is
48707 ** returned to the caller.
48708 **
48709 ** Otherwise, if the callback function does not return an error, this
48710 ** function returns SQLCIPHER_OK.
48711 */
48712 SQLCIPHER_PRIVATE int sqlcipher3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
48713   int rc = SQLCIPHER_OK;
48714   if( ALWAYS(pWal->writeLock) ){
48715     Pgno iMax = pWal->hdr.mxFrame;
48716     Pgno iFrame;
48717   
48718     /* Restore the clients cache of the wal-index header to the state it
48719     ** was in before the client began writing to the database. 
48720     */
48721     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
48722
48723     for(iFrame=pWal->hdr.mxFrame+1; 
48724         ALWAYS(rc==SQLCIPHER_OK) && iFrame<=iMax; 
48725         iFrame++
48726     ){
48727       /* This call cannot fail. Unless the page for which the page number
48728       ** is passed as the second argument is (a) in the cache and 
48729       ** (b) has an outstanding reference, then xUndo is either a no-op
48730       ** (if (a) is false) or simply expels the page from the cache (if (b)
48731       ** is false).
48732       **
48733       ** If the upper layer is doing a rollback, it is guaranteed that there
48734       ** are no outstanding references to any page other than page 1. And
48735       ** page 1 is never written to the log until the transaction is
48736       ** committed. As a result, the call to xUndo may not fail.
48737       */
48738       assert( walFramePgno(pWal, iFrame)!=1 );
48739       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
48740     }
48741     walCleanupHash(pWal);
48742   }
48743   assert( rc==SQLCIPHER_OK );
48744   return rc;
48745 }
48746
48747 /* 
48748 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
48749 ** values. This function populates the array with values required to 
48750 ** "rollback" the write position of the WAL handle back to the current 
48751 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
48752 */
48753 SQLCIPHER_PRIVATE void sqlcipher3WalSavepoint(Wal *pWal, u32 *aWalData){
48754   assert( pWal->writeLock );
48755   aWalData[0] = pWal->hdr.mxFrame;
48756   aWalData[1] = pWal->hdr.aFrameCksum[0];
48757   aWalData[2] = pWal->hdr.aFrameCksum[1];
48758   aWalData[3] = pWal->nCkpt;
48759 }
48760
48761 /* 
48762 ** Move the write position of the WAL back to the point identified by
48763 ** the values in the aWalData[] array. aWalData must point to an array
48764 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
48765 ** by a call to WalSavepoint().
48766 */
48767 SQLCIPHER_PRIVATE int sqlcipher3WalSavepointUndo(Wal *pWal, u32 *aWalData){
48768   int rc = SQLCIPHER_OK;
48769
48770   assert( pWal->writeLock );
48771   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
48772
48773   if( aWalData[3]!=pWal->nCkpt ){
48774     /* This savepoint was opened immediately after the write-transaction
48775     ** was started. Right after that, the writer decided to wrap around
48776     ** to the start of the log. Update the savepoint values to match.
48777     */
48778     aWalData[0] = 0;
48779     aWalData[3] = pWal->nCkpt;
48780   }
48781
48782   if( aWalData[0]<pWal->hdr.mxFrame ){
48783     pWal->hdr.mxFrame = aWalData[0];
48784     pWal->hdr.aFrameCksum[0] = aWalData[1];
48785     pWal->hdr.aFrameCksum[1] = aWalData[2];
48786     walCleanupHash(pWal);
48787   }
48788
48789   return rc;
48790 }
48791
48792 /*
48793 ** This function is called just before writing a set of frames to the log
48794 ** file (see sqlcipher3WalFrames()). It checks to see if, instead of appending
48795 ** to the current log file, it is possible to overwrite the start of the
48796 ** existing log file with the new frames (i.e. "reset" the log). If so,
48797 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
48798 ** unchanged.
48799 **
48800 ** SQLCIPHER_OK is returned if no error is encountered (regardless of whether
48801 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
48802 ** if an error occurs.
48803 */
48804 static int walRestartLog(Wal *pWal){
48805   int rc = SQLCIPHER_OK;
48806   int cnt;
48807
48808   if( pWal->readLock==0 ){
48809     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
48810     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
48811     if( pInfo->nBackfill>0 ){
48812       u32 salt1;
48813       sqlcipher3_randomness(4, &salt1);
48814       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48815       if( rc==SQLCIPHER_OK ){
48816         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
48817         ** readers are currently using the WAL), then the transactions
48818         ** frames will overwrite the start of the existing log. Update the
48819         ** wal-index header to reflect this.
48820         **
48821         ** In theory it would be Ok to update the cache of the header only
48822         ** at this point. But updating the actual wal-index header is also
48823         ** safe and means there is no special case for sqlcipher3WalUndo()
48824         ** to handle if this transaction is rolled back.
48825         */
48826         int i;                    /* Loop counter */
48827         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
48828
48829         /* Limit the size of WAL file if the journal_size_limit PRAGMA is
48830         ** set to a non-negative value.  Log errors encountered
48831         ** during the truncation attempt. */
48832         if( pWal->mxWalSize>=0 ){
48833           i64 sz;
48834           int rx;
48835           sqlcipher3BeginBenignMalloc();
48836           rx = sqlcipher3OsFileSize(pWal->pWalFd, &sz);
48837           if( rx==SQLCIPHER_OK && (sz > pWal->mxWalSize) ){
48838             rx = sqlcipher3OsTruncate(pWal->pWalFd, pWal->mxWalSize);
48839           }
48840           sqlcipher3EndBenignMalloc();
48841           if( rx ){
48842             sqlcipher3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
48843           }
48844         }
48845
48846         pWal->nCkpt++;
48847         pWal->hdr.mxFrame = 0;
48848         sqlcipher3Put4byte((u8*)&aSalt[0], 1 + sqlcipher3Get4byte((u8*)&aSalt[0]));
48849         aSalt[1] = salt1;
48850         walIndexWriteHdr(pWal);
48851         pInfo->nBackfill = 0;
48852         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48853         assert( pInfo->aReadMark[0]==0 );
48854         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48855       }else if( rc!=SQLCIPHER_BUSY ){
48856         return rc;
48857       }
48858     }
48859     walUnlockShared(pWal, WAL_READ_LOCK(0));
48860     pWal->readLock = -1;
48861     cnt = 0;
48862     do{
48863       int notUsed;
48864       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
48865     }while( rc==WAL_RETRY );
48866     assert( (rc&0xff)!=SQLCIPHER_BUSY ); /* BUSY not possible when useWal==1 */
48867     testcase( (rc&0xff)==SQLCIPHER_IOERR );
48868     testcase( rc==SQLCIPHER_PROTOCOL );
48869     testcase( rc==SQLCIPHER_OK );
48870   }
48871   return rc;
48872 }
48873
48874 /* 
48875 ** Write a set of frames to the log. The caller must hold the write-lock
48876 ** on the log file (obtained using sqlcipher3WalBeginWriteTransaction()).
48877 */
48878 SQLCIPHER_PRIVATE int sqlcipher3WalFrames(
48879   Wal *pWal,                      /* Wal handle to write to */
48880   int szPage,                     /* Database page-size in bytes */
48881   PgHdr *pList,                   /* List of dirty pages to write */
48882   Pgno nTruncate,                 /* Database size after this commit */
48883   int isCommit,                   /* True if this is a commit */
48884   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48885 ){
48886   int rc;                         /* Used to catch return codes */
48887   u32 iFrame;                     /* Next frame address */
48888   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48889   PgHdr *p;                       /* Iterator to run through pList with. */
48890   PgHdr *pLast = 0;               /* Last frame in list */
48891   int nLast = 0;                  /* Number of extra copies of last page */
48892
48893   assert( pList );
48894   assert( pWal->writeLock );
48895
48896 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
48897   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48898     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48899               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48900   }
48901 #endif
48902
48903   /* See if it is possible to write these frames into the start of the
48904   ** log file, instead of appending to it at pWal->hdr.mxFrame.
48905   */
48906   if( SQLCIPHER_OK!=(rc = walRestartLog(pWal)) ){
48907     return rc;
48908   }
48909
48910   /* If this is the first frame written into the log, write the WAL
48911   ** header to the start of the WAL file. See comments at the top of
48912   ** this source file for a description of the WAL header format.
48913   */
48914   iFrame = pWal->hdr.mxFrame;
48915   if( iFrame==0 ){
48916     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48917     u32 aCksum[2];                /* Checksum for wal-header */
48918
48919     sqlcipher3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLCIPHER_BIGENDIAN));
48920     sqlcipher3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48921     sqlcipher3Put4byte(&aWalHdr[8], szPage);
48922     sqlcipher3Put4byte(&aWalHdr[12], pWal->nCkpt);
48923     sqlcipher3_randomness(8, pWal->hdr.aSalt);
48924     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48925     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48926     sqlcipher3Put4byte(&aWalHdr[24], aCksum[0]);
48927     sqlcipher3Put4byte(&aWalHdr[28], aCksum[1]);
48928     
48929     pWal->szPage = szPage;
48930     pWal->hdr.bigEndCksum = SQLCIPHER_BIGENDIAN;
48931     pWal->hdr.aFrameCksum[0] = aCksum[0];
48932     pWal->hdr.aFrameCksum[1] = aCksum[1];
48933
48934     rc = sqlcipher3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48935     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48936     if( rc!=SQLCIPHER_OK ){
48937       return rc;
48938     }
48939   }
48940   assert( (int)pWal->szPage==szPage );
48941
48942   /* Write the log file. */
48943   for(p=pList; p; p=p->pDirty){
48944     u32 nDbsize;                  /* Db-size field for frame header */
48945     i64 iOffset;                  /* Write offset in log file */
48946     void *pData;
48947    
48948     iOffset = walFrameOffset(++iFrame, szPage);
48949     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48950     
48951     /* Populate and write the frame header */
48952     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48953 #if defined(SQLCIPHER_HAS_CODEC)
48954     if( (pData = sqlcipher3PagerCodec(p))==0 ) return SQLCIPHER_NOMEM;
48955 #else
48956     pData = p->pData;
48957 #endif
48958     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
48959     rc = sqlcipher3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
48960     if( rc!=SQLCIPHER_OK ){
48961       return rc;
48962     }
48963
48964     /* Write the page data */
48965     rc = sqlcipher3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
48966     if( rc!=SQLCIPHER_OK ){
48967       return rc;
48968     }
48969     pLast = p;
48970   }
48971
48972   /* Sync the log file if the 'isSync' flag was specified. */
48973   if( sync_flags ){
48974     i64 iSegment = sqlcipher3OsSectorSize(pWal->pWalFd);
48975     i64 iOffset = walFrameOffset(iFrame+1, szPage);
48976
48977     assert( isCommit );
48978     assert( iSegment>0 );
48979
48980     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
48981     while( iOffset<iSegment ){
48982       void *pData;
48983 #if defined(SQLCIPHER_HAS_CODEC)
48984       if( (pData = sqlcipher3PagerCodec(pLast))==0 ) return SQLCIPHER_NOMEM;
48985 #else
48986       pData = pLast->pData;
48987 #endif
48988       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
48989       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
48990       rc = sqlcipher3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
48991       if( rc!=SQLCIPHER_OK ){
48992         return rc;
48993       }
48994       iOffset += WAL_FRAME_HDRSIZE;
48995       rc = sqlcipher3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
48996       if( rc!=SQLCIPHER_OK ){
48997         return rc;
48998       }
48999       nLast++;
49000       iOffset += szPage;
49001     }
49002
49003     rc = sqlcipher3OsSync(pWal->pWalFd, sync_flags);
49004   }
49005
49006   /* Append data to the wal-index. It is not necessary to lock the 
49007   ** wal-index to do this as the SQLCIPHER_SHM_WRITE lock held on the wal-index
49008   ** guarantees that there are no other writers, and no data that may
49009   ** be in use by existing readers is being overwritten.
49010   */
49011   iFrame = pWal->hdr.mxFrame;
49012   for(p=pList; p && rc==SQLCIPHER_OK; p=p->pDirty){
49013     iFrame++;
49014     rc = walIndexAppend(pWal, iFrame, p->pgno);
49015   }
49016   while( nLast>0 && rc==SQLCIPHER_OK ){
49017     iFrame++;
49018     nLast--;
49019     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
49020   }
49021
49022   if( rc==SQLCIPHER_OK ){
49023     /* Update the private copy of the header. */
49024     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49025     testcase( szPage<=32768 );
49026     testcase( szPage>=65536 );
49027     pWal->hdr.mxFrame = iFrame;
49028     if( isCommit ){
49029       pWal->hdr.iChange++;
49030       pWal->hdr.nPage = nTruncate;
49031     }
49032     /* If this is a commit, update the wal-index header too. */
49033     if( isCommit ){
49034       walIndexWriteHdr(pWal);
49035       pWal->iCallback = iFrame;
49036     }
49037   }
49038
49039   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
49040   return rc;
49041 }
49042
49043 /* 
49044 ** This routine is called to implement sqlcipher3_wal_checkpoint() and
49045 ** related interfaces.
49046 **
49047 ** Obtain a CHECKPOINT lock and then backfill as much information as
49048 ** we can from WAL into the database.
49049 **
49050 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
49051 ** callback. In this case this function runs a blocking checkpoint.
49052 */
49053 SQLCIPHER_PRIVATE int sqlcipher3WalCheckpoint(
49054   Wal *pWal,                      /* Wal connection */
49055   int eMode,                      /* PASSIVE, FULL or RESTART */
49056   int (*xBusy)(void*),            /* Function to call when busy */
49057   void *pBusyArg,                 /* Context argument for xBusyHandler */
49058   int sync_flags,                 /* Flags to sync db file with (or 0) */
49059   int nBuf,                       /* Size of temporary buffer */
49060   u8 *zBuf,                       /* Temporary buffer to use */
49061   int *pnLog,                     /* OUT: Number of frames in WAL */
49062   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
49063 ){
49064   int rc;                         /* Return code */
49065   int isChanged = 0;              /* True if a new wal-index header is loaded */
49066   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
49067
49068   assert( pWal->ckptLock==0 );
49069   assert( pWal->writeLock==0 );
49070
49071   if( pWal->readOnly ) return SQLCIPHER_READONLY;
49072   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
49073   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
49074   if( rc ){
49075     /* Usually this is SQLCIPHER_BUSY meaning that another thread or process
49076     ** is already running a checkpoint, or maybe a recovery.  But it might
49077     ** also be SQLCIPHER_IOERR. */
49078     return rc;
49079   }
49080   pWal->ckptLock = 1;
49081
49082   /* If this is a blocking-checkpoint, then obtain the write-lock as well
49083   ** to prevent any writers from running while the checkpoint is underway.
49084   ** This has to be done before the call to walIndexReadHdr() below.
49085   **
49086   ** If the writer lock cannot be obtained, then a passive checkpoint is
49087   ** run instead. Since the checkpointer is not holding the writer lock,
49088   ** there is no point in blocking waiting for any readers. Assuming no 
49089   ** other error occurs, this function will return SQLCIPHER_BUSY to the caller.
49090   */
49091   if( eMode!=SQLCIPHER_CHECKPOINT_PASSIVE ){
49092     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
49093     if( rc==SQLCIPHER_OK ){
49094       pWal->writeLock = 1;
49095     }else if( rc==SQLCIPHER_BUSY ){
49096       eMode2 = SQLCIPHER_CHECKPOINT_PASSIVE;
49097       rc = SQLCIPHER_OK;
49098     }
49099   }
49100
49101   /* Read the wal-index header. */
49102   if( rc==SQLCIPHER_OK ){
49103     rc = walIndexReadHdr(pWal, &isChanged);
49104   }
49105
49106   /* Copy data from the log to the database file. */
49107   if( rc==SQLCIPHER_OK ){
49108     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
49109       rc = SQLCIPHER_CORRUPT_BKPT;
49110     }else{
49111       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
49112     }
49113
49114     /* If no error occurred, set the output variables. */
49115     if( rc==SQLCIPHER_OK || rc==SQLCIPHER_BUSY ){
49116       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
49117       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
49118     }
49119   }
49120
49121   if( isChanged ){
49122     /* If a new wal-index header was loaded before the checkpoint was 
49123     ** performed, then the pager-cache associated with pWal is now
49124     ** out of date. So zero the cached wal-index header to ensure that
49125     ** next time the pager opens a snapshot on this database it knows that
49126     ** the cache needs to be reset.
49127     */
49128     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49129   }
49130
49131   /* Release the locks. */
49132   sqlcipher3WalEndWriteTransaction(pWal);
49133   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
49134   pWal->ckptLock = 0;
49135   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
49136   return (rc==SQLCIPHER_OK && eMode!=eMode2 ? SQLCIPHER_BUSY : rc);
49137 }
49138
49139 /* Return the value to pass to a sqlcipher3_wal_hook callback, the
49140 ** number of frames in the WAL at the point of the last commit since
49141 ** sqlcipher3WalCallback() was called.  If no commits have occurred since
49142 ** the last call, then return 0.
49143 */
49144 SQLCIPHER_PRIVATE int sqlcipher3WalCallback(Wal *pWal){
49145   u32 ret = 0;
49146   if( pWal ){
49147     ret = pWal->iCallback;
49148     pWal->iCallback = 0;
49149   }
49150   return (int)ret;
49151 }
49152
49153 /*
49154 ** This function is called to change the WAL subsystem into or out
49155 ** of locking_mode=EXCLUSIVE.
49156 **
49157 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
49158 ** into locking_mode=NORMAL.  This means that we must acquire a lock
49159 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
49160 ** or if the acquisition of the lock fails, then return 0.  If the
49161 ** transition out of exclusive-mode is successful, return 1.  This
49162 ** operation must occur while the pager is still holding the exclusive
49163 ** lock on the main database file.
49164 **
49165 ** If op is one, then change from locking_mode=NORMAL into 
49166 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
49167 ** be released.  Return 1 if the transition is made and 0 if the
49168 ** WAL is already in exclusive-locking mode - meaning that this
49169 ** routine is a no-op.  The pager must already hold the exclusive lock
49170 ** on the main database file before invoking this operation.
49171 **
49172 ** If op is negative, then do a dry-run of the op==1 case but do
49173 ** not actually change anything. The pager uses this to see if it
49174 ** should acquire the database exclusive lock prior to invoking
49175 ** the op==1 case.
49176 */
49177 SQLCIPHER_PRIVATE int sqlcipher3WalExclusiveMode(Wal *pWal, int op){
49178   int rc;
49179   assert( pWal->writeLock==0 );
49180   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
49181
49182   /* pWal->readLock is usually set, but might be -1 if there was a 
49183   ** prior error while attempting to acquire are read-lock. This cannot 
49184   ** happen if the connection is actually in exclusive mode (as no xShmLock
49185   ** locks are taken in this case). Nor should the pager attempt to
49186   ** upgrade to exclusive-mode following such an error.
49187   */
49188   assert( pWal->readLock>=0 || pWal->lockError );
49189   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
49190
49191   if( op==0 ){
49192     if( pWal->exclusiveMode ){
49193       pWal->exclusiveMode = 0;
49194       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLCIPHER_OK ){
49195         pWal->exclusiveMode = 1;
49196       }
49197       rc = pWal->exclusiveMode==0;
49198     }else{
49199       /* Already in locking_mode=NORMAL */
49200       rc = 0;
49201     }
49202   }else if( op>0 ){
49203     assert( pWal->exclusiveMode==0 );
49204     assert( pWal->readLock>=0 );
49205     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
49206     pWal->exclusiveMode = 1;
49207     rc = 1;
49208   }else{
49209     rc = pWal->exclusiveMode==0;
49210   }
49211   return rc;
49212 }
49213
49214 /* 
49215 ** Return true if the argument is non-NULL and the WAL module is using
49216 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
49217 ** WAL module is using shared-memory, return false. 
49218 */
49219 SQLCIPHER_PRIVATE int sqlcipher3WalHeapMemory(Wal *pWal){
49220   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
49221 }
49222
49223 #endif /* #ifndef SQLCIPHER_OMIT_WAL */
49224
49225 /************** End of wal.c *************************************************/
49226 /************** Begin file btmutex.c *****************************************/
49227 /*
49228 ** 2007 August 27
49229 **
49230 ** The author disclaims copyright to this source code.  In place of
49231 ** a legal notice, here is a blessing:
49232 **
49233 **    May you do good and not evil.
49234 **    May you find forgiveness for yourself and forgive others.
49235 **    May you share freely, never taking more than you give.
49236 **
49237 *************************************************************************
49238 **
49239 ** This file contains code used to implement mutexes on Btree objects.
49240 ** This code really belongs in btree.c.  But btree.c is getting too
49241 ** big and we want to break it down some.  This packaged seemed like
49242 ** a good breakout.
49243 */
49244 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49245 #if SQLCIPHER_THREADSAFE
49246
49247 /*
49248 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49249 ** set BtShared.db to the database handle associated with p and the
49250 ** p->locked boolean to true.
49251 */
49252 static void lockBtreeMutex(Btree *p){
49253   assert( p->locked==0 );
49254   assert( sqlcipher3_mutex_notheld(p->pBt->mutex) );
49255   assert( sqlcipher3_mutex_held(p->db->mutex) );
49256
49257   sqlcipher3_mutex_enter(p->pBt->mutex);
49258   p->pBt->db = p->db;
49259   p->locked = 1;
49260 }
49261
49262 /*
49263 ** Release the BtShared mutex associated with B-Tree handle p and
49264 ** clear the p->locked boolean.
49265 */
49266 static void unlockBtreeMutex(Btree *p){
49267   BtShared *pBt = p->pBt;
49268   assert( p->locked==1 );
49269   assert( sqlcipher3_mutex_held(pBt->mutex) );
49270   assert( sqlcipher3_mutex_held(p->db->mutex) );
49271   assert( p->db==pBt->db );
49272
49273   sqlcipher3_mutex_leave(pBt->mutex);
49274   p->locked = 0;
49275 }
49276
49277 /*
49278 ** Enter a mutex on the given BTree object.
49279 **
49280 ** If the object is not sharable, then no mutex is ever required
49281 ** and this routine is a no-op.  The underlying mutex is non-recursive.
49282 ** But we keep a reference count in Btree.wantToLock so the behavior
49283 ** of this interface is recursive.
49284 **
49285 ** To avoid deadlocks, multiple Btrees are locked in the same order
49286 ** by all database connections.  The p->pNext is a list of other
49287 ** Btrees belonging to the same database connection as the p Btree
49288 ** which need to be locked after p.  If we cannot get a lock on
49289 ** p, then first unlock all of the others on p->pNext, then wait
49290 ** for the lock to become available on p, then relock all of the
49291 ** subsequent Btrees that desire a lock.
49292 */
49293 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnter(Btree *p){
49294   Btree *pLater;
49295
49296   /* Some basic sanity checking on the Btree.  The list of Btrees
49297   ** connected by pNext and pPrev should be in sorted order by
49298   ** Btree.pBt value. All elements of the list should belong to
49299   ** the same connection. Only shared Btrees are on the list. */
49300   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49301   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49302   assert( p->pNext==0 || p->pNext->db==p->db );
49303   assert( p->pPrev==0 || p->pPrev->db==p->db );
49304   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49305
49306   /* Check for locking consistency */
49307   assert( !p->locked || p->wantToLock>0 );
49308   assert( p->sharable || p->wantToLock==0 );
49309
49310   /* We should already hold a lock on the database connection */
49311   assert( sqlcipher3_mutex_held(p->db->mutex) );
49312
49313   /* Unless the database is sharable and unlocked, then BtShared.db
49314   ** should already be set correctly. */
49315   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49316
49317   if( !p->sharable ) return;
49318   p->wantToLock++;
49319   if( p->locked ) return;
49320
49321   /* In most cases, we should be able to acquire the lock we
49322   ** want without having to go throught the ascending lock
49323   ** procedure that follows.  Just be sure not to block.
49324   */
49325   if( sqlcipher3_mutex_try(p->pBt->mutex)==SQLCIPHER_OK ){
49326     p->pBt->db = p->db;
49327     p->locked = 1;
49328     return;
49329   }
49330
49331   /* To avoid deadlock, first release all locks with a larger
49332   ** BtShared address.  Then acquire our lock.  Then reacquire
49333   ** the other BtShared locks that we used to hold in ascending
49334   ** order.
49335   */
49336   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49337     assert( pLater->sharable );
49338     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49339     assert( !pLater->locked || pLater->wantToLock>0 );
49340     if( pLater->locked ){
49341       unlockBtreeMutex(pLater);
49342     }
49343   }
49344   lockBtreeMutex(p);
49345   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49346     if( pLater->wantToLock ){
49347       lockBtreeMutex(pLater);
49348     }
49349   }
49350 }
49351
49352 /*
49353 ** Exit the recursive mutex on a Btree.
49354 */
49355 SQLCIPHER_PRIVATE void sqlcipher3BtreeLeave(Btree *p){
49356   if( p->sharable ){
49357     assert( p->wantToLock>0 );
49358     p->wantToLock--;
49359     if( p->wantToLock==0 ){
49360       unlockBtreeMutex(p);
49361     }
49362   }
49363 }
49364
49365 #ifndef NDEBUG
49366 /*
49367 ** Return true if the BtShared mutex is held on the btree, or if the
49368 ** B-Tree is not marked as sharable.
49369 **
49370 ** This routine is used only from within assert() statements.
49371 */
49372 SQLCIPHER_PRIVATE int sqlcipher3BtreeHoldsMutex(Btree *p){
49373   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49374   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49375   assert( p->sharable==0 || p->locked==0 || sqlcipher3_mutex_held(p->pBt->mutex) );
49376   assert( p->sharable==0 || p->locked==0 || sqlcipher3_mutex_held(p->db->mutex) );
49377
49378   return (p->sharable==0 || p->locked);
49379 }
49380 #endif
49381
49382
49383 #ifndef SQLCIPHER_OMIT_INCRBLOB
49384 /*
49385 ** Enter and leave a mutex on a Btree given a cursor owned by that
49386 ** Btree.  These entry points are used by incremental I/O and can be
49387 ** omitted if that module is not used.
49388 */
49389 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnterCursor(BtCursor *pCur){
49390   sqlcipher3BtreeEnter(pCur->pBtree);
49391 }
49392 SQLCIPHER_PRIVATE void sqlcipher3BtreeLeaveCursor(BtCursor *pCur){
49393   sqlcipher3BtreeLeave(pCur->pBtree);
49394 }
49395 #endif /* SQLCIPHER_OMIT_INCRBLOB */
49396
49397
49398 /*
49399 ** Enter the mutex on every Btree associated with a database
49400 ** connection.  This is needed (for example) prior to parsing
49401 ** a statement since we will be comparing table and column names
49402 ** against all schemas and we do not want those schemas being
49403 ** reset out from under us.
49404 **
49405 ** There is a corresponding leave-all procedures.
49406 **
49407 ** Enter the mutexes in accending order by BtShared pointer address
49408 ** to avoid the possibility of deadlock when two threads with
49409 ** two or more btrees in common both try to lock all their btrees
49410 ** at the same instant.
49411 */
49412 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnterAll(sqlcipher3 *db){
49413   int i;
49414   Btree *p;
49415   assert( sqlcipher3_mutex_held(db->mutex) );
49416   for(i=0; i<db->nDb; i++){
49417     p = db->aDb[i].pBt;
49418     if( p ) sqlcipher3BtreeEnter(p);
49419   }
49420 }
49421 SQLCIPHER_PRIVATE void sqlcipher3BtreeLeaveAll(sqlcipher3 *db){
49422   int i;
49423   Btree *p;
49424   assert( sqlcipher3_mutex_held(db->mutex) );
49425   for(i=0; i<db->nDb; i++){
49426     p = db->aDb[i].pBt;
49427     if( p ) sqlcipher3BtreeLeave(p);
49428   }
49429 }
49430
49431 /*
49432 ** Return true if a particular Btree requires a lock.  Return FALSE if
49433 ** no lock is ever required since it is not sharable.
49434 */
49435 SQLCIPHER_PRIVATE int sqlcipher3BtreeSharable(Btree *p){
49436   return p->sharable;
49437 }
49438
49439 #ifndef NDEBUG
49440 /*
49441 ** Return true if the current thread holds the database connection
49442 ** mutex and all required BtShared mutexes.
49443 **
49444 ** This routine is used inside assert() statements only.
49445 */
49446 SQLCIPHER_PRIVATE int sqlcipher3BtreeHoldsAllMutexes(sqlcipher3 *db){
49447   int i;
49448   if( !sqlcipher3_mutex_held(db->mutex) ){
49449     return 0;
49450   }
49451   for(i=0; i<db->nDb; i++){
49452     Btree *p;
49453     p = db->aDb[i].pBt;
49454     if( p && p->sharable &&
49455          (p->wantToLock==0 || !sqlcipher3_mutex_held(p->pBt->mutex)) ){
49456       return 0;
49457     }
49458   }
49459   return 1;
49460 }
49461 #endif /* NDEBUG */
49462
49463 #ifndef NDEBUG
49464 /*
49465 ** Return true if the correct mutexes are held for accessing the
49466 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49467 ** access are:
49468 **
49469 **   (1) The mutex on db
49470 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49471 **
49472 ** If pSchema is not NULL, then iDb is computed from pSchema and
49473 ** db using sqlcipher3SchemaToIndex().
49474 */
49475 SQLCIPHER_PRIVATE int sqlcipher3SchemaMutexHeld(sqlcipher3 *db, int iDb, Schema *pSchema){
49476   Btree *p;
49477   assert( db!=0 );
49478   if( pSchema ) iDb = sqlcipher3SchemaToIndex(db, pSchema);
49479   assert( iDb>=0 && iDb<db->nDb );
49480   if( !sqlcipher3_mutex_held(db->mutex) ) return 0;
49481   if( iDb==1 ) return 1;
49482   p = db->aDb[iDb].pBt;
49483   assert( p!=0 );
49484   return p->sharable==0 || p->locked==1;
49485 }
49486 #endif /* NDEBUG */
49487
49488 #else /* SQLCIPHER_THREADSAFE>0 above.  SQLCIPHER_THREADSAFE==0 below */
49489 /*
49490 ** The following are special cases for mutex enter routines for use
49491 ** in single threaded applications that use shared cache.  Except for
49492 ** these two routines, all mutex operations are no-ops in that case and
49493 ** are null #defines in btree.h.
49494 **
49495 ** If shared cache is disabled, then all btree mutex routines, including
49496 ** the ones below, are no-ops and are null #defines in btree.h.
49497 */
49498
49499 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnter(Btree *p){
49500   p->pBt->db = p->db;
49501 }
49502 SQLCIPHER_PRIVATE void sqlcipher3BtreeEnterAll(sqlcipher3 *db){
49503   int i;
49504   for(i=0; i<db->nDb; i++){
49505     Btree *p = db->aDb[i].pBt;
49506     if( p ){
49507       p->pBt->db = p->db;
49508     }
49509   }
49510 }
49511 #endif /* if SQLCIPHER_THREADSAFE */
49512 #endif /* ifndef SQLCIPHER_OMIT_SHARED_CACHE */
49513
49514 /************** End of btmutex.c *********************************************/
49515 /************** Begin file btree.c *******************************************/
49516 /*
49517 ** 2004 April 6
49518 **
49519 ** The author disclaims copyright to this source code.  In place of
49520 ** a legal notice, here is a blessing:
49521 **
49522 **    May you do good and not evil.
49523 **    May you find forgiveness for yourself and forgive others.
49524 **    May you share freely, never taking more than you give.
49525 **
49526 *************************************************************************
49527 ** This file implements a external (disk-based) database using BTrees.
49528 ** See the header comment on "btreeInt.h" for additional information.
49529 ** Including a description of file format and an overview of operation.
49530 */
49531
49532 /*
49533 ** The header string that appears at the beginning of every
49534 ** SQLite database.
49535 */
49536 static const char zMagicHeader[] = SQLCIPHER_FILE_HEADER;
49537
49538 /*
49539 ** Set this global variable to 1 to enable tracing using the TRACE
49540 ** macro.
49541 */
49542 #if 0
49543 int sqlcipher3BtreeTrace=1;  /* True to enable tracing */
49544 # define TRACE(X)  if(sqlcipher3BtreeTrace){printf X;fflush(stdout);}
49545 #else
49546 # define TRACE(X)
49547 #endif
49548
49549 /*
49550 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49551 ** But if the value is zero, make it 65536.
49552 **
49553 ** This routine is used to extract the "offset to cell content area" value
49554 ** from the header of a btree page.  If the page size is 65536 and the page
49555 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
49556 ** This routine makes the necessary adjustment to 65536.
49557 */
49558 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
49559
49560 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49561 /*
49562 ** A list of BtShared objects that are eligible for participation
49563 ** in shared cache.  This variable has file scope during normal builds,
49564 ** but the test harness needs to access it so we make it global for 
49565 ** test builds.
49566 **
49567 ** Access to this variable is protected by SQLCIPHER_MUTEX_STATIC_MASTER.
49568 */
49569 #ifdef SQLCIPHER_TEST
49570 SQLCIPHER_PRIVATE BtShared *SQLCIPHER_WSD sqlcipher3SharedCacheList = 0;
49571 #else
49572 static BtShared *SQLCIPHER_WSD sqlcipher3SharedCacheList = 0;
49573 #endif
49574 #endif /* SQLCIPHER_OMIT_SHARED_CACHE */
49575
49576 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49577 /*
49578 ** Enable or disable the shared pager and schema features.
49579 **
49580 ** This routine has no effect on existing database connections.
49581 ** The shared cache setting effects only future calls to
49582 ** sqlcipher3_open(), sqlcipher3_open16(), or sqlcipher3_open_v2().
49583 */
49584 SQLCIPHER_API int sqlcipher3_enable_shared_cache(int enable){
49585   sqlcipher3GlobalConfig.sharedCacheEnabled = enable;
49586   return SQLCIPHER_OK;
49587 }
49588 #endif
49589
49590
49591
49592 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
49593   /*
49594   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49595   ** and clearAllSharedCacheTableLocks()
49596   ** manipulate entries in the BtShared.pLock linked list used to store
49597   ** shared-cache table level locks. If the library is compiled with the
49598   ** shared-cache feature disabled, then there is only ever one user
49599   ** of each BtShared structure and so this locking is not necessary. 
49600   ** So define the lock related functions as no-ops.
49601   */
49602   #define querySharedCacheTableLock(a,b,c) SQLCIPHER_OK
49603   #define setSharedCacheTableLock(a,b,c) SQLCIPHER_OK
49604   #define clearAllSharedCacheTableLocks(a)
49605   #define downgradeAllSharedCacheTableLocks(a)
49606   #define hasSharedCacheTableLock(a,b,c,d) 1
49607   #define hasReadConflicts(a, b) 0
49608 #endif
49609
49610 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49611
49612 #ifdef SQLCIPHER_DEBUG
49613 /*
49614 **** This function is only used as part of an assert() statement. ***
49615 **
49616 ** Check to see if pBtree holds the required locks to read or write to the 
49617 ** table with root page iRoot.   Return 1 if it does and 0 if not.
49618 **
49619 ** For example, when writing to a table with root-page iRoot via 
49620 ** Btree connection pBtree:
49621 **
49622 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49623 **
49624 ** When writing to an index that resides in a sharable database, the 
49625 ** caller should have first obtained a lock specifying the root page of
49626 ** the corresponding table. This makes things a bit more complicated,
49627 ** as this module treats each table as a separate structure. To determine
49628 ** the table corresponding to the index being written, this
49629 ** function has to search through the database schema.
49630 **
49631 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
49632 ** hold a write-lock on the schema table (root page 1). This is also
49633 ** acceptable.
49634 */
49635 static int hasSharedCacheTableLock(
49636   Btree *pBtree,         /* Handle that must hold lock */
49637   Pgno iRoot,            /* Root page of b-tree */
49638   int isIndex,           /* True if iRoot is the root of an index b-tree */
49639   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
49640 ){
49641   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49642   Pgno iTab = 0;
49643   BtLock *pLock;
49644
49645   /* If this database is not shareable, or if the client is reading
49646   ** and has the read-uncommitted flag set, then no lock is required. 
49647   ** Return true immediately.
49648   */
49649   if( (pBtree->sharable==0)
49650    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLCIPHER_ReadUncommitted))
49651   ){
49652     return 1;
49653   }
49654
49655   /* If the client is reading  or writing an index and the schema is
49656   ** not loaded, then it is too difficult to actually check to see if
49657   ** the correct locks are held.  So do not bother - just return true.
49658   ** This case does not come up very often anyhow.
49659   */
49660   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49661     return 1;
49662   }
49663
49664   /* Figure out the root-page that the lock should be held on. For table
49665   ** b-trees, this is just the root page of the b-tree being read or
49666   ** written. For index b-trees, it is the root page of the associated
49667   ** table.  */
49668   if( isIndex ){
49669     HashElem *p;
49670     for(p=sqlcipherHashFirst(&pSchema->idxHash); p; p=sqlcipherHashNext(p)){
49671       Index *pIdx = (Index *)sqlcipherHashData(p);
49672       if( pIdx->tnum==(int)iRoot ){
49673         iTab = pIdx->pTable->tnum;
49674       }
49675     }
49676   }else{
49677     iTab = iRoot;
49678   }
49679
49680   /* Search for the required lock. Either a write-lock on root-page iTab, a 
49681   ** write-lock on the schema table, or (if the client is reading) a
49682   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
49683   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49684     if( pLock->pBtree==pBtree 
49685      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49686      && pLock->eLock>=eLockType 
49687     ){
49688       return 1;
49689     }
49690   }
49691
49692   /* Failed to find the required lock. */
49693   return 0;
49694 }
49695 #endif /* SQLCIPHER_DEBUG */
49696
49697 #ifdef SQLCIPHER_DEBUG
49698 /*
49699 **** This function may be used as part of assert() statements only. ****
49700 **
49701 ** Return true if it would be illegal for pBtree to write into the
49702 ** table or index rooted at iRoot because other shared connections are
49703 ** simultaneously reading that same table or index.
49704 **
49705 ** It is illegal for pBtree to write if some other Btree object that
49706 ** shares the same BtShared object is currently reading or writing
49707 ** the iRoot table.  Except, if the other Btree object has the
49708 ** read-uncommitted flag set, then it is OK for the other object to
49709 ** have a read cursor.
49710 **
49711 ** For example, before writing to any part of the table or index
49712 ** rooted at page iRoot, one should call:
49713 **
49714 **    assert( !hasReadConflicts(pBtree, iRoot) );
49715 */
49716 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49717   BtCursor *p;
49718   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49719     if( p->pgnoRoot==iRoot 
49720      && p->pBtree!=pBtree
49721      && 0==(p->pBtree->db->flags & SQLCIPHER_ReadUncommitted)
49722     ){
49723       return 1;
49724     }
49725   }
49726   return 0;
49727 }
49728 #endif    /* #ifdef SQLCIPHER_DEBUG */
49729
49730 /*
49731 ** Query to see if Btree handle p may obtain a lock of type eLock 
49732 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49733 ** SQLCIPHER_OK if the lock may be obtained (by calling
49734 ** setSharedCacheTableLock()), or SQLCIPHER_LOCKED if not.
49735 */
49736 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49737   BtShared *pBt = p->pBt;
49738   BtLock *pIter;
49739
49740   assert( sqlcipher3BtreeHoldsMutex(p) );
49741   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49742   assert( p->db!=0 );
49743   assert( !(p->db->flags&SQLCIPHER_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49744   
49745   /* If requesting a write-lock, then the Btree must have an open write
49746   ** transaction on this file. And, obviously, for this to be so there 
49747   ** must be an open write transaction on the file itself.
49748   */
49749   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49750   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49751   
49752   /* This routine is a no-op if the shared-cache is not enabled */
49753   if( !p->sharable ){
49754     return SQLCIPHER_OK;
49755   }
49756
49757   /* If some other connection is holding an exclusive lock, the
49758   ** requested lock may not be obtained.
49759   */
49760   if( pBt->pWriter!=p && pBt->isExclusive ){
49761     sqlcipher3ConnectionBlocked(p->db, pBt->pWriter->db);
49762     return SQLCIPHER_LOCKED_SHAREDCACHE;
49763   }
49764
49765   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49766     /* The condition (pIter->eLock!=eLock) in the following if(...) 
49767     ** statement is a simplification of:
49768     **
49769     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49770     **
49771     ** since we know that if eLock==WRITE_LOCK, then no other connection
49772     ** may hold a WRITE_LOCK on any table in this file (since there can
49773     ** only be a single writer).
49774     */
49775     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49776     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49777     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49778       sqlcipher3ConnectionBlocked(p->db, pIter->pBtree->db);
49779       if( eLock==WRITE_LOCK ){
49780         assert( p==pBt->pWriter );
49781         pBt->isPending = 1;
49782       }
49783       return SQLCIPHER_LOCKED_SHAREDCACHE;
49784     }
49785   }
49786   return SQLCIPHER_OK;
49787 }
49788 #endif /* !SQLCIPHER_OMIT_SHARED_CACHE */
49789
49790 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49791 /*
49792 ** Add a lock on the table with root-page iTable to the shared-btree used
49793 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
49794 ** WRITE_LOCK.
49795 **
49796 ** This function assumes the following:
49797 **
49798 **   (a) The specified Btree object p is connected to a sharable
49799 **       database (one with the BtShared.sharable flag set), and
49800 **
49801 **   (b) No other Btree objects hold a lock that conflicts
49802 **       with the requested lock (i.e. querySharedCacheTableLock() has
49803 **       already been called and returned SQLCIPHER_OK).
49804 **
49805 ** SQLCIPHER_OK is returned if the lock is added successfully. SQLCIPHER_NOMEM 
49806 ** is returned if a malloc attempt fails.
49807 */
49808 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49809   BtShared *pBt = p->pBt;
49810   BtLock *pLock = 0;
49811   BtLock *pIter;
49812
49813   assert( sqlcipher3BtreeHoldsMutex(p) );
49814   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49815   assert( p->db!=0 );
49816
49817   /* A connection with the read-uncommitted flag set will never try to
49818   ** obtain a read-lock using this function. The only read-lock obtained
49819   ** by a connection in read-uncommitted mode is on the sqlcipher_master 
49820   ** table, and that lock is obtained in BtreeBeginTrans().  */
49821   assert( 0==(p->db->flags&SQLCIPHER_ReadUncommitted) || eLock==WRITE_LOCK );
49822
49823   /* This function should only be called on a sharable b-tree after it 
49824   ** has been determined that no other b-tree holds a conflicting lock.  */
49825   assert( p->sharable );
49826   assert( SQLCIPHER_OK==querySharedCacheTableLock(p, iTable, eLock) );
49827
49828   /* First search the list for an existing lock on this table. */
49829   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49830     if( pIter->iTable==iTable && pIter->pBtree==p ){
49831       pLock = pIter;
49832       break;
49833     }
49834   }
49835
49836   /* If the above search did not find a BtLock struct associating Btree p
49837   ** with table iTable, allocate one and link it into the list.
49838   */
49839   if( !pLock ){
49840     pLock = (BtLock *)sqlcipher3MallocZero(sizeof(BtLock));
49841     if( !pLock ){
49842       return SQLCIPHER_NOMEM;
49843     }
49844     pLock->iTable = iTable;
49845     pLock->pBtree = p;
49846     pLock->pNext = pBt->pLock;
49847     pBt->pLock = pLock;
49848   }
49849
49850   /* Set the BtLock.eLock variable to the maximum of the current lock
49851   ** and the requested lock. This means if a write-lock was already held
49852   ** and a read-lock requested, we don't incorrectly downgrade the lock.
49853   */
49854   assert( WRITE_LOCK>READ_LOCK );
49855   if( eLock>pLock->eLock ){
49856     pLock->eLock = eLock;
49857   }
49858
49859   return SQLCIPHER_OK;
49860 }
49861 #endif /* !SQLCIPHER_OMIT_SHARED_CACHE */
49862
49863 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
49864 /*
49865 ** Release all the table locks (locks obtained via calls to
49866 ** the setSharedCacheTableLock() procedure) held by Btree object p.
49867 **
49868 ** This function assumes that Btree p has an open read or write 
49869 ** transaction. If it does not, then the BtShared.isPending variable
49870 ** may be incorrectly cleared.
49871 */
49872 static void clearAllSharedCacheTableLocks(Btree *p){
49873   BtShared *pBt = p->pBt;
49874   BtLock **ppIter = &pBt->pLock;
49875
49876   assert( sqlcipher3BtreeHoldsMutex(p) );
49877   assert( p->sharable || 0==*ppIter );
49878   assert( p->inTrans>0 );
49879
49880   while( *ppIter ){
49881     BtLock *pLock = *ppIter;
49882     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
49883     assert( pLock->pBtree->inTrans>=pLock->eLock );
49884     if( pLock->pBtree==p ){
49885       *ppIter = pLock->pNext;
49886       assert( pLock->iTable!=1 || pLock==&p->lock );
49887       if( pLock->iTable!=1 ){
49888         sqlcipher3_free(pLock);
49889       }
49890     }else{
49891       ppIter = &pLock->pNext;
49892     }
49893   }
49894
49895   assert( pBt->isPending==0 || pBt->pWriter );
49896   if( pBt->pWriter==p ){
49897     pBt->pWriter = 0;
49898     pBt->isExclusive = 0;
49899     pBt->isPending = 0;
49900   }else if( pBt->nTransaction==2 ){
49901     /* This function is called when Btree p is concluding its 
49902     ** transaction. If there currently exists a writer, and p is not
49903     ** that writer, then the number of locks held by connections other
49904     ** than the writer must be about to drop to zero. In this case
49905     ** set the isPending flag to 0.
49906     **
49907     ** If there is not currently a writer, then BtShared.isPending must
49908     ** be zero already. So this next line is harmless in that case.
49909     */
49910     pBt->isPending = 0;
49911   }
49912 }
49913
49914 /*
49915 ** This function changes all write-locks held by Btree p into read-locks.
49916 */
49917 static void downgradeAllSharedCacheTableLocks(Btree *p){
49918   BtShared *pBt = p->pBt;
49919   if( pBt->pWriter==p ){
49920     BtLock *pLock;
49921     pBt->pWriter = 0;
49922     pBt->isExclusive = 0;
49923     pBt->isPending = 0;
49924     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
49925       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
49926       pLock->eLock = READ_LOCK;
49927     }
49928   }
49929 }
49930
49931 #endif /* SQLCIPHER_OMIT_SHARED_CACHE */
49932
49933 static void releasePage(MemPage *pPage);  /* Forward reference */
49934
49935 /*
49936 ***** This routine is used inside of assert() only ****
49937 **
49938 ** Verify that the cursor holds the mutex on its BtShared
49939 */
49940 #ifdef SQLCIPHER_DEBUG
49941 static int cursorHoldsMutex(BtCursor *p){
49942   return sqlcipher3_mutex_held(p->pBt->mutex);
49943 }
49944 #endif
49945
49946
49947 #ifndef SQLCIPHER_OMIT_INCRBLOB
49948 /*
49949 ** Invalidate the overflow page-list cache for cursor pCur, if any.
49950 */
49951 static void invalidateOverflowCache(BtCursor *pCur){
49952   assert( cursorHoldsMutex(pCur) );
49953   sqlcipher3_free(pCur->aOverflow);
49954   pCur->aOverflow = 0;
49955 }
49956
49957 /*
49958 ** Invalidate the overflow page-list cache for all cursors opened
49959 ** on the shared btree structure pBt.
49960 */
49961 static void invalidateAllOverflowCache(BtShared *pBt){
49962   BtCursor *p;
49963   assert( sqlcipher3_mutex_held(pBt->mutex) );
49964   for(p=pBt->pCursor; p; p=p->pNext){
49965     invalidateOverflowCache(p);
49966   }
49967 }
49968
49969 /*
49970 ** This function is called before modifying the contents of a table
49971 ** to invalidate any incrblob cursors that are open on the
49972 ** row or one of the rows being modified.
49973 **
49974 ** If argument isClearTable is true, then the entire contents of the
49975 ** table is about to be deleted. In this case invalidate all incrblob
49976 ** cursors open on any row within the table with root-page pgnoRoot.
49977 **
49978 ** Otherwise, if argument isClearTable is false, then the row with
49979 ** rowid iRow is being replaced or deleted. In this case invalidate
49980 ** only those incrblob cursors open on that specific row.
49981 */
49982 static void invalidateIncrblobCursors(
49983   Btree *pBtree,          /* The database file to check */
49984   i64 iRow,               /* The rowid that might be changing */
49985   int isClearTable        /* True if all rows are being deleted */
49986 ){
49987   BtCursor *p;
49988   BtShared *pBt = pBtree->pBt;
49989   assert( sqlcipher3BtreeHoldsMutex(pBtree) );
49990   for(p=pBt->pCursor; p; p=p->pNext){
49991     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
49992       p->eState = CURSOR_INVALID;
49993     }
49994   }
49995 }
49996
49997 #else
49998   /* Stub functions when INCRBLOB is omitted */
49999   #define invalidateOverflowCache(x)
50000   #define invalidateAllOverflowCache(x)
50001   #define invalidateIncrblobCursors(x,y,z)
50002 #endif /* SQLCIPHER_OMIT_INCRBLOB */
50003
50004 /*
50005 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
50006 ** when a page that previously contained data becomes a free-list leaf 
50007 ** page.
50008 **
50009 ** The BtShared.pHasContent bitvec exists to work around an obscure
50010 ** bug caused by the interaction of two useful IO optimizations surrounding
50011 ** free-list leaf pages:
50012 **
50013 **   1) When all data is deleted from a page and the page becomes
50014 **      a free-list leaf page, the page is not written to the database
50015 **      (as free-list leaf pages contain no meaningful data). Sometimes
50016 **      such a page is not even journalled (as it will not be modified,
50017 **      why bother journalling it?).
50018 **
50019 **   2) When a free-list leaf page is reused, its content is not read
50020 **      from the database or written to the journal file (why should it
50021 **      be, if it is not at all meaningful?).
50022 **
50023 ** By themselves, these optimizations work fine and provide a handy
50024 ** performance boost to bulk delete or insert operations. However, if
50025 ** a page is moved to the free-list and then reused within the same
50026 ** transaction, a problem comes up. If the page is not journalled when
50027 ** it is moved to the free-list and it is also not journalled when it
50028 ** is extracted from the free-list and reused, then the original data
50029 ** may be lost. In the event of a rollback, it may not be possible
50030 ** to restore the database to its original configuration.
50031 **
50032 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
50033 ** moved to become a free-list leaf page, the corresponding bit is
50034 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50035 ** optimization 2 above is omitted if the corresponding bit is already
50036 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
50037 ** at the end of every transaction.
50038 */
50039 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50040   int rc = SQLCIPHER_OK;
50041   if( !pBt->pHasContent ){
50042     assert( pgno<=pBt->nPage );
50043     pBt->pHasContent = sqlcipher3BitvecCreate(pBt->nPage);
50044     if( !pBt->pHasContent ){
50045       rc = SQLCIPHER_NOMEM;
50046     }
50047   }
50048   if( rc==SQLCIPHER_OK && pgno<=sqlcipher3BitvecSize(pBt->pHasContent) ){
50049     rc = sqlcipher3BitvecSet(pBt->pHasContent, pgno);
50050   }
50051   return rc;
50052 }
50053
50054 /*
50055 ** Query the BtShared.pHasContent vector.
50056 **
50057 ** This function is called when a free-list leaf page is removed from the
50058 ** free-list for reuse. It returns false if it is safe to retrieve the
50059 ** page from the pager layer with the 'no-content' flag set. True otherwise.
50060 */
50061 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50062   Bitvec *p = pBt->pHasContent;
50063   return (p && (pgno>sqlcipher3BitvecSize(p) || sqlcipher3BitvecTest(p, pgno)));
50064 }
50065
50066 /*
50067 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50068 ** invoked at the conclusion of each write-transaction.
50069 */
50070 static void btreeClearHasContent(BtShared *pBt){
50071   sqlcipher3BitvecDestroy(pBt->pHasContent);
50072   pBt->pHasContent = 0;
50073 }
50074
50075 /*
50076 ** Save the current cursor position in the variables BtCursor.nKey 
50077 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50078 **
50079 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50080 ** prior to calling this routine.  
50081 */
50082 static int saveCursorPosition(BtCursor *pCur){
50083   int rc;
50084
50085   assert( CURSOR_VALID==pCur->eState );
50086   assert( 0==pCur->pKey );
50087   assert( cursorHoldsMutex(pCur) );
50088
50089   rc = sqlcipher3BtreeKeySize(pCur, &pCur->nKey);
50090   assert( rc==SQLCIPHER_OK );  /* KeySize() cannot fail */
50091
50092   /* If this is an intKey table, then the above call to BtreeKeySize()
50093   ** stores the integer key in pCur->nKey. In this case this value is
50094   ** all that is required. Otherwise, if pCur is not open on an intKey
50095   ** table, then malloc space for and store the pCur->nKey bytes of key 
50096   ** data.
50097   */
50098   if( 0==pCur->apPage[0]->intKey ){
50099     void *pKey = sqlcipher3Malloc( (int)pCur->nKey );
50100     if( pKey ){
50101       rc = sqlcipher3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50102       if( rc==SQLCIPHER_OK ){
50103         pCur->pKey = pKey;
50104       }else{
50105         sqlcipher3_free(pKey);
50106       }
50107     }else{
50108       rc = SQLCIPHER_NOMEM;
50109     }
50110   }
50111   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50112
50113   if( rc==SQLCIPHER_OK ){
50114     int i;
50115     for(i=0; i<=pCur->iPage; i++){
50116       releasePage(pCur->apPage[i]);
50117       pCur->apPage[i] = 0;
50118     }
50119     pCur->iPage = -1;
50120     pCur->eState = CURSOR_REQUIRESEEK;
50121   }
50122
50123   invalidateOverflowCache(pCur);
50124   return rc;
50125 }
50126
50127 /*
50128 ** Save the positions of all cursors (except pExcept) that are open on
50129 ** the table  with root-page iRoot. Usually, this is called just before cursor
50130 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50131 */
50132 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50133   BtCursor *p;
50134   assert( sqlcipher3_mutex_held(pBt->mutex) );
50135   assert( pExcept==0 || pExcept->pBt==pBt );
50136   for(p=pBt->pCursor; p; p=p->pNext){
50137     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
50138         p->eState==CURSOR_VALID ){
50139       int rc = saveCursorPosition(p);
50140       if( SQLCIPHER_OK!=rc ){
50141         return rc;
50142       }
50143     }
50144   }
50145   return SQLCIPHER_OK;
50146 }
50147
50148 /*
50149 ** Clear the current cursor position.
50150 */
50151 SQLCIPHER_PRIVATE void sqlcipher3BtreeClearCursor(BtCursor *pCur){
50152   assert( cursorHoldsMutex(pCur) );
50153   sqlcipher3_free(pCur->pKey);
50154   pCur->pKey = 0;
50155   pCur->eState = CURSOR_INVALID;
50156 }
50157
50158 /*
50159 ** In this version of BtreeMoveto, pKey is a packed index record
50160 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
50161 ** record and then call BtreeMovetoUnpacked() to do the work.
50162 */
50163 static int btreeMoveto(
50164   BtCursor *pCur,     /* Cursor open on the btree to be searched */
50165   const void *pKey,   /* Packed key if the btree is an index */
50166   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50167   int bias,           /* Bias search to the high end */
50168   int *pRes           /* Write search results here */
50169 ){
50170   int rc;                    /* Status code */
50171   UnpackedRecord *pIdxKey;   /* Unpacked index key */
50172   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50173   char *pFree = 0;
50174
50175   if( pKey ){
50176     assert( nKey==(i64)(int)nKey );
50177     pIdxKey = sqlcipher3VdbeAllocUnpackedRecord(
50178         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50179     );
50180     if( pIdxKey==0 ) return SQLCIPHER_NOMEM;
50181     sqlcipher3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50182   }else{
50183     pIdxKey = 0;
50184   }
50185   rc = sqlcipher3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50186   if( pFree ){
50187     sqlcipher3DbFree(pCur->pKeyInfo->db, pFree);
50188   }
50189   return rc;
50190 }
50191
50192 /*
50193 ** Restore the cursor to the position it was in (or as close to as possible)
50194 ** when saveCursorPosition() was called. Note that this call deletes the 
50195 ** saved position info stored by saveCursorPosition(), so there can be
50196 ** at most one effective restoreCursorPosition() call after each 
50197 ** saveCursorPosition().
50198 */
50199 static int btreeRestoreCursorPosition(BtCursor *pCur){
50200   int rc;
50201   assert( cursorHoldsMutex(pCur) );
50202   assert( pCur->eState>=CURSOR_REQUIRESEEK );
50203   if( pCur->eState==CURSOR_FAULT ){
50204     return pCur->skipNext;
50205   }
50206   pCur->eState = CURSOR_INVALID;
50207   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50208   if( rc==SQLCIPHER_OK ){
50209     sqlcipher3_free(pCur->pKey);
50210     pCur->pKey = 0;
50211     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50212   }
50213   return rc;
50214 }
50215
50216 #define restoreCursorPosition(p) \
50217   (p->eState>=CURSOR_REQUIRESEEK ? \
50218          btreeRestoreCursorPosition(p) : \
50219          SQLCIPHER_OK)
50220
50221 /*
50222 ** Determine whether or not a cursor has moved from the position it
50223 ** was last placed at.  Cursors can move when the row they are pointing
50224 ** at is deleted out from under them.
50225 **
50226 ** This routine returns an error code if something goes wrong.  The
50227 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50228 */
50229 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50230   int rc;
50231
50232   rc = restoreCursorPosition(pCur);
50233   if( rc ){
50234     *pHasMoved = 1;
50235     return rc;
50236   }
50237   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50238     *pHasMoved = 1;
50239   }else{
50240     *pHasMoved = 0;
50241   }
50242   return SQLCIPHER_OK;
50243 }
50244
50245 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
50246 /*
50247 ** Given a page number of a regular database page, return the page
50248 ** number for the pointer-map page that contains the entry for the
50249 ** input page number.
50250 **
50251 ** Return 0 (not a valid page) for pgno==1 since there is
50252 ** no pointer map associated with page 1.  The integrity_check logic
50253 ** requires that ptrmapPageno(*,1)!=1.
50254 */
50255 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50256   int nPagesPerMapPage;
50257   Pgno iPtrMap, ret;
50258   assert( sqlcipher3_mutex_held(pBt->mutex) );
50259   if( pgno<2 ) return 0;
50260   nPagesPerMapPage = (pBt->usableSize/5)+1;
50261   iPtrMap = (pgno-2)/nPagesPerMapPage;
50262   ret = (iPtrMap*nPagesPerMapPage) + 2; 
50263   if( ret==PENDING_BYTE_PAGE(pBt) ){
50264     ret++;
50265   }
50266   return ret;
50267 }
50268
50269 /*
50270 ** Write an entry into the pointer map.
50271 **
50272 ** This routine updates the pointer map entry for page number 'key'
50273 ** so that it maps to type 'eType' and parent page number 'pgno'.
50274 **
50275 ** If *pRC is initially non-zero (non-SQLCIPHER_OK) then this routine is
50276 ** a no-op.  If an error occurs, the appropriate error code is written
50277 ** into *pRC.
50278 */
50279 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50280   DbPage *pDbPage;  /* The pointer map page */
50281   u8 *pPtrmap;      /* The pointer map data */
50282   Pgno iPtrmap;     /* The pointer map page number */
50283   int offset;       /* Offset in pointer map page */
50284   int rc;           /* Return code from subfunctions */
50285
50286   if( *pRC ) return;
50287
50288   assert( sqlcipher3_mutex_held(pBt->mutex) );
50289   /* The master-journal page number must never be used as a pointer map page */
50290   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50291
50292   assert( pBt->autoVacuum );
50293   if( key==0 ){
50294     *pRC = SQLCIPHER_CORRUPT_BKPT;
50295     return;
50296   }
50297   iPtrmap = PTRMAP_PAGENO(pBt, key);
50298   rc = sqlcipher3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50299   if( rc!=SQLCIPHER_OK ){
50300     *pRC = rc;
50301     return;
50302   }
50303   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50304   if( offset<0 ){
50305     *pRC = SQLCIPHER_CORRUPT_BKPT;
50306     goto ptrmap_exit;
50307   }
50308   assert( offset <= (int)pBt->usableSize-5 );
50309   pPtrmap = (u8 *)sqlcipher3PagerGetData(pDbPage);
50310
50311   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50312     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50313     *pRC= rc = sqlcipher3PagerWrite(pDbPage);
50314     if( rc==SQLCIPHER_OK ){
50315       pPtrmap[offset] = eType;
50316       put4byte(&pPtrmap[offset+1], parent);
50317     }
50318   }
50319
50320 ptrmap_exit:
50321   sqlcipher3PagerUnref(pDbPage);
50322 }
50323
50324 /*
50325 ** Read an entry from the pointer map.
50326 **
50327 ** This routine retrieves the pointer map entry for page 'key', writing
50328 ** the type and parent page number to *pEType and *pPgno respectively.
50329 ** An error code is returned if something goes wrong, otherwise SQLCIPHER_OK.
50330 */
50331 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50332   DbPage *pDbPage;   /* The pointer map page */
50333   int iPtrmap;       /* Pointer map page index */
50334   u8 *pPtrmap;       /* Pointer map page data */
50335   int offset;        /* Offset of entry in pointer map */
50336   int rc;
50337
50338   assert( sqlcipher3_mutex_held(pBt->mutex) );
50339
50340   iPtrmap = PTRMAP_PAGENO(pBt, key);
50341   rc = sqlcipher3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50342   if( rc!=0 ){
50343     return rc;
50344   }
50345   pPtrmap = (u8 *)sqlcipher3PagerGetData(pDbPage);
50346
50347   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50348   if( offset<0 ){
50349     sqlcipher3PagerUnref(pDbPage);
50350     return SQLCIPHER_CORRUPT_BKPT;
50351   }
50352   assert( offset <= (int)pBt->usableSize-5 );
50353   assert( pEType!=0 );
50354   *pEType = pPtrmap[offset];
50355   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50356
50357   sqlcipher3PagerUnref(pDbPage);
50358   if( *pEType<1 || *pEType>5 ) return SQLCIPHER_CORRUPT_BKPT;
50359   return SQLCIPHER_OK;
50360 }
50361
50362 #else /* if defined SQLCIPHER_OMIT_AUTOVACUUM */
50363   #define ptrmapPut(w,x,y,z,rc)
50364   #define ptrmapGet(w,x,y,z) SQLCIPHER_OK
50365   #define ptrmapPutOvflPtr(x, y, rc)
50366 #endif
50367
50368 /*
50369 ** Given a btree page and a cell index (0 means the first cell on
50370 ** the page, 1 means the second cell, and so forth) return a pointer
50371 ** to the cell content.
50372 **
50373 ** This routine works only for pages that do not contain overflow cells.
50374 */
50375 #define findCell(P,I) \
50376   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
50377 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50378
50379
50380 /*
50381 ** This a more complex version of findCell() that works for
50382 ** pages that do contain overflow cells.
50383 */
50384 static u8 *findOverflowCell(MemPage *pPage, int iCell){
50385   int i;
50386   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50387   for(i=pPage->nOverflow-1; i>=0; i--){
50388     int k;
50389     struct _OvflCell *pOvfl;
50390     pOvfl = &pPage->aOvfl[i];
50391     k = pOvfl->idx;
50392     if( k<=iCell ){
50393       if( k==iCell ){
50394         return pOvfl->pCell;
50395       }
50396       iCell--;
50397     }
50398   }
50399   return findCell(pPage, iCell);
50400 }
50401
50402 /*
50403 ** Parse a cell content block and fill in the CellInfo structure.  There
50404 ** are two versions of this function.  btreeParseCell() takes a 
50405 ** cell index as the second argument and btreeParseCellPtr() 
50406 ** takes a pointer to the body of the cell as its second argument.
50407 **
50408 ** Within this file, the parseCell() macro can be called instead of
50409 ** btreeParseCellPtr(). Using some compilers, this will be faster.
50410 */
50411 static void btreeParseCellPtr(
50412   MemPage *pPage,         /* Page containing the cell */
50413   u8 *pCell,              /* Pointer to the cell text. */
50414   CellInfo *pInfo         /* Fill in this structure */
50415 ){
50416   u16 n;                  /* Number bytes in cell content header */
50417   u32 nPayload;           /* Number of bytes of cell payload */
50418
50419   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50420
50421   pInfo->pCell = pCell;
50422   assert( pPage->leaf==0 || pPage->leaf==1 );
50423   n = pPage->childPtrSize;
50424   assert( n==4-4*pPage->leaf );
50425   if( pPage->intKey ){
50426     if( pPage->hasData ){
50427       n += getVarint32(&pCell[n], nPayload);
50428     }else{
50429       nPayload = 0;
50430     }
50431     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50432     pInfo->nData = nPayload;
50433   }else{
50434     pInfo->nData = 0;
50435     n += getVarint32(&pCell[n], nPayload);
50436     pInfo->nKey = nPayload;
50437   }
50438   pInfo->nPayload = nPayload;
50439   pInfo->nHeader = n;
50440   testcase( nPayload==pPage->maxLocal );
50441   testcase( nPayload==pPage->maxLocal+1 );
50442   if( likely(nPayload<=pPage->maxLocal) ){
50443     /* This is the (easy) common case where the entire payload fits
50444     ** on the local page.  No overflow is required.
50445     */
50446     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50447     pInfo->nLocal = (u16)nPayload;
50448     pInfo->iOverflow = 0;
50449   }else{
50450     /* If the payload will not fit completely on the local page, we have
50451     ** to decide how much to store locally and how much to spill onto
50452     ** overflow pages.  The strategy is to minimize the amount of unused
50453     ** space on overflow pages while keeping the amount of local storage
50454     ** in between minLocal and maxLocal.
50455     **
50456     ** Warning:  changing the way overflow payload is distributed in any
50457     ** way will result in an incompatible file format.
50458     */
50459     int minLocal;  /* Minimum amount of payload held locally */
50460     int maxLocal;  /* Maximum amount of payload held locally */
50461     int surplus;   /* Overflow payload available for local storage */
50462
50463     minLocal = pPage->minLocal;
50464     maxLocal = pPage->maxLocal;
50465     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50466     testcase( surplus==maxLocal );
50467     testcase( surplus==maxLocal+1 );
50468     if( surplus <= maxLocal ){
50469       pInfo->nLocal = (u16)surplus;
50470     }else{
50471       pInfo->nLocal = (u16)minLocal;
50472     }
50473     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50474     pInfo->nSize = pInfo->iOverflow + 4;
50475   }
50476 }
50477 #define parseCell(pPage, iCell, pInfo) \
50478   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50479 static void btreeParseCell(
50480   MemPage *pPage,         /* Page containing the cell */
50481   int iCell,              /* The cell index.  First cell is 0 */
50482   CellInfo *pInfo         /* Fill in this structure */
50483 ){
50484   parseCell(pPage, iCell, pInfo);
50485 }
50486
50487 /*
50488 ** Compute the total number of bytes that a Cell needs in the cell
50489 ** data area of the btree-page.  The return number includes the cell
50490 ** data header and the local payload, but not any overflow page or
50491 ** the space used by the cell pointer.
50492 */
50493 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50494   u8 *pIter = &pCell[pPage->childPtrSize];
50495   u32 nSize;
50496
50497 #ifdef SQLCIPHER_DEBUG
50498   /* The value returned by this function should always be the same as
50499   ** the (CellInfo.nSize) value found by doing a full parse of the
50500   ** cell. If SQLCIPHER_DEBUG is defined, an assert() at the bottom of
50501   ** this function verifies that this invariant is not violated. */
50502   CellInfo debuginfo;
50503   btreeParseCellPtr(pPage, pCell, &debuginfo);
50504 #endif
50505
50506   if( pPage->intKey ){
50507     u8 *pEnd;
50508     if( pPage->hasData ){
50509       pIter += getVarint32(pIter, nSize);
50510     }else{
50511       nSize = 0;
50512     }
50513
50514     /* pIter now points at the 64-bit integer key value, a variable length 
50515     ** integer. The following block moves pIter to point at the first byte
50516     ** past the end of the key value. */
50517     pEnd = &pIter[9];
50518     while( (*pIter++)&0x80 && pIter<pEnd );
50519   }else{
50520     pIter += getVarint32(pIter, nSize);
50521   }
50522
50523   testcase( nSize==pPage->maxLocal );
50524   testcase( nSize==pPage->maxLocal+1 );
50525   if( nSize>pPage->maxLocal ){
50526     int minLocal = pPage->minLocal;
50527     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50528     testcase( nSize==pPage->maxLocal );
50529     testcase( nSize==pPage->maxLocal+1 );
50530     if( nSize>pPage->maxLocal ){
50531       nSize = minLocal;
50532     }
50533     nSize += 4;
50534   }
50535   nSize += (u32)(pIter - pCell);
50536
50537   /* The minimum size of any cell is 4 bytes. */
50538   if( nSize<4 ){
50539     nSize = 4;
50540   }
50541
50542   assert( nSize==debuginfo.nSize );
50543   return (u16)nSize;
50544 }
50545
50546 #ifdef SQLCIPHER_DEBUG
50547 /* This variation on cellSizePtr() is used inside of assert() statements
50548 ** only. */
50549 static u16 cellSize(MemPage *pPage, int iCell){
50550   return cellSizePtr(pPage, findCell(pPage, iCell));
50551 }
50552 #endif
50553
50554 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
50555 /*
50556 ** If the cell pCell, part of page pPage contains a pointer
50557 ** to an overflow page, insert an entry into the pointer-map
50558 ** for the overflow page.
50559 */
50560 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50561   CellInfo info;
50562   if( *pRC ) return;
50563   assert( pCell!=0 );
50564   btreeParseCellPtr(pPage, pCell, &info);
50565   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50566   if( info.iOverflow ){
50567     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50568     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50569   }
50570 }
50571 #endif
50572
50573
50574 /*
50575 ** Defragment the page given.  All Cells are moved to the
50576 ** end of the page and all free space is collected into one
50577 ** big FreeBlk that occurs in between the header and cell
50578 ** pointer array and the cell content area.
50579 */
50580 static int defragmentPage(MemPage *pPage){
50581   int i;                     /* Loop counter */
50582   int pc;                    /* Address of a i-th cell */
50583   int hdr;                   /* Offset to the page header */
50584   int size;                  /* Size of a cell */
50585   int usableSize;            /* Number of usable bytes on a page */
50586   int cellOffset;            /* Offset to the cell pointer array */
50587   int cbrk;                  /* Offset to the cell content area */
50588   int nCell;                 /* Number of cells on the page */
50589   unsigned char *data;       /* The page data */
50590   unsigned char *temp;       /* Temp area for cell content */
50591   int iCellFirst;            /* First allowable cell index */
50592   int iCellLast;             /* Last possible cell index */
50593
50594
50595   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50596   assert( pPage->pBt!=0 );
50597   assert( pPage->pBt->usableSize <= SQLCIPHER_MAX_PAGE_SIZE );
50598   assert( pPage->nOverflow==0 );
50599   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50600   temp = sqlcipher3PagerTempSpace(pPage->pBt->pPager);
50601   data = pPage->aData;
50602   hdr = pPage->hdrOffset;
50603   cellOffset = pPage->cellOffset;
50604   nCell = pPage->nCell;
50605   assert( nCell==get2byte(&data[hdr+3]) );
50606   usableSize = pPage->pBt->usableSize;
50607   cbrk = get2byte(&data[hdr+5]);
50608   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50609   cbrk = usableSize;
50610   iCellFirst = cellOffset + 2*nCell;
50611   iCellLast = usableSize - 4;
50612   for(i=0; i<nCell; i++){
50613     u8 *pAddr;     /* The i-th cell pointer */
50614     pAddr = &data[cellOffset + i*2];
50615     pc = get2byte(pAddr);
50616     testcase( pc==iCellFirst );
50617     testcase( pc==iCellLast );
50618 #if !defined(SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK)
50619     /* These conditions have already been verified in btreeInitPage()
50620     ** if SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK is defined 
50621     */
50622     if( pc<iCellFirst || pc>iCellLast ){
50623       return SQLCIPHER_CORRUPT_BKPT;
50624     }
50625 #endif
50626     assert( pc>=iCellFirst && pc<=iCellLast );
50627     size = cellSizePtr(pPage, &temp[pc]);
50628     cbrk -= size;
50629 #if defined(SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK)
50630     if( cbrk<iCellFirst ){
50631       return SQLCIPHER_CORRUPT_BKPT;
50632     }
50633 #else
50634     if( cbrk<iCellFirst || pc+size>usableSize ){
50635       return SQLCIPHER_CORRUPT_BKPT;
50636     }
50637 #endif
50638     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50639     testcase( cbrk+size==usableSize );
50640     testcase( pc+size==usableSize );
50641     memcpy(&data[cbrk], &temp[pc], size);
50642     put2byte(pAddr, cbrk);
50643   }
50644   assert( cbrk>=iCellFirst );
50645   put2byte(&data[hdr+5], cbrk);
50646   data[hdr+1] = 0;
50647   data[hdr+2] = 0;
50648   data[hdr+7] = 0;
50649   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50650   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50651   if( cbrk-iCellFirst!=pPage->nFree ){
50652     return SQLCIPHER_CORRUPT_BKPT;
50653   }
50654   return SQLCIPHER_OK;
50655 }
50656
50657 /*
50658 ** Allocate nByte bytes of space from within the B-Tree page passed
50659 ** as the first argument. Write into *pIdx the index into pPage->aData[]
50660 ** of the first byte of allocated space. Return either SQLCIPHER_OK or
50661 ** an error code (usually SQLCIPHER_CORRUPT).
50662 **
50663 ** The caller guarantees that there is sufficient space to make the
50664 ** allocation.  This routine might need to defragment in order to bring
50665 ** all the space together, however.  This routine will avoid using
50666 ** the first two bytes past the cell pointer area since presumably this
50667 ** allocation is being made in order to insert a new cell, so we will
50668 ** also end up needing a new cell pointer.
50669 */
50670 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50671   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
50672   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
50673   int nFrag;                           /* Number of fragmented bytes on pPage */
50674   int top;                             /* First byte of cell content area */
50675   int gap;        /* First byte of gap between cell pointers and cell content */
50676   int rc;         /* Integer return code */
50677   int usableSize; /* Usable size of the page */
50678   
50679   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50680   assert( pPage->pBt );
50681   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50682   assert( nByte>=0 );  /* Minimum cell size is 4 */
50683   assert( pPage->nFree>=nByte );
50684   assert( pPage->nOverflow==0 );
50685   usableSize = pPage->pBt->usableSize;
50686   assert( nByte < usableSize-8 );
50687
50688   nFrag = data[hdr+7];
50689   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50690   gap = pPage->cellOffset + 2*pPage->nCell;
50691   top = get2byteNotZero(&data[hdr+5]);
50692   if( gap>top ) return SQLCIPHER_CORRUPT_BKPT;
50693   testcase( gap+2==top );
50694   testcase( gap+1==top );
50695   testcase( gap==top );
50696
50697   if( nFrag>=60 ){
50698     /* Always defragment highly fragmented pages */
50699     rc = defragmentPage(pPage);
50700     if( rc ) return rc;
50701     top = get2byteNotZero(&data[hdr+5]);
50702   }else if( gap+2<=top ){
50703     /* Search the freelist looking for a free slot big enough to satisfy 
50704     ** the request. The allocation is made from the first free slot in 
50705     ** the list that is large enough to accomadate it.
50706     */
50707     int pc, addr;
50708     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50709       int size;            /* Size of the free slot */
50710       if( pc>usableSize-4 || pc<addr+4 ){
50711         return SQLCIPHER_CORRUPT_BKPT;
50712       }
50713       size = get2byte(&data[pc+2]);
50714       if( size>=nByte ){
50715         int x = size - nByte;
50716         testcase( x==4 );
50717         testcase( x==3 );
50718         if( x<4 ){
50719           /* Remove the slot from the free-list. Update the number of
50720           ** fragmented bytes within the page. */
50721           memcpy(&data[addr], &data[pc], 2);
50722           data[hdr+7] = (u8)(nFrag + x);
50723         }else if( size+pc > usableSize ){
50724           return SQLCIPHER_CORRUPT_BKPT;
50725         }else{
50726           /* The slot remains on the free-list. Reduce its size to account
50727           ** for the portion used by the new allocation. */
50728           put2byte(&data[pc+2], x);
50729         }
50730         *pIdx = pc + x;
50731         return SQLCIPHER_OK;
50732       }
50733     }
50734   }
50735
50736   /* Check to make sure there is enough space in the gap to satisfy
50737   ** the allocation.  If not, defragment.
50738   */
50739   testcase( gap+2+nByte==top );
50740   if( gap+2+nByte>top ){
50741     rc = defragmentPage(pPage);
50742     if( rc ) return rc;
50743     top = get2byteNotZero(&data[hdr+5]);
50744     assert( gap+nByte<=top );
50745   }
50746
50747
50748   /* Allocate memory from the gap in between the cell pointer array
50749   ** and the cell content area.  The btreeInitPage() call has already
50750   ** validated the freelist.  Given that the freelist is valid, there
50751   ** is no way that the allocation can extend off the end of the page.
50752   ** The assert() below verifies the previous sentence.
50753   */
50754   top -= nByte;
50755   put2byte(&data[hdr+5], top);
50756   assert( top+nByte <= (int)pPage->pBt->usableSize );
50757   *pIdx = top;
50758   return SQLCIPHER_OK;
50759 }
50760
50761 /*
50762 ** Return a section of the pPage->aData to the freelist.
50763 ** The first byte of the new free block is pPage->aDisk[start]
50764 ** and the size of the block is "size" bytes.
50765 **
50766 ** Most of the effort here is involved in coalesing adjacent
50767 ** free blocks into a single big free block.
50768 */
50769 static int freeSpace(MemPage *pPage, int start, int size){
50770   int addr, pbegin, hdr;
50771   int iLast;                        /* Largest possible freeblock offset */
50772   unsigned char *data = pPage->aData;
50773
50774   assert( pPage->pBt!=0 );
50775   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50776   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50777   assert( (start + size) <= (int)pPage->pBt->usableSize );
50778   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50779   assert( size>=0 );   /* Minimum cell size is 4 */
50780
50781   if( pPage->pBt->secureDelete ){
50782     /* Overwrite deleted information with zeros when the secure_delete
50783     ** option is enabled */
50784     memset(&data[start], 0, size);
50785   }
50786
50787   /* Add the space back into the linked list of freeblocks.  Note that
50788   ** even though the freeblock list was checked by btreeInitPage(),
50789   ** btreeInitPage() did not detect overlapping cells or
50790   ** freeblocks that overlapped cells.   Nor does it detect when the
50791   ** cell content area exceeds the value in the page header.  If these
50792   ** situations arise, then subsequent insert operations might corrupt
50793   ** the freelist.  So we do need to check for corruption while scanning
50794   ** the freelist.
50795   */
50796   hdr = pPage->hdrOffset;
50797   addr = hdr + 1;
50798   iLast = pPage->pBt->usableSize - 4;
50799   assert( start<=iLast );
50800   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50801     if( pbegin<addr+4 ){
50802       return SQLCIPHER_CORRUPT_BKPT;
50803     }
50804     addr = pbegin;
50805   }
50806   if( pbegin>iLast ){
50807     return SQLCIPHER_CORRUPT_BKPT;
50808   }
50809   assert( pbegin>addr || pbegin==0 );
50810   put2byte(&data[addr], start);
50811   put2byte(&data[start], pbegin);
50812   put2byte(&data[start+2], size);
50813   pPage->nFree = pPage->nFree + (u16)size;
50814
50815   /* Coalesce adjacent free blocks */
50816   addr = hdr + 1;
50817   while( (pbegin = get2byte(&data[addr]))>0 ){
50818     int pnext, psize, x;
50819     assert( pbegin>addr );
50820     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50821     pnext = get2byte(&data[pbegin]);
50822     psize = get2byte(&data[pbegin+2]);
50823     if( pbegin + psize + 3 >= pnext && pnext>0 ){
50824       int frag = pnext - (pbegin+psize);
50825       if( (frag<0) || (frag>(int)data[hdr+7]) ){
50826         return SQLCIPHER_CORRUPT_BKPT;
50827       }
50828       data[hdr+7] -= (u8)frag;
50829       x = get2byte(&data[pnext]);
50830       put2byte(&data[pbegin], x);
50831       x = pnext + get2byte(&data[pnext+2]) - pbegin;
50832       put2byte(&data[pbegin+2], x);
50833     }else{
50834       addr = pbegin;
50835     }
50836   }
50837
50838   /* If the cell content area begins with a freeblock, remove it. */
50839   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50840     int top;
50841     pbegin = get2byte(&data[hdr+1]);
50842     memcpy(&data[hdr+1], &data[pbegin], 2);
50843     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50844     put2byte(&data[hdr+5], top);
50845   }
50846   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
50847   return SQLCIPHER_OK;
50848 }
50849
50850 /*
50851 ** Decode the flags byte (the first byte of the header) for a page
50852 ** and initialize fields of the MemPage structure accordingly.
50853 **
50854 ** Only the following combinations are supported.  Anything different
50855 ** indicates a corrupt database files:
50856 **
50857 **         PTF_ZERODATA
50858 **         PTF_ZERODATA | PTF_LEAF
50859 **         PTF_LEAFDATA | PTF_INTKEY
50860 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50861 */
50862 static int decodeFlags(MemPage *pPage, int flagByte){
50863   BtShared *pBt;     /* A copy of pPage->pBt */
50864
50865   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50866   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50867   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
50868   flagByte &= ~PTF_LEAF;
50869   pPage->childPtrSize = 4-4*pPage->leaf;
50870   pBt = pPage->pBt;
50871   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50872     pPage->intKey = 1;
50873     pPage->hasData = pPage->leaf;
50874     pPage->maxLocal = pBt->maxLeaf;
50875     pPage->minLocal = pBt->minLeaf;
50876   }else if( flagByte==PTF_ZERODATA ){
50877     pPage->intKey = 0;
50878     pPage->hasData = 0;
50879     pPage->maxLocal = pBt->maxLocal;
50880     pPage->minLocal = pBt->minLocal;
50881   }else{
50882     return SQLCIPHER_CORRUPT_BKPT;
50883   }
50884   return SQLCIPHER_OK;
50885 }
50886
50887 /*
50888 ** Initialize the auxiliary information for a disk block.
50889 **
50890 ** Return SQLCIPHER_OK on success.  If we see that the page does
50891 ** not contain a well-formed database page, then return 
50892 ** SQLCIPHER_CORRUPT.  Note that a return of SQLCIPHER_OK does not
50893 ** guarantee that the page is well-formed.  It only shows that
50894 ** we failed to detect any corruption.
50895 */
50896 static int btreeInitPage(MemPage *pPage){
50897
50898   assert( pPage->pBt!=0 );
50899   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
50900   assert( pPage->pgno==sqlcipher3PagerPagenumber(pPage->pDbPage) );
50901   assert( pPage == sqlcipher3PagerGetExtra(pPage->pDbPage) );
50902   assert( pPage->aData == sqlcipher3PagerGetData(pPage->pDbPage) );
50903
50904   if( !pPage->isInit ){
50905     u16 pc;            /* Address of a freeblock within pPage->aData[] */
50906     u8 hdr;            /* Offset to beginning of page header */
50907     u8 *data;          /* Equal to pPage->aData */
50908     BtShared *pBt;        /* The main btree structure */
50909     int usableSize;    /* Amount of usable space on each page */
50910     u16 cellOffset;    /* Offset from start of page to first cell pointer */
50911     int nFree;         /* Number of unused bytes on the page */
50912     int top;           /* First byte of the cell content area */
50913     int iCellFirst;    /* First allowable cell or freeblock offset */
50914     int iCellLast;     /* Last possible cell or freeblock offset */
50915
50916     pBt = pPage->pBt;
50917
50918     hdr = pPage->hdrOffset;
50919     data = pPage->aData;
50920     if( decodeFlags(pPage, data[hdr]) ) return SQLCIPHER_CORRUPT_BKPT;
50921     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50922     pPage->maskPage = (u16)(pBt->pageSize - 1);
50923     pPage->nOverflow = 0;
50924     usableSize = pBt->usableSize;
50925     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
50926     top = get2byteNotZero(&data[hdr+5]);
50927     pPage->nCell = get2byte(&data[hdr+3]);
50928     if( pPage->nCell>MX_CELL(pBt) ){
50929       /* To many cells for a single page.  The page must be corrupt */
50930       return SQLCIPHER_CORRUPT_BKPT;
50931     }
50932     testcase( pPage->nCell==MX_CELL(pBt) );
50933
50934     /* A malformed database page might cause us to read past the end
50935     ** of page when parsing a cell.  
50936     **
50937     ** The following block of code checks early to see if a cell extends
50938     ** past the end of a page boundary and causes SQLCIPHER_CORRUPT to be 
50939     ** returned if it does.
50940     */
50941     iCellFirst = cellOffset + 2*pPage->nCell;
50942     iCellLast = usableSize - 4;
50943 #if defined(SQLCIPHER_ENABLE_OVERSIZE_CELL_CHECK)
50944     {
50945       int i;            /* Index into the cell pointer array */
50946       int sz;           /* Size of a cell */
50947
50948       if( !pPage->leaf ) iCellLast--;
50949       for(i=0; i<pPage->nCell; i++){
50950         pc = get2byte(&data[cellOffset+i*2]);
50951         testcase( pc==iCellFirst );
50952         testcase( pc==iCellLast );
50953         if( pc<iCellFirst || pc>iCellLast ){
50954           return SQLCIPHER_CORRUPT_BKPT;
50955         }
50956         sz = cellSizePtr(pPage, &data[pc]);
50957         testcase( pc+sz==usableSize );
50958         if( pc+sz>usableSize ){
50959           return SQLCIPHER_CORRUPT_BKPT;
50960         }
50961       }
50962       if( !pPage->leaf ) iCellLast++;
50963     }  
50964 #endif
50965
50966     /* Compute the total free space on the page */
50967     pc = get2byte(&data[hdr+1]);
50968     nFree = data[hdr+7] + top;
50969     while( pc>0 ){
50970       u16 next, size;
50971       if( pc<iCellFirst || pc>iCellLast ){
50972         /* Start of free block is off the page */
50973         return SQLCIPHER_CORRUPT_BKPT; 
50974       }
50975       next = get2byte(&data[pc]);
50976       size = get2byte(&data[pc+2]);
50977       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
50978         /* Free blocks must be in ascending order. And the last byte of
50979         ** the free-block must lie on the database page.  */
50980         return SQLCIPHER_CORRUPT_BKPT; 
50981       }
50982       nFree = nFree + size;
50983       pc = next;
50984     }
50985
50986     /* At this point, nFree contains the sum of the offset to the start
50987     ** of the cell-content area plus the number of free bytes within
50988     ** the cell-content area. If this is greater than the usable-size
50989     ** of the page, then the page must be corrupted. This check also
50990     ** serves to verify that the offset to the start of the cell-content
50991     ** area, according to the page header, lies within the page.
50992     */
50993     if( nFree>usableSize ){
50994       return SQLCIPHER_CORRUPT_BKPT; 
50995     }
50996     pPage->nFree = (u16)(nFree - iCellFirst);
50997     pPage->isInit = 1;
50998   }
50999   return SQLCIPHER_OK;
51000 }
51001
51002 /*
51003 ** Set up a raw page so that it looks like a database page holding
51004 ** no entries.
51005 */
51006 static void zeroPage(MemPage *pPage, int flags){
51007   unsigned char *data = pPage->aData;
51008   BtShared *pBt = pPage->pBt;
51009   u8 hdr = pPage->hdrOffset;
51010   u16 first;
51011
51012   assert( sqlcipher3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
51013   assert( sqlcipher3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51014   assert( sqlcipher3PagerGetData(pPage->pDbPage) == data );
51015   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
51016   assert( sqlcipher3_mutex_held(pBt->mutex) );
51017   if( pBt->secureDelete ){
51018     memset(&data[hdr], 0, pBt->usableSize - hdr);
51019   }
51020   data[hdr] = (char)flags;
51021   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
51022   memset(&data[hdr+1], 0, 4);
51023   data[hdr+7] = 0;
51024   put2byte(&data[hdr+5], pBt->usableSize);
51025   pPage->nFree = (u16)(pBt->usableSize - first);
51026   decodeFlags(pPage, flags);
51027   pPage->hdrOffset = hdr;
51028   pPage->cellOffset = first;
51029   pPage->nOverflow = 0;
51030   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51031   pPage->maskPage = (u16)(pBt->pageSize - 1);
51032   pPage->nCell = 0;
51033   pPage->isInit = 1;
51034 }
51035
51036
51037 /*
51038 ** Convert a DbPage obtained from the pager into a MemPage used by
51039 ** the btree layer.
51040 */
51041 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51042   MemPage *pPage = (MemPage*)sqlcipher3PagerGetExtra(pDbPage);
51043   pPage->aData = sqlcipher3PagerGetData(pDbPage);
51044   pPage->pDbPage = pDbPage;
51045   pPage->pBt = pBt;
51046   pPage->pgno = pgno;
51047   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51048   return pPage; 
51049 }
51050
51051 /*
51052 ** Get a page from the pager.  Initialize the MemPage.pBt and
51053 ** MemPage.aData elements if needed.
51054 **
51055 ** If the noContent flag is set, it means that we do not care about
51056 ** the content of the page at this time.  So do not go to the disk
51057 ** to fetch the content.  Just fill in the content with zeros for now.
51058 ** If in the future we call sqlcipher3PagerWrite() on this page, that
51059 ** means we have started to be concerned about content and the disk
51060 ** read should occur at that point.
51061 */
51062 static int btreeGetPage(
51063   BtShared *pBt,       /* The btree */
51064   Pgno pgno,           /* Number of the page to fetch */
51065   MemPage **ppPage,    /* Return the page in this parameter */
51066   int noContent        /* Do not load page content if true */
51067 ){
51068   int rc;
51069   DbPage *pDbPage;
51070
51071   assert( sqlcipher3_mutex_held(pBt->mutex) );
51072   rc = sqlcipher3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
51073   if( rc ) return rc;
51074   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51075   return SQLCIPHER_OK;
51076 }
51077
51078 /*
51079 ** Retrieve a page from the pager cache. If the requested page is not
51080 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
51081 ** MemPage.aData elements if needed.
51082 */
51083 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51084   DbPage *pDbPage;
51085   assert( sqlcipher3_mutex_held(pBt->mutex) );
51086   pDbPage = sqlcipher3PagerLookup(pBt->pPager, pgno);
51087   if( pDbPage ){
51088     return btreePageFromDbPage(pDbPage, pgno, pBt);
51089   }
51090   return 0;
51091 }
51092
51093 /*
51094 ** Return the size of the database file in pages. If there is any kind of
51095 ** error, return ((unsigned int)-1).
51096 */
51097 static Pgno btreePagecount(BtShared *pBt){
51098   return pBt->nPage;
51099 }
51100 SQLCIPHER_PRIVATE u32 sqlcipher3BtreeLastPage(Btree *p){
51101   assert( sqlcipher3BtreeHoldsMutex(p) );
51102   assert( ((p->pBt->nPage)&0x8000000)==0 );
51103   return (int)btreePagecount(p->pBt);
51104 }
51105
51106 /*
51107 ** Get a page from the pager and initialize it.  This routine is just a
51108 ** convenience wrapper around separate calls to btreeGetPage() and 
51109 ** btreeInitPage().
51110 **
51111 ** If an error occurs, then the value *ppPage is set to is undefined. It
51112 ** may remain unchanged, or it may be set to an invalid value.
51113 */
51114 static int getAndInitPage(
51115   BtShared *pBt,          /* The database file */
51116   Pgno pgno,           /* Number of the page to get */
51117   MemPage **ppPage     /* Write the page pointer here */
51118 ){
51119   int rc;
51120   assert( sqlcipher3_mutex_held(pBt->mutex) );
51121
51122   if( pgno>btreePagecount(pBt) ){
51123     rc = SQLCIPHER_CORRUPT_BKPT;
51124   }else{
51125     rc = btreeGetPage(pBt, pgno, ppPage, 0);
51126     if( rc==SQLCIPHER_OK ){
51127       rc = btreeInitPage(*ppPage);
51128       if( rc!=SQLCIPHER_OK ){
51129         releasePage(*ppPage);
51130       }
51131     }
51132   }
51133
51134   testcase( pgno==0 );
51135   assert( pgno!=0 || rc==SQLCIPHER_CORRUPT );
51136   return rc;
51137 }
51138
51139 /*
51140 ** Release a MemPage.  This should be called once for each prior
51141 ** call to btreeGetPage.
51142 */
51143 static void releasePage(MemPage *pPage){
51144   if( pPage ){
51145     assert( pPage->aData );
51146     assert( pPage->pBt );
51147     assert( sqlcipher3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51148     assert( sqlcipher3PagerGetData(pPage->pDbPage)==pPage->aData );
51149     assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
51150     sqlcipher3PagerUnref(pPage->pDbPage);
51151   }
51152 }
51153
51154 /*
51155 ** During a rollback, when the pager reloads information into the cache
51156 ** so that the cache is restored to its original state at the start of
51157 ** the transaction, for each page restored this routine is called.
51158 **
51159 ** This routine needs to reset the extra data section at the end of the
51160 ** page to agree with the restored data.
51161 */
51162 static void pageReinit(DbPage *pData){
51163   MemPage *pPage;
51164   pPage = (MemPage *)sqlcipher3PagerGetExtra(pData);
51165   assert( sqlcipher3PagerPageRefcount(pData)>0 );
51166   if( pPage->isInit ){
51167     assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
51168     pPage->isInit = 0;
51169     if( sqlcipher3PagerPageRefcount(pData)>1 ){
51170       /* pPage might not be a btree page;  it might be an overflow page
51171       ** or ptrmap page or a free page.  In those cases, the following
51172       ** call to btreeInitPage() will likely return SQLCIPHER_CORRUPT.
51173       ** But no harm is done by this.  And it is very important that
51174       ** btreeInitPage() be called on every btree page so we make
51175       ** the call for every page that comes in for re-initing. */
51176       btreeInitPage(pPage);
51177     }
51178   }
51179 }
51180
51181 /*
51182 ** Invoke the busy handler for a btree.
51183 */
51184 static int btreeInvokeBusyHandler(void *pArg){
51185   BtShared *pBt = (BtShared*)pArg;
51186   assert( pBt->db );
51187   assert( sqlcipher3_mutex_held(pBt->db->mutex) );
51188   return sqlcipher3InvokeBusyHandler(&pBt->db->busyHandler);
51189 }
51190
51191 /*
51192 ** Open a database file.
51193 ** 
51194 ** zFilename is the name of the database file.  If zFilename is NULL
51195 ** then an ephemeral database is created.  The ephemeral database might
51196 ** be exclusively in memory, or it might use a disk-based memory cache.
51197 ** Either way, the ephemeral database will be automatically deleted 
51198 ** when sqlcipher3BtreeClose() is called.
51199 **
51200 ** If zFilename is ":memory:" then an in-memory database is created
51201 ** that is automatically destroyed when it is closed.
51202 **
51203 ** The "flags" parameter is a bitmask that might contain bits
51204 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
51205 ** bit is also set if the SQLCIPHER_NoReadlock flags is set in db->flags.
51206 ** These flags are passed through into sqlcipher3PagerOpen() and must
51207 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
51208 **
51209 ** If the database is already opened in the same database connection
51210 ** and we are in shared cache mode, then the open will fail with an
51211 ** SQLCIPHER_CONSTRAINT error.  We cannot allow two or more BtShared
51212 ** objects in the same database connection since doing so will lead
51213 ** to problems with locking.
51214 */
51215 SQLCIPHER_PRIVATE int sqlcipher3BtreeOpen(
51216   sqlcipher3_vfs *pVfs,      /* VFS to use for this b-tree */
51217   const char *zFilename,  /* Name of the file containing the BTree database */
51218   sqlcipher3 *db,            /* Associated database handle */
51219   Btree **ppBtree,        /* Pointer to new Btree object written here */
51220   int flags,              /* Options */
51221   int vfsFlags            /* Flags passed through to sqlcipher3_vfs.xOpen() */
51222 ){
51223   BtShared *pBt = 0;             /* Shared part of btree structure */
51224   Btree *p;                      /* Handle to return */
51225   sqlcipher3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51226   int rc = SQLCIPHER_OK;            /* Result code from this function */
51227   u8 nReserve;                   /* Byte of unused space on each page */
51228   unsigned char zDbHeader[100];  /* Database header content */
51229
51230   /* True if opening an ephemeral, temporary database */
51231   const int isTempDb = zFilename==0 || zFilename[0]==0;
51232
51233   /* Set the variable isMemdb to true for an in-memory database, or 
51234   ** false for a file-based database.
51235   */
51236 #ifdef SQLCIPHER_OMIT_MEMORYDB
51237   const int isMemdb = 0;
51238 #else
51239   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51240                        || (isTempDb && sqlcipher3TempInMemory(db));
51241 #endif
51242
51243   assert( db!=0 );
51244   assert( pVfs!=0 );
51245   assert( sqlcipher3_mutex_held(db->mutex) );
51246   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51247
51248   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51249   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51250
51251   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51252   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51253
51254   if( db->flags & SQLCIPHER_NoReadlock ){
51255     flags |= BTREE_NO_READLOCK;
51256   }
51257   if( isMemdb ){
51258     flags |= BTREE_MEMORY;
51259   }
51260   if( (vfsFlags & SQLCIPHER_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51261     vfsFlags = (vfsFlags & ~SQLCIPHER_OPEN_MAIN_DB) | SQLCIPHER_OPEN_TEMP_DB;
51262   }
51263   p = sqlcipher3MallocZero(sizeof(Btree));
51264   if( !p ){
51265     return SQLCIPHER_NOMEM;
51266   }
51267   p->inTrans = TRANS_NONE;
51268   p->db = db;
51269 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
51270   p->lock.pBtree = p;
51271   p->lock.iTable = 1;
51272 #endif
51273
51274 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && !defined(SQLCIPHER_OMIT_DISKIO)
51275   /*
51276   ** If this Btree is a candidate for shared cache, try to find an
51277   ** existing BtShared object that we can share with
51278   */
51279   if( isMemdb==0 && isTempDb==0 ){
51280     if( vfsFlags & SQLCIPHER_OPEN_SHAREDCACHE ){
51281       int nFullPathname = pVfs->mxPathname+1;
51282       char *zFullPathname = sqlcipher3Malloc(nFullPathname);
51283       MUTEX_LOGIC( sqlcipher3_mutex *mutexShared; )
51284       p->sharable = 1;
51285       if( !zFullPathname ){
51286         sqlcipher3_free(p);
51287         return SQLCIPHER_NOMEM;
51288       }
51289       sqlcipher3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
51290 #if SQLCIPHER_THREADSAFE
51291       mutexOpen = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_OPEN);
51292       sqlcipher3_mutex_enter(mutexOpen);
51293       mutexShared = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
51294       sqlcipher3_mutex_enter(mutexShared);
51295 #endif
51296       for(pBt=GLOBAL(BtShared*,sqlcipher3SharedCacheList); pBt; pBt=pBt->pNext){
51297         assert( pBt->nRef>0 );
51298         if( 0==strcmp(zFullPathname, sqlcipher3PagerFilename(pBt->pPager))
51299                  && sqlcipher3PagerVfs(pBt->pPager)==pVfs ){
51300           int iDb;
51301           for(iDb=db->nDb-1; iDb>=0; iDb--){
51302             Btree *pExisting = db->aDb[iDb].pBt;
51303             if( pExisting && pExisting->pBt==pBt ){
51304               sqlcipher3_mutex_leave(mutexShared);
51305               sqlcipher3_mutex_leave(mutexOpen);
51306               sqlcipher3_free(zFullPathname);
51307               sqlcipher3_free(p);
51308               return SQLCIPHER_CONSTRAINT;
51309             }
51310           }
51311           p->pBt = pBt;
51312           pBt->nRef++;
51313           break;
51314         }
51315       }
51316       sqlcipher3_mutex_leave(mutexShared);
51317       sqlcipher3_free(zFullPathname);
51318     }
51319 #ifdef SQLCIPHER_DEBUG
51320     else{
51321       /* In debug mode, we mark all persistent databases as sharable
51322       ** even when they are not.  This exercises the locking code and
51323       ** gives more opportunity for asserts(sqlcipher3_mutex_held())
51324       ** statements to find locking problems.
51325       */
51326       p->sharable = 1;
51327     }
51328 #endif
51329   }
51330 #endif
51331   if( pBt==0 ){
51332     /*
51333     ** The following asserts make sure that structures used by the btree are
51334     ** the right size.  This is to guard against size changes that result
51335     ** when compiling on a different architecture.
51336     */
51337     assert( sizeof(i64)==8 || sizeof(i64)==4 );
51338     assert( sizeof(u64)==8 || sizeof(u64)==4 );
51339     assert( sizeof(u32)==4 );
51340     assert( sizeof(u16)==2 );
51341     assert( sizeof(Pgno)==4 );
51342   
51343     pBt = sqlcipher3MallocZero( sizeof(*pBt) );
51344     if( pBt==0 ){
51345       rc = SQLCIPHER_NOMEM;
51346       goto btree_open_out;
51347     }
51348     rc = sqlcipher3PagerOpen(pVfs, &pBt->pPager, zFilename,
51349                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
51350     if( rc==SQLCIPHER_OK ){
51351       rc = sqlcipher3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51352     }
51353     if( rc!=SQLCIPHER_OK ){
51354       goto btree_open_out;
51355     }
51356     pBt->openFlags = (u8)flags;
51357     pBt->db = db;
51358     sqlcipher3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51359     p->pBt = pBt;
51360   
51361     pBt->pCursor = 0;
51362     pBt->pPage1 = 0;
51363     pBt->readOnly = sqlcipher3PagerIsreadonly(pBt->pPager);
51364 #ifdef SQLCIPHER_SECURE_DELETE
51365     pBt->secureDelete = 1;
51366 #endif
51367     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51368     if( pBt->pageSize<512 || pBt->pageSize>SQLCIPHER_MAX_PAGE_SIZE
51369          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51370       pBt->pageSize = 0;
51371 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51372       /* If the magic name ":memory:" will create an in-memory database, then
51373       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51374       ** SQLCIPHER_DEFAULT_AUTOVACUUM is true. On the other hand, if
51375       ** SQLCIPHER_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51376       ** regular file-name. In this case the auto-vacuum applies as per normal.
51377       */
51378       if( zFilename && !isMemdb ){
51379         pBt->autoVacuum = (SQLCIPHER_DEFAULT_AUTOVACUUM ? 1 : 0);
51380         pBt->incrVacuum = (SQLCIPHER_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51381       }
51382 #endif
51383       nReserve = 0;
51384     }else{
51385       nReserve = zDbHeader[20];
51386       pBt->pageSizeFixed = 1;
51387 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51388       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51389       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51390 #endif
51391     }
51392     rc = sqlcipher3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51393     if( rc ) goto btree_open_out;
51394     pBt->usableSize = pBt->pageSize - nReserve;
51395     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51396    
51397 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && !defined(SQLCIPHER_OMIT_DISKIO)
51398     /* Add the new BtShared object to the linked list sharable BtShareds.
51399     */
51400     if( p->sharable ){
51401       MUTEX_LOGIC( sqlcipher3_mutex *mutexShared; )
51402       pBt->nRef = 1;
51403       MUTEX_LOGIC( mutexShared = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);)
51404       if( SQLCIPHER_THREADSAFE && sqlcipher3GlobalConfig.bCoreMutex ){
51405         pBt->mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_FAST);
51406         if( pBt->mutex==0 ){
51407           rc = SQLCIPHER_NOMEM;
51408           db->mallocFailed = 0;
51409           goto btree_open_out;
51410         }
51411       }
51412       sqlcipher3_mutex_enter(mutexShared);
51413       pBt->pNext = GLOBAL(BtShared*,sqlcipher3SharedCacheList);
51414       GLOBAL(BtShared*,sqlcipher3SharedCacheList) = pBt;
51415       sqlcipher3_mutex_leave(mutexShared);
51416     }
51417 #endif
51418   }
51419
51420 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && !defined(SQLCIPHER_OMIT_DISKIO)
51421   /* If the new Btree uses a sharable pBtShared, then link the new
51422   ** Btree into the list of all sharable Btrees for the same connection.
51423   ** The list is kept in ascending order by pBt address.
51424   */
51425   if( p->sharable ){
51426     int i;
51427     Btree *pSib;
51428     for(i=0; i<db->nDb; i++){
51429       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51430         while( pSib->pPrev ){ pSib = pSib->pPrev; }
51431         if( p->pBt<pSib->pBt ){
51432           p->pNext = pSib;
51433           p->pPrev = 0;
51434           pSib->pPrev = p;
51435         }else{
51436           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51437             pSib = pSib->pNext;
51438           }
51439           p->pNext = pSib->pNext;
51440           p->pPrev = pSib;
51441           if( p->pNext ){
51442             p->pNext->pPrev = p;
51443           }
51444           pSib->pNext = p;
51445         }
51446         break;
51447       }
51448     }
51449   }
51450 #endif
51451   *ppBtree = p;
51452
51453 btree_open_out:
51454   if( rc!=SQLCIPHER_OK ){
51455     if( pBt && pBt->pPager ){
51456       sqlcipher3PagerClose(pBt->pPager);
51457     }
51458     sqlcipher3_free(pBt);
51459     sqlcipher3_free(p);
51460     *ppBtree = 0;
51461   }else{
51462     /* If the B-Tree was successfully opened, set the pager-cache size to the
51463     ** default value. Except, when opening on an existing shared pager-cache,
51464     ** do not change the pager-cache size.
51465     */
51466     if( sqlcipher3BtreeSchema(p, 0, 0)==0 ){
51467       sqlcipher3PagerSetCachesize(p->pBt->pPager, SQLCIPHER_DEFAULT_CACHE_SIZE);
51468     }
51469   }
51470   if( mutexOpen ){
51471     assert( sqlcipher3_mutex_held(mutexOpen) );
51472     sqlcipher3_mutex_leave(mutexOpen);
51473   }
51474   return rc;
51475 }
51476
51477 /*
51478 ** Decrement the BtShared.nRef counter.  When it reaches zero,
51479 ** remove the BtShared structure from the sharing list.  Return
51480 ** true if the BtShared.nRef counter reaches zero and return
51481 ** false if it is still positive.
51482 */
51483 static int removeFromSharingList(BtShared *pBt){
51484 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
51485   MUTEX_LOGIC( sqlcipher3_mutex *pMaster; )
51486   BtShared *pList;
51487   int removed = 0;
51488
51489   assert( sqlcipher3_mutex_notheld(pBt->mutex) );
51490   MUTEX_LOGIC( pMaster = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER); )
51491   sqlcipher3_mutex_enter(pMaster);
51492   pBt->nRef--;
51493   if( pBt->nRef<=0 ){
51494     if( GLOBAL(BtShared*,sqlcipher3SharedCacheList)==pBt ){
51495       GLOBAL(BtShared*,sqlcipher3SharedCacheList) = pBt->pNext;
51496     }else{
51497       pList = GLOBAL(BtShared*,sqlcipher3SharedCacheList);
51498       while( ALWAYS(pList) && pList->pNext!=pBt ){
51499         pList=pList->pNext;
51500       }
51501       if( ALWAYS(pList) ){
51502         pList->pNext = pBt->pNext;
51503       }
51504     }
51505     if( SQLCIPHER_THREADSAFE ){
51506       sqlcipher3_mutex_free(pBt->mutex);
51507     }
51508     removed = 1;
51509   }
51510   sqlcipher3_mutex_leave(pMaster);
51511   return removed;
51512 #else
51513   return 1;
51514 #endif
51515 }
51516
51517 /*
51518 ** Make sure pBt->pTmpSpace points to an allocation of 
51519 ** MX_CELL_SIZE(pBt) bytes.
51520 */
51521 static void allocateTempSpace(BtShared *pBt){
51522   if( !pBt->pTmpSpace ){
51523     pBt->pTmpSpace = sqlcipher3PageMalloc( pBt->pageSize );
51524   }
51525 }
51526
51527 /*
51528 ** Free the pBt->pTmpSpace allocation
51529 */
51530 static void freeTempSpace(BtShared *pBt){
51531   sqlcipher3PageFree( pBt->pTmpSpace);
51532   pBt->pTmpSpace = 0;
51533 }
51534
51535 /*
51536 ** Close an open database and invalidate all cursors.
51537 */
51538 SQLCIPHER_PRIVATE int sqlcipher3BtreeClose(Btree *p){
51539   BtShared *pBt = p->pBt;
51540   BtCursor *pCur;
51541
51542   /* Close all cursors opened via this handle.  */
51543   assert( sqlcipher3_mutex_held(p->db->mutex) );
51544   sqlcipher3BtreeEnter(p);
51545   pCur = pBt->pCursor;
51546   while( pCur ){
51547     BtCursor *pTmp = pCur;
51548     pCur = pCur->pNext;
51549     if( pTmp->pBtree==p ){
51550       sqlcipher3BtreeCloseCursor(pTmp);
51551     }
51552   }
51553
51554   /* Rollback any active transaction and free the handle structure.
51555   ** The call to sqlcipher3BtreeRollback() drops any table-locks held by
51556   ** this handle.
51557   */
51558   sqlcipher3BtreeRollback(p);
51559   sqlcipher3BtreeLeave(p);
51560
51561   /* If there are still other outstanding references to the shared-btree
51562   ** structure, return now. The remainder of this procedure cleans 
51563   ** up the shared-btree.
51564   */
51565   assert( p->wantToLock==0 && p->locked==0 );
51566   if( !p->sharable || removeFromSharingList(pBt) ){
51567     /* The pBt is no longer on the sharing list, so we can access
51568     ** it without having to hold the mutex.
51569     **
51570     ** Clean out and delete the BtShared object.
51571     */
51572     assert( !pBt->pCursor );
51573     sqlcipher3PagerClose(pBt->pPager);
51574     if( pBt->xFreeSchema && pBt->pSchema ){
51575       pBt->xFreeSchema(pBt->pSchema);
51576     }
51577     sqlcipher3DbFree(0, pBt->pSchema);
51578     freeTempSpace(pBt);
51579     sqlcipher3_free(pBt);
51580   }
51581
51582 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
51583   assert( p->wantToLock==0 );
51584   assert( p->locked==0 );
51585   if( p->pPrev ) p->pPrev->pNext = p->pNext;
51586   if( p->pNext ) p->pNext->pPrev = p->pPrev;
51587 #endif
51588
51589   sqlcipher3_free(p);
51590   return SQLCIPHER_OK;
51591 }
51592
51593 /*
51594 ** Change the limit on the number of pages allowed in the cache.
51595 **
51596 ** The maximum number of cache pages is set to the absolute
51597 ** value of mxPage.  If mxPage is negative, the pager will
51598 ** operate asynchronously - it will not stop to do fsync()s
51599 ** to insure data is written to the disk surface before
51600 ** continuing.  Transactions still work if synchronous is off,
51601 ** and the database cannot be corrupted if this program
51602 ** crashes.  But if the operating system crashes or there is
51603 ** an abrupt power failure when synchronous is off, the database
51604 ** could be left in an inconsistent and unrecoverable state.
51605 ** Synchronous is on by default so database corruption is not
51606 ** normally a worry.
51607 */
51608 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetCacheSize(Btree *p, int mxPage){
51609   BtShared *pBt = p->pBt;
51610   assert( sqlcipher3_mutex_held(p->db->mutex) );
51611   sqlcipher3BtreeEnter(p);
51612   sqlcipher3PagerSetCachesize(pBt->pPager, mxPage);
51613   sqlcipher3BtreeLeave(p);
51614   return SQLCIPHER_OK;
51615 }
51616
51617 /*
51618 ** Change the way data is synced to disk in order to increase or decrease
51619 ** how well the database resists damage due to OS crashes and power
51620 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
51621 ** there is a high probability of damage)  Level 2 is the default.  There
51622 ** is a very low but non-zero probability of damage.  Level 3 reduces the
51623 ** probability of damage to near zero but with a write performance reduction.
51624 */
51625 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
51626 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetSafetyLevel(
51627   Btree *p,              /* The btree to set the safety level on */
51628   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
51629   int fullSync,          /* PRAGMA fullfsync. */
51630   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
51631 ){
51632   BtShared *pBt = p->pBt;
51633   assert( sqlcipher3_mutex_held(p->db->mutex) );
51634   assert( level>=1 && level<=3 );
51635   sqlcipher3BtreeEnter(p);
51636   sqlcipher3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
51637   sqlcipher3BtreeLeave(p);
51638   return SQLCIPHER_OK;
51639 }
51640 #endif
51641
51642 /*
51643 ** Return TRUE if the given btree is set to safety level 1.  In other
51644 ** words, return TRUE if no sync() occurs on the disk files.
51645 */
51646 SQLCIPHER_PRIVATE int sqlcipher3BtreeSyncDisabled(Btree *p){
51647   BtShared *pBt = p->pBt;
51648   int rc;
51649   assert( sqlcipher3_mutex_held(p->db->mutex) );  
51650   sqlcipher3BtreeEnter(p);
51651   assert( pBt && pBt->pPager );
51652   rc = sqlcipher3PagerNosync(pBt->pPager);
51653   sqlcipher3BtreeLeave(p);
51654   return rc;
51655 }
51656
51657 /*
51658 ** Change the default pages size and the number of reserved bytes per page.
51659 ** Or, if the page size has already been fixed, return SQLCIPHER_READONLY 
51660 ** without changing anything.
51661 **
51662 ** The page size must be a power of 2 between 512 and 65536.  If the page
51663 ** size supplied does not meet this constraint then the page size is not
51664 ** changed.
51665 **
51666 ** Page sizes are constrained to be a power of two so that the region
51667 ** of the database file used for locking (beginning at PENDING_BYTE,
51668 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
51669 ** at the beginning of a page.
51670 **
51671 ** If parameter nReserve is less than zero, then the number of reserved
51672 ** bytes per page is left unchanged.
51673 **
51674 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
51675 ** and autovacuum mode can no longer be changed.
51676 */
51677 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51678   int rc = SQLCIPHER_OK;
51679   BtShared *pBt = p->pBt;
51680   assert( nReserve>=-1 && nReserve<=255 );
51681   sqlcipher3BtreeEnter(p);
51682   if( pBt->pageSizeFixed ){
51683     sqlcipher3BtreeLeave(p);
51684     return SQLCIPHER_READONLY;
51685   }
51686   if( nReserve<0 ){
51687     nReserve = pBt->pageSize - pBt->usableSize;
51688   }
51689   assert( nReserve>=0 && nReserve<=255 );
51690   if( pageSize>=512 && pageSize<=SQLCIPHER_MAX_PAGE_SIZE &&
51691         ((pageSize-1)&pageSize)==0 ){
51692     assert( (pageSize & 7)==0 );
51693     assert( !pBt->pPage1 && !pBt->pCursor );
51694     pBt->pageSize = (u32)pageSize;
51695     freeTempSpace(pBt);
51696   }
51697   rc = sqlcipher3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51698   pBt->usableSize = pBt->pageSize - (u16)nReserve;
51699   if( iFix ) pBt->pageSizeFixed = 1;
51700   sqlcipher3BtreeLeave(p);
51701   return rc;
51702 }
51703
51704 /*
51705 ** Return the currently defined page size
51706 */
51707 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetPageSize(Btree *p){
51708   return p->pBt->pageSize;
51709 }
51710
51711 #if !defined(SQLCIPHER_OMIT_PAGER_PRAGMAS) || !defined(SQLCIPHER_OMIT_VACUUM)
51712 /*
51713 ** Return the number of bytes of space at the end of every page that
51714 ** are intentually left unused.  This is the "reserved" space that is
51715 ** sometimes used by extensions.
51716 */
51717 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetReserve(Btree *p){
51718   int n;
51719   sqlcipher3BtreeEnter(p);
51720   n = p->pBt->pageSize - p->pBt->usableSize;
51721   sqlcipher3BtreeLeave(p);
51722   return n;
51723 }
51724
51725 /*
51726 ** Set the maximum page count for a database if mxPage is positive.
51727 ** No changes are made if mxPage is 0 or negative.
51728 ** Regardless of the value of mxPage, return the maximum page count.
51729 */
51730 SQLCIPHER_PRIVATE int sqlcipher3BtreeMaxPageCount(Btree *p, int mxPage){
51731   int n;
51732   sqlcipher3BtreeEnter(p);
51733   n = sqlcipher3PagerMaxPageCount(p->pBt->pPager, mxPage);
51734   sqlcipher3BtreeLeave(p);
51735   return n;
51736 }
51737
51738 /*
51739 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
51740 ** then make no changes.  Always return the value of the secureDelete
51741 ** setting after the change.
51742 */
51743 SQLCIPHER_PRIVATE int sqlcipher3BtreeSecureDelete(Btree *p, int newFlag){
51744   int b;
51745   if( p==0 ) return 0;
51746   sqlcipher3BtreeEnter(p);
51747   if( newFlag>=0 ){
51748     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
51749   } 
51750   b = p->pBt->secureDelete;
51751   sqlcipher3BtreeLeave(p);
51752   return b;
51753 }
51754 #endif /* !defined(SQLCIPHER_OMIT_PAGER_PRAGMAS) || !defined(SQLCIPHER_OMIT_VACUUM) */
51755
51756 /*
51757 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51758 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51759 ** is disabled. The default value for the auto-vacuum property is 
51760 ** determined by the SQLCIPHER_DEFAULT_AUTOVACUUM macro.
51761 */
51762 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51763 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
51764   return SQLCIPHER_READONLY;
51765 #else
51766   BtShared *pBt = p->pBt;
51767   int rc = SQLCIPHER_OK;
51768   u8 av = (u8)autoVacuum;
51769
51770   sqlcipher3BtreeEnter(p);
51771   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
51772     rc = SQLCIPHER_READONLY;
51773   }else{
51774     pBt->autoVacuum = av ?1:0;
51775     pBt->incrVacuum = av==2 ?1:0;
51776   }
51777   sqlcipher3BtreeLeave(p);
51778   return rc;
51779 #endif
51780 }
51781
51782 /*
51783 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
51784 ** enabled 1 is returned. Otherwise 0.
51785 */
51786 SQLCIPHER_PRIVATE int sqlcipher3BtreeGetAutoVacuum(Btree *p){
51787 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
51788   return BTREE_AUTOVACUUM_NONE;
51789 #else
51790   int rc;
51791   sqlcipher3BtreeEnter(p);
51792   rc = (
51793     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51794     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51795     BTREE_AUTOVACUUM_INCR
51796   );
51797   sqlcipher3BtreeLeave(p);
51798   return rc;
51799 #endif
51800 }
51801
51802
51803 /*
51804 ** Get a reference to pPage1 of the database file.  This will
51805 ** also acquire a readlock on that file.
51806 **
51807 ** SQLCIPHER_OK is returned on success.  If the file is not a
51808 ** well-formed database file, then SQLCIPHER_CORRUPT is returned.
51809 ** SQLCIPHER_BUSY is returned if the database is locked.  SQLCIPHER_NOMEM
51810 ** is returned if we run out of memory. 
51811 */
51812 static int lockBtree(BtShared *pBt){
51813   int rc;              /* Result code from subfunctions */
51814   MemPage *pPage1;     /* Page 1 of the database file */
51815   int nPage;           /* Number of pages in the database */
51816   int nPageFile = 0;   /* Number of pages in the database file */
51817   int nPageHeader;     /* Number of pages in the database according to hdr */
51818
51819   assert( sqlcipher3_mutex_held(pBt->mutex) );
51820   assert( pBt->pPage1==0 );
51821   rc = sqlcipher3PagerSharedLock(pBt->pPager);
51822   if( rc!=SQLCIPHER_OK ) return rc;
51823   rc = btreeGetPage(pBt, 1, &pPage1, 0);
51824   if( rc!=SQLCIPHER_OK ) return rc;
51825
51826   /* Do some checking to help insure the file we opened really is
51827   ** a valid database file. 
51828   */
51829   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51830   sqlcipher3PagerPagecount(pBt->pPager, &nPageFile);
51831   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51832     nPage = nPageFile;
51833   }
51834   if( nPage>0 ){
51835     u32 pageSize;
51836     u32 usableSize;
51837     u8 *page1 = pPage1->aData;
51838     rc = SQLCIPHER_NOTADB;
51839     if( memcmp(page1, zMagicHeader, 16)!=0 ){
51840       goto page1_init_failed;
51841     }
51842
51843 #ifdef SQLCIPHER_OMIT_WAL
51844     if( page1[18]>1 ){
51845       pBt->readOnly = 1;
51846     }
51847     if( page1[19]>1 ){
51848       goto page1_init_failed;
51849     }
51850 #else
51851     if( page1[18]>2 ){
51852       pBt->readOnly = 1;
51853     }
51854     if( page1[19]>2 ){
51855       goto page1_init_failed;
51856     }
51857
51858     /* If the write version is set to 2, this database should be accessed
51859     ** in WAL mode. If the log is not already open, open it now. Then 
51860     ** return SQLCIPHER_OK and return without populating BtShared.pPage1.
51861     ** The caller detects this and calls this function again. This is
51862     ** required as the version of page 1 currently in the page1 buffer
51863     ** may not be the latest version - there may be a newer one in the log
51864     ** file.
51865     */
51866     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
51867       int isOpen = 0;
51868       rc = sqlcipher3PagerOpenWal(pBt->pPager, &isOpen);
51869       if( rc!=SQLCIPHER_OK ){
51870         goto page1_init_failed;
51871       }else if( isOpen==0 ){
51872         releasePage(pPage1);
51873         return SQLCIPHER_OK;
51874       }
51875       rc = SQLCIPHER_NOTADB;
51876     }
51877 #endif
51878
51879     /* The maximum embedded fraction must be exactly 25%.  And the minimum
51880     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
51881     ** The original design allowed these amounts to vary, but as of
51882     ** version 3.6.0, we require them to be fixed.
51883     */
51884     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
51885       goto page1_init_failed;
51886     }
51887     pageSize = (page1[16]<<8) | (page1[17]<<16);
51888     if( ((pageSize-1)&pageSize)!=0
51889      || pageSize>SQLCIPHER_MAX_PAGE_SIZE 
51890      || pageSize<=256 
51891     ){
51892       goto page1_init_failed;
51893     }
51894     assert( (pageSize & 7)==0 );
51895     usableSize = pageSize - page1[20];
51896     if( (u32)pageSize!=pBt->pageSize ){
51897       /* After reading the first page of the database assuming a page size
51898       ** of BtShared.pageSize, we have discovered that the page-size is
51899       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
51900       ** zero and return SQLCIPHER_OK. The caller will call this function
51901       ** again with the correct page-size.
51902       */
51903       releasePage(pPage1);
51904       pBt->usableSize = usableSize;
51905       pBt->pageSize = pageSize;
51906       freeTempSpace(pBt);
51907       rc = sqlcipher3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
51908                                    pageSize-usableSize);
51909       return rc;
51910     }
51911     if( (pBt->db->flags & SQLCIPHER_RecoveryMode)==0 && nPage>nPageFile ){
51912       rc = SQLCIPHER_CORRUPT_BKPT;
51913       goto page1_init_failed;
51914     }
51915     if( usableSize<480 ){
51916       goto page1_init_failed;
51917     }
51918     pBt->pageSize = pageSize;
51919     pBt->usableSize = usableSize;
51920 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
51921     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
51922     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
51923 #endif
51924   }
51925
51926   /* maxLocal is the maximum amount of payload to store locally for
51927   ** a cell.  Make sure it is small enough so that at least minFanout
51928   ** cells can will fit on one page.  We assume a 10-byte page header.
51929   ** Besides the payload, the cell must store:
51930   **     2-byte pointer to the cell
51931   **     4-byte child pointer
51932   **     9-byte nKey value
51933   **     4-byte nData value
51934   **     4-byte overflow page pointer
51935   ** So a cell consists of a 2-byte pointer, a header which is as much as
51936   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
51937   ** page pointer.
51938   */
51939   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
51940   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
51941   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
51942   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
51943   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
51944   pBt->pPage1 = pPage1;
51945   pBt->nPage = nPage;
51946   return SQLCIPHER_OK;
51947
51948 page1_init_failed:
51949   releasePage(pPage1);
51950   pBt->pPage1 = 0;
51951   return rc;
51952 }
51953
51954 /*
51955 ** If there are no outstanding cursors and we are not in the middle
51956 ** of a transaction but there is a read lock on the database, then
51957 ** this routine unrefs the first page of the database file which 
51958 ** has the effect of releasing the read lock.
51959 **
51960 ** If there is a transaction in progress, this routine is a no-op.
51961 */
51962 static void unlockBtreeIfUnused(BtShared *pBt){
51963   assert( sqlcipher3_mutex_held(pBt->mutex) );
51964   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
51965   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
51966     assert( pBt->pPage1->aData );
51967     assert( sqlcipher3PagerRefcount(pBt->pPager)==1 );
51968     assert( pBt->pPage1->aData );
51969     releasePage(pBt->pPage1);
51970     pBt->pPage1 = 0;
51971   }
51972 }
51973
51974 /*
51975 ** If pBt points to an empty file then convert that empty file
51976 ** into a new empty database by initializing the first page of
51977 ** the database.
51978 */
51979 static int newDatabase(BtShared *pBt){
51980   MemPage *pP1;
51981   unsigned char *data;
51982   int rc;
51983
51984   assert( sqlcipher3_mutex_held(pBt->mutex) );
51985   if( pBt->nPage>0 ){
51986     return SQLCIPHER_OK;
51987   }
51988   pP1 = pBt->pPage1;
51989   assert( pP1!=0 );
51990   data = pP1->aData;
51991   rc = sqlcipher3PagerWrite(pP1->pDbPage);
51992   if( rc ) return rc;
51993   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
51994   assert( sizeof(zMagicHeader)==16 );
51995   data[16] = (u8)((pBt->pageSize>>8)&0xff);
51996   data[17] = (u8)((pBt->pageSize>>16)&0xff);
51997   data[18] = 1;
51998   data[19] = 1;
51999   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
52000   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
52001   data[21] = 64;
52002   data[22] = 32;
52003   data[23] = 32;
52004   memset(&data[24], 0, 100-24);
52005   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
52006   pBt->pageSizeFixed = 1;
52007 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
52008   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
52009   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
52010   put4byte(&data[36 + 4*4], pBt->autoVacuum);
52011   put4byte(&data[36 + 7*4], pBt->incrVacuum);
52012 #endif
52013   pBt->nPage = 1;
52014   data[31] = 1;
52015   return SQLCIPHER_OK;
52016 }
52017
52018 /*
52019 ** Attempt to start a new transaction. A write-transaction
52020 ** is started if the second argument is nonzero, otherwise a read-
52021 ** transaction.  If the second argument is 2 or more and exclusive
52022 ** transaction is started, meaning that no other process is allowed
52023 ** to access the database.  A preexisting transaction may not be
52024 ** upgraded to exclusive by calling this routine a second time - the
52025 ** exclusivity flag only works for a new transaction.
52026 **
52027 ** A write-transaction must be started before attempting any 
52028 ** changes to the database.  None of the following routines 
52029 ** will work unless a transaction is started first:
52030 **
52031 **      sqlcipher3BtreeCreateTable()
52032 **      sqlcipher3BtreeCreateIndex()
52033 **      sqlcipher3BtreeClearTable()
52034 **      sqlcipher3BtreeDropTable()
52035 **      sqlcipher3BtreeInsert()
52036 **      sqlcipher3BtreeDelete()
52037 **      sqlcipher3BtreeUpdateMeta()
52038 **
52039 ** If an initial attempt to acquire the lock fails because of lock contention
52040 ** and the database was previously unlocked, then invoke the busy handler
52041 ** if there is one.  But if there was previously a read-lock, do not
52042 ** invoke the busy handler - just return SQLCIPHER_BUSY.  SQLCIPHER_BUSY is 
52043 ** returned when there is already a read-lock in order to avoid a deadlock.
52044 **
52045 ** Suppose there are two processes A and B.  A has a read lock and B has
52046 ** a reserved lock.  B tries to promote to exclusive but is blocked because
52047 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
52048 ** One or the other of the two processes must give way or there can be
52049 ** no progress.  By returning SQLCIPHER_BUSY and not invoking the busy callback
52050 ** when A already has a read lock, we encourage A to give up and let B
52051 ** proceed.
52052 */
52053 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginTrans(Btree *p, int wrflag){
52054   sqlcipher3 *pBlock = 0;
52055   BtShared *pBt = p->pBt;
52056   int rc = SQLCIPHER_OK;
52057
52058   sqlcipher3BtreeEnter(p);
52059   btreeIntegrity(p);
52060
52061   /* If the btree is already in a write-transaction, or it
52062   ** is already in a read-transaction and a read-transaction
52063   ** is requested, this is a no-op.
52064   */
52065   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52066     goto trans_begun;
52067   }
52068
52069   /* Write transactions are not possible on a read-only database */
52070   if( pBt->readOnly && wrflag ){
52071     rc = SQLCIPHER_READONLY;
52072     goto trans_begun;
52073   }
52074
52075 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52076   /* If another database handle has already opened a write transaction 
52077   ** on this shared-btree structure and a second write transaction is
52078   ** requested, return SQLCIPHER_LOCKED.
52079   */
52080   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
52081     pBlock = pBt->pWriter->db;
52082   }else if( wrflag>1 ){
52083     BtLock *pIter;
52084     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52085       if( pIter->pBtree!=p ){
52086         pBlock = pIter->pBtree->db;
52087         break;
52088       }
52089     }
52090   }
52091   if( pBlock ){
52092     sqlcipher3ConnectionBlocked(p->db, pBlock);
52093     rc = SQLCIPHER_LOCKED_SHAREDCACHE;
52094     goto trans_begun;
52095   }
52096 #endif
52097
52098   /* Any read-only or read-write transaction implies a read-lock on 
52099   ** page 1. So if some other shared-cache client already has a write-lock 
52100   ** on page 1, the transaction cannot be opened. */
52101   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52102   if( SQLCIPHER_OK!=rc ) goto trans_begun;
52103
52104   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
52105   do {
52106     /* Call lockBtree() until either pBt->pPage1 is populated or
52107     ** lockBtree() returns something other than SQLCIPHER_OK. lockBtree()
52108     ** may return SQLCIPHER_OK but leave pBt->pPage1 set to 0 if after
52109     ** reading page 1 it discovers that the page-size of the database 
52110     ** file is not pBt->pageSize. In this case lockBtree() will update
52111     ** pBt->pageSize to the page-size of the file on disk.
52112     */
52113     while( pBt->pPage1==0 && SQLCIPHER_OK==(rc = lockBtree(pBt)) );
52114
52115     if( rc==SQLCIPHER_OK && wrflag ){
52116       if( pBt->readOnly ){
52117         rc = SQLCIPHER_READONLY;
52118       }else{
52119         rc = sqlcipher3PagerBegin(pBt->pPager,wrflag>1,sqlcipher3TempInMemory(p->db));
52120         if( rc==SQLCIPHER_OK ){
52121           rc = newDatabase(pBt);
52122         }
52123       }
52124     }
52125   
52126     if( rc!=SQLCIPHER_OK ){
52127       unlockBtreeIfUnused(pBt);
52128     }
52129   }while( (rc&0xFF)==SQLCIPHER_BUSY && pBt->inTransaction==TRANS_NONE &&
52130           btreeInvokeBusyHandler(pBt) );
52131
52132   if( rc==SQLCIPHER_OK ){
52133     if( p->inTrans==TRANS_NONE ){
52134       pBt->nTransaction++;
52135 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52136       if( p->sharable ){
52137         assert( p->lock.pBtree==p && p->lock.iTable==1 );
52138         p->lock.eLock = READ_LOCK;
52139         p->lock.pNext = pBt->pLock;
52140         pBt->pLock = &p->lock;
52141       }
52142 #endif
52143     }
52144     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52145     if( p->inTrans>pBt->inTransaction ){
52146       pBt->inTransaction = p->inTrans;
52147     }
52148     if( wrflag ){
52149       MemPage *pPage1 = pBt->pPage1;
52150 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52151       assert( !pBt->pWriter );
52152       pBt->pWriter = p;
52153       pBt->isExclusive = (u8)(wrflag>1);
52154 #endif
52155
52156       /* If the db-size header field is incorrect (as it may be if an old
52157       ** client has been writing the database file), update it now. Doing
52158       ** this sooner rather than later means the database size can safely 
52159       ** re-read the database size from page 1 if a savepoint or transaction
52160       ** rollback occurs within the transaction.
52161       */
52162       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52163         rc = sqlcipher3PagerWrite(pPage1->pDbPage);
52164         if( rc==SQLCIPHER_OK ){
52165           put4byte(&pPage1->aData[28], pBt->nPage);
52166         }
52167       }
52168     }
52169   }
52170
52171
52172 trans_begun:
52173   if( rc==SQLCIPHER_OK && wrflag ){
52174     /* This call makes sure that the pager has the correct number of
52175     ** open savepoints. If the second parameter is greater than 0 and
52176     ** the sub-journal is not already open, then it will be opened here.
52177     */
52178     rc = sqlcipher3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52179   }
52180
52181   btreeIntegrity(p);
52182   sqlcipher3BtreeLeave(p);
52183   return rc;
52184 }
52185
52186 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
52187
52188 /*
52189 ** Set the pointer-map entries for all children of page pPage. Also, if
52190 ** pPage contains cells that point to overflow pages, set the pointer
52191 ** map entries for the overflow pages as well.
52192 */
52193 static int setChildPtrmaps(MemPage *pPage){
52194   int i;                             /* Counter variable */
52195   int nCell;                         /* Number of cells in page pPage */
52196   int rc;                            /* Return code */
52197   BtShared *pBt = pPage->pBt;
52198   u8 isInitOrig = pPage->isInit;
52199   Pgno pgno = pPage->pgno;
52200
52201   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
52202   rc = btreeInitPage(pPage);
52203   if( rc!=SQLCIPHER_OK ){
52204     goto set_child_ptrmaps_out;
52205   }
52206   nCell = pPage->nCell;
52207
52208   for(i=0; i<nCell; i++){
52209     u8 *pCell = findCell(pPage, i);
52210
52211     ptrmapPutOvflPtr(pPage, pCell, &rc);
52212
52213     if( !pPage->leaf ){
52214       Pgno childPgno = get4byte(pCell);
52215       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52216     }
52217   }
52218
52219   if( !pPage->leaf ){
52220     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52221     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52222   }
52223
52224 set_child_ptrmaps_out:
52225   pPage->isInit = isInitOrig;
52226   return rc;
52227 }
52228
52229 /*
52230 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52231 ** that it points to iTo. Parameter eType describes the type of pointer to
52232 ** be modified, as  follows:
52233 **
52234 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
52235 **                   page of pPage.
52236 **
52237 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52238 **                   page pointed to by one of the cells on pPage.
52239 **
52240 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52241 **                   overflow page in the list.
52242 */
52243 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52244   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
52245   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
52246   if( eType==PTRMAP_OVERFLOW2 ){
52247     /* The pointer is always the first 4 bytes of the page in this case.  */
52248     if( get4byte(pPage->aData)!=iFrom ){
52249       return SQLCIPHER_CORRUPT_BKPT;
52250     }
52251     put4byte(pPage->aData, iTo);
52252   }else{
52253     u8 isInitOrig = pPage->isInit;
52254     int i;
52255     int nCell;
52256
52257     btreeInitPage(pPage);
52258     nCell = pPage->nCell;
52259
52260     for(i=0; i<nCell; i++){
52261       u8 *pCell = findCell(pPage, i);
52262       if( eType==PTRMAP_OVERFLOW1 ){
52263         CellInfo info;
52264         btreeParseCellPtr(pPage, pCell, &info);
52265         if( info.iOverflow
52266          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52267          && iFrom==get4byte(&pCell[info.iOverflow])
52268         ){
52269           put4byte(&pCell[info.iOverflow], iTo);
52270           break;
52271         }
52272       }else{
52273         if( get4byte(pCell)==iFrom ){
52274           put4byte(pCell, iTo);
52275           break;
52276         }
52277       }
52278     }
52279   
52280     if( i==nCell ){
52281       if( eType!=PTRMAP_BTREE || 
52282           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52283         return SQLCIPHER_CORRUPT_BKPT;
52284       }
52285       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52286     }
52287
52288     pPage->isInit = isInitOrig;
52289   }
52290   return SQLCIPHER_OK;
52291 }
52292
52293
52294 /*
52295 ** Move the open database page pDbPage to location iFreePage in the 
52296 ** database. The pDbPage reference remains valid.
52297 **
52298 ** The isCommit flag indicates that there is no need to remember that
52299 ** the journal needs to be sync()ed before database page pDbPage->pgno 
52300 ** can be written to. The caller has already promised not to write to that
52301 ** page.
52302 */
52303 static int relocatePage(
52304   BtShared *pBt,           /* Btree */
52305   MemPage *pDbPage,        /* Open page to move */
52306   u8 eType,                /* Pointer map 'type' entry for pDbPage */
52307   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52308   Pgno iFreePage,          /* The location to move pDbPage to */
52309   int isCommit             /* isCommit flag passed to sqlcipher3PagerMovepage */
52310 ){
52311   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52312   Pgno iDbPage = pDbPage->pgno;
52313   Pager *pPager = pBt->pPager;
52314   int rc;
52315
52316   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
52317       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52318   assert( sqlcipher3_mutex_held(pBt->mutex) );
52319   assert( pDbPage->pBt==pBt );
52320
52321   /* Move page iDbPage from its current location to page number iFreePage */
52322   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
52323       iDbPage, iFreePage, iPtrPage, eType));
52324   rc = sqlcipher3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52325   if( rc!=SQLCIPHER_OK ){
52326     return rc;
52327   }
52328   pDbPage->pgno = iFreePage;
52329
52330   /* If pDbPage was a btree-page, then it may have child pages and/or cells
52331   ** that point to overflow pages. The pointer map entries for all these
52332   ** pages need to be changed.
52333   **
52334   ** If pDbPage is an overflow page, then the first 4 bytes may store a
52335   ** pointer to a subsequent overflow page. If this is the case, then
52336   ** the pointer map needs to be updated for the subsequent overflow page.
52337   */
52338   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52339     rc = setChildPtrmaps(pDbPage);
52340     if( rc!=SQLCIPHER_OK ){
52341       return rc;
52342     }
52343   }else{
52344     Pgno nextOvfl = get4byte(pDbPage->aData);
52345     if( nextOvfl!=0 ){
52346       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52347       if( rc!=SQLCIPHER_OK ){
52348         return rc;
52349       }
52350     }
52351   }
52352
52353   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52354   ** that it points at iFreePage. Also fix the pointer map entry for
52355   ** iPtrPage.
52356   */
52357   if( eType!=PTRMAP_ROOTPAGE ){
52358     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
52359     if( rc!=SQLCIPHER_OK ){
52360       return rc;
52361     }
52362     rc = sqlcipher3PagerWrite(pPtrPage->pDbPage);
52363     if( rc!=SQLCIPHER_OK ){
52364       releasePage(pPtrPage);
52365       return rc;
52366     }
52367     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52368     releasePage(pPtrPage);
52369     if( rc==SQLCIPHER_OK ){
52370       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52371     }
52372   }
52373   return rc;
52374 }
52375
52376 /* Forward declaration required by incrVacuumStep(). */
52377 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52378
52379 /*
52380 ** Perform a single step of an incremental-vacuum. If successful,
52381 ** return SQLCIPHER_OK. If there is no work to do (and therefore no
52382 ** point in calling this function again), return SQLCIPHER_DONE.
52383 **
52384 ** More specificly, this function attempts to re-organize the 
52385 ** database so that the last page of the file currently in use
52386 ** is no longer in use.
52387 **
52388 ** If the nFin parameter is non-zero, this function assumes
52389 ** that the caller will keep calling incrVacuumStep() until
52390 ** it returns SQLCIPHER_DONE or an error, and that nFin is the
52391 ** number of pages the database file will contain after this 
52392 ** process is complete.  If nFin is zero, it is assumed that
52393 ** incrVacuumStep() will be called a finite amount of times
52394 ** which may or may not empty the freelist.  A full autovacuum
52395 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
52396 */
52397 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
52398   Pgno nFreeList;           /* Number of pages still on the free-list */
52399   int rc;
52400
52401   assert( sqlcipher3_mutex_held(pBt->mutex) );
52402   assert( iLastPg>nFin );
52403
52404   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52405     u8 eType;
52406     Pgno iPtrPage;
52407
52408     nFreeList = get4byte(&pBt->pPage1->aData[36]);
52409     if( nFreeList==0 ){
52410       return SQLCIPHER_DONE;
52411     }
52412
52413     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52414     if( rc!=SQLCIPHER_OK ){
52415       return rc;
52416     }
52417     if( eType==PTRMAP_ROOTPAGE ){
52418       return SQLCIPHER_CORRUPT_BKPT;
52419     }
52420
52421     if( eType==PTRMAP_FREEPAGE ){
52422       if( nFin==0 ){
52423         /* Remove the page from the files free-list. This is not required
52424         ** if nFin is non-zero. In that case, the free-list will be
52425         ** truncated to zero after this function returns, so it doesn't 
52426         ** matter if it still contains some garbage entries.
52427         */
52428         Pgno iFreePg;
52429         MemPage *pFreePg;
52430         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
52431         if( rc!=SQLCIPHER_OK ){
52432           return rc;
52433         }
52434         assert( iFreePg==iLastPg );
52435         releasePage(pFreePg);
52436       }
52437     } else {
52438       Pgno iFreePg;             /* Index of free page to move pLastPg to */
52439       MemPage *pLastPg;
52440
52441       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
52442       if( rc!=SQLCIPHER_OK ){
52443         return rc;
52444       }
52445
52446       /* If nFin is zero, this loop runs exactly once and page pLastPg
52447       ** is swapped with the first free page pulled off the free list.
52448       **
52449       ** On the other hand, if nFin is greater than zero, then keep
52450       ** looping until a free-page located within the first nFin pages
52451       ** of the file is found.
52452       */
52453       do {
52454         MemPage *pFreePg;
52455         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
52456         if( rc!=SQLCIPHER_OK ){
52457           releasePage(pLastPg);
52458           return rc;
52459         }
52460         releasePage(pFreePg);
52461       }while( nFin!=0 && iFreePg>nFin );
52462       assert( iFreePg<iLastPg );
52463       
52464       rc = sqlcipher3PagerWrite(pLastPg->pDbPage);
52465       if( rc==SQLCIPHER_OK ){
52466         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
52467       }
52468       releasePage(pLastPg);
52469       if( rc!=SQLCIPHER_OK ){
52470         return rc;
52471       }
52472     }
52473   }
52474
52475   if( nFin==0 ){
52476     iLastPg--;
52477     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
52478       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
52479         MemPage *pPg;
52480         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
52481         if( rc!=SQLCIPHER_OK ){
52482           return rc;
52483         }
52484         rc = sqlcipher3PagerWrite(pPg->pDbPage);
52485         releasePage(pPg);
52486         if( rc!=SQLCIPHER_OK ){
52487           return rc;
52488         }
52489       }
52490       iLastPg--;
52491     }
52492     sqlcipher3PagerTruncateImage(pBt->pPager, iLastPg);
52493     pBt->nPage = iLastPg;
52494   }
52495   return SQLCIPHER_OK;
52496 }
52497
52498 /*
52499 ** A write-transaction must be opened before calling this function.
52500 ** It performs a single unit of work towards an incremental vacuum.
52501 **
52502 ** If the incremental vacuum is finished after this function has run,
52503 ** SQLCIPHER_DONE is returned. If it is not finished, but no error occurred,
52504 ** SQLCIPHER_OK is returned. Otherwise an SQLite error code. 
52505 */
52506 SQLCIPHER_PRIVATE int sqlcipher3BtreeIncrVacuum(Btree *p){
52507   int rc;
52508   BtShared *pBt = p->pBt;
52509
52510   sqlcipher3BtreeEnter(p);
52511   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52512   if( !pBt->autoVacuum ){
52513     rc = SQLCIPHER_DONE;
52514   }else{
52515     invalidateAllOverflowCache(pBt);
52516     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
52517     if( rc==SQLCIPHER_OK ){
52518       rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
52519       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52520     }
52521   }
52522   sqlcipher3BtreeLeave(p);
52523   return rc;
52524 }
52525
52526 /*
52527 ** This routine is called prior to sqlcipher3PagerCommit when a transaction
52528 ** is commited for an auto-vacuum database.
52529 **
52530 ** If SQLCIPHER_OK is returned, then *pnTrunc is set to the number of pages
52531 ** the database file should be truncated to during the commit process. 
52532 ** i.e. the database has been reorganized so that only the first *pnTrunc
52533 ** pages are in use.
52534 */
52535 static int autoVacuumCommit(BtShared *pBt){
52536   int rc = SQLCIPHER_OK;
52537   Pager *pPager = pBt->pPager;
52538   VVA_ONLY( int nRef = sqlcipher3PagerRefcount(pPager) );
52539
52540   assert( sqlcipher3_mutex_held(pBt->mutex) );
52541   invalidateAllOverflowCache(pBt);
52542   assert(pBt->autoVacuum);
52543   if( !pBt->incrVacuum ){
52544     Pgno nFin;         /* Number of pages in database after autovacuuming */
52545     Pgno nFree;        /* Number of pages on the freelist initially */
52546     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
52547     Pgno iFree;        /* The next page to be freed */
52548     int nEntry;        /* Number of entries on one ptrmap page */
52549     Pgno nOrig;        /* Database size before freeing */
52550
52551     nOrig = btreePagecount(pBt);
52552     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52553       /* It is not possible to create a database for which the final page
52554       ** is either a pointer-map page or the pending-byte page. If one
52555       ** is encountered, this indicates corruption.
52556       */
52557       return SQLCIPHER_CORRUPT_BKPT;
52558     }
52559
52560     nFree = get4byte(&pBt->pPage1->aData[36]);
52561     nEntry = pBt->usableSize/5;
52562     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52563     nFin = nOrig - nFree - nPtrmap;
52564     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52565       nFin--;
52566     }
52567     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52568       nFin--;
52569     }
52570     if( nFin>nOrig ) return SQLCIPHER_CORRUPT_BKPT;
52571
52572     for(iFree=nOrig; iFree>nFin && rc==SQLCIPHER_OK; iFree--){
52573       rc = incrVacuumStep(pBt, nFin, iFree);
52574     }
52575     if( (rc==SQLCIPHER_DONE || rc==SQLCIPHER_OK) && nFree>0 ){
52576       rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
52577       put4byte(&pBt->pPage1->aData[32], 0);
52578       put4byte(&pBt->pPage1->aData[36], 0);
52579       put4byte(&pBt->pPage1->aData[28], nFin);
52580       sqlcipher3PagerTruncateImage(pBt->pPager, nFin);
52581       pBt->nPage = nFin;
52582     }
52583     if( rc!=SQLCIPHER_OK ){
52584       sqlcipher3PagerRollback(pPager);
52585     }
52586   }
52587
52588   assert( nRef==sqlcipher3PagerRefcount(pPager) );
52589   return rc;
52590 }
52591
52592 #else /* ifndef SQLCIPHER_OMIT_AUTOVACUUM */
52593 # define setChildPtrmaps(x) SQLCIPHER_OK
52594 #endif
52595
52596 /*
52597 ** This routine does the first phase of a two-phase commit.  This routine
52598 ** causes a rollback journal to be created (if it does not already exist)
52599 ** and populated with enough information so that if a power loss occurs
52600 ** the database can be restored to its original state by playing back
52601 ** the journal.  Then the contents of the journal are flushed out to
52602 ** the disk.  After the journal is safely on oxide, the changes to the
52603 ** database are written into the database file and flushed to oxide.
52604 ** At the end of this call, the rollback journal still exists on the
52605 ** disk and we are still holding all locks, so the transaction has not
52606 ** committed.  See sqlcipher3BtreeCommitPhaseTwo() for the second phase of the
52607 ** commit process.
52608 **
52609 ** This call is a no-op if no write-transaction is currently active on pBt.
52610 **
52611 ** Otherwise, sync the database file for the btree pBt. zMaster points to
52612 ** the name of a master journal file that should be written into the
52613 ** individual journal file, or is NULL, indicating no master journal file 
52614 ** (single database transaction).
52615 **
52616 ** When this is called, the master journal should already have been
52617 ** created, populated with this journal pointer and synced to disk.
52618 **
52619 ** Once this is routine has returned, the only thing required to commit
52620 ** the write-transaction for this database file is to delete the journal.
52621 */
52622 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52623   int rc = SQLCIPHER_OK;
52624   if( p->inTrans==TRANS_WRITE ){
52625     BtShared *pBt = p->pBt;
52626     sqlcipher3BtreeEnter(p);
52627 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
52628     if( pBt->autoVacuum ){
52629       rc = autoVacuumCommit(pBt);
52630       if( rc!=SQLCIPHER_OK ){
52631         sqlcipher3BtreeLeave(p);
52632         return rc;
52633       }
52634     }
52635 #endif
52636     rc = sqlcipher3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52637     sqlcipher3BtreeLeave(p);
52638   }
52639   return rc;
52640 }
52641
52642 /*
52643 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52644 ** at the conclusion of a transaction.
52645 */
52646 static void btreeEndTransaction(Btree *p){
52647   BtShared *pBt = p->pBt;
52648   assert( sqlcipher3BtreeHoldsMutex(p) );
52649
52650   btreeClearHasContent(pBt);
52651   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
52652     /* If there are other active statements that belong to this database
52653     ** handle, downgrade to a read-only transaction. The other statements
52654     ** may still be reading from the database.  */
52655     downgradeAllSharedCacheTableLocks(p);
52656     p->inTrans = TRANS_READ;
52657   }else{
52658     /* If the handle had any kind of transaction open, decrement the 
52659     ** transaction count of the shared btree. If the transaction count 
52660     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52661     ** call below will unlock the pager.  */
52662     if( p->inTrans!=TRANS_NONE ){
52663       clearAllSharedCacheTableLocks(p);
52664       pBt->nTransaction--;
52665       if( 0==pBt->nTransaction ){
52666         pBt->inTransaction = TRANS_NONE;
52667       }
52668     }
52669
52670     /* Set the current transaction state to TRANS_NONE and unlock the 
52671     ** pager if this call closed the only read or write transaction.  */
52672     p->inTrans = TRANS_NONE;
52673     unlockBtreeIfUnused(pBt);
52674   }
52675
52676   btreeIntegrity(p);
52677 }
52678
52679 /*
52680 ** Commit the transaction currently in progress.
52681 **
52682 ** This routine implements the second phase of a 2-phase commit.  The
52683 ** sqlcipher3BtreeCommitPhaseOne() routine does the first phase and should
52684 ** be invoked prior to calling this routine.  The sqlcipher3BtreeCommitPhaseOne()
52685 ** routine did all the work of writing information out to disk and flushing the
52686 ** contents so that they are written onto the disk platter.  All this
52687 ** routine has to do is delete or truncate or zero the header in the
52688 ** the rollback journal (which causes the transaction to commit) and
52689 ** drop locks.
52690 **
52691 ** Normally, if an error occurs while the pager layer is attempting to 
52692 ** finalize the underlying journal file, this function returns an error and
52693 ** the upper layer will attempt a rollback. However, if the second argument
52694 ** is non-zero then this b-tree transaction is part of a multi-file 
52695 ** transaction. In this case, the transaction has already been committed 
52696 ** (by deleting a master journal file) and the caller will ignore this 
52697 ** functions return code. So, even if an error occurs in the pager layer,
52698 ** reset the b-tree objects internal state to indicate that the write
52699 ** transaction has been closed. This is quite safe, as the pager will have
52700 ** transitioned to the error state.
52701 **
52702 ** This will release the write lock on the database file.  If there
52703 ** are no active cursors, it also releases the read lock.
52704 */
52705 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52706
52707   if( p->inTrans==TRANS_NONE ) return SQLCIPHER_OK;
52708   sqlcipher3BtreeEnter(p);
52709   btreeIntegrity(p);
52710
52711   /* If the handle has a write-transaction open, commit the shared-btrees 
52712   ** transaction and set the shared state to TRANS_READ.
52713   */
52714   if( p->inTrans==TRANS_WRITE ){
52715     int rc;
52716     BtShared *pBt = p->pBt;
52717     assert( pBt->inTransaction==TRANS_WRITE );
52718     assert( pBt->nTransaction>0 );
52719     rc = sqlcipher3PagerCommitPhaseTwo(pBt->pPager);
52720     if( rc!=SQLCIPHER_OK && bCleanup==0 ){
52721       sqlcipher3BtreeLeave(p);
52722       return rc;
52723     }
52724     pBt->inTransaction = TRANS_READ;
52725   }
52726
52727   btreeEndTransaction(p);
52728   sqlcipher3BtreeLeave(p);
52729   return SQLCIPHER_OK;
52730 }
52731
52732 /*
52733 ** Do both phases of a commit.
52734 */
52735 SQLCIPHER_PRIVATE int sqlcipher3BtreeCommit(Btree *p){
52736   int rc;
52737   sqlcipher3BtreeEnter(p);
52738   rc = sqlcipher3BtreeCommitPhaseOne(p, 0);
52739   if( rc==SQLCIPHER_OK ){
52740     rc = sqlcipher3BtreeCommitPhaseTwo(p, 0);
52741   }
52742   sqlcipher3BtreeLeave(p);
52743   return rc;
52744 }
52745
52746 #ifndef NDEBUG
52747 /*
52748 ** Return the number of write-cursors open on this handle. This is for use
52749 ** in assert() expressions, so it is only compiled if NDEBUG is not
52750 ** defined.
52751 **
52752 ** For the purposes of this routine, a write-cursor is any cursor that
52753 ** is capable of writing to the databse.  That means the cursor was
52754 ** originally opened for writing and the cursor has not be disabled
52755 ** by having its state changed to CURSOR_FAULT.
52756 */
52757 static int countWriteCursors(BtShared *pBt){
52758   BtCursor *pCur;
52759   int r = 0;
52760   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52761     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
52762   }
52763   return r;
52764 }
52765 #endif
52766
52767 /*
52768 ** This routine sets the state to CURSOR_FAULT and the error
52769 ** code to errCode for every cursor on BtShared that pBtree
52770 ** references.
52771 **
52772 ** Every cursor is tripped, including cursors that belong
52773 ** to other database connections that happen to be sharing
52774 ** the cache with pBtree.
52775 **
52776 ** This routine gets called when a rollback occurs.
52777 ** All cursors using the same cache must be tripped
52778 ** to prevent them from trying to use the btree after
52779 ** the rollback.  The rollback may have deleted tables
52780 ** or moved root pages, so it is not sufficient to
52781 ** save the state of the cursor.  The cursor must be
52782 ** invalidated.
52783 */
52784 SQLCIPHER_PRIVATE void sqlcipher3BtreeTripAllCursors(Btree *pBtree, int errCode){
52785   BtCursor *p;
52786   sqlcipher3BtreeEnter(pBtree);
52787   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52788     int i;
52789     sqlcipher3BtreeClearCursor(p);
52790     p->eState = CURSOR_FAULT;
52791     p->skipNext = errCode;
52792     for(i=0; i<=p->iPage; i++){
52793       releasePage(p->apPage[i]);
52794       p->apPage[i] = 0;
52795     }
52796   }
52797   sqlcipher3BtreeLeave(pBtree);
52798 }
52799
52800 /*
52801 ** Rollback the transaction in progress.  All cursors will be
52802 ** invalided by this operation.  Any attempt to use a cursor
52803 ** that was open at the beginning of this operation will result
52804 ** in an error.
52805 **
52806 ** This will release the write lock on the database file.  If there
52807 ** are no active cursors, it also releases the read lock.
52808 */
52809 SQLCIPHER_PRIVATE int sqlcipher3BtreeRollback(Btree *p){
52810   int rc;
52811   BtShared *pBt = p->pBt;
52812   MemPage *pPage1;
52813
52814   sqlcipher3BtreeEnter(p);
52815   rc = saveAllCursors(pBt, 0, 0);
52816 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
52817   if( rc!=SQLCIPHER_OK ){
52818     /* This is a horrible situation. An IO or malloc() error occurred whilst
52819     ** trying to save cursor positions. If this is an automatic rollback (as
52820     ** the result of a constraint, malloc() failure or IO error) then 
52821     ** the cache may be internally inconsistent (not contain valid trees) so
52822     ** we cannot simply return the error to the caller. Instead, abort 
52823     ** all queries that may be using any of the cursors that failed to save.
52824     */
52825     sqlcipher3BtreeTripAllCursors(p, rc);
52826   }
52827 #endif
52828   btreeIntegrity(p);
52829
52830   if( p->inTrans==TRANS_WRITE ){
52831     int rc2;
52832
52833     assert( TRANS_WRITE==pBt->inTransaction );
52834     rc2 = sqlcipher3PagerRollback(pBt->pPager);
52835     if( rc2!=SQLCIPHER_OK ){
52836       rc = rc2;
52837     }
52838
52839     /* The rollback may have destroyed the pPage1->aData value.  So
52840     ** call btreeGetPage() on page 1 again to make
52841     ** sure pPage1->aData is set correctly. */
52842     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLCIPHER_OK ){
52843       int nPage = get4byte(28+(u8*)pPage1->aData);
52844       testcase( nPage==0 );
52845       if( nPage==0 ) sqlcipher3PagerPagecount(pBt->pPager, &nPage);
52846       testcase( pBt->nPage!=nPage );
52847       pBt->nPage = nPage;
52848       releasePage(pPage1);
52849     }
52850     assert( countWriteCursors(pBt)==0 );
52851     pBt->inTransaction = TRANS_READ;
52852   }
52853
52854   btreeEndTransaction(p);
52855   sqlcipher3BtreeLeave(p);
52856   return rc;
52857 }
52858
52859 /*
52860 ** Start a statement subtransaction. The subtransaction can can be rolled
52861 ** back independently of the main transaction. You must start a transaction 
52862 ** before starting a subtransaction. The subtransaction is ended automatically 
52863 ** if the main transaction commits or rolls back.
52864 **
52865 ** Statement subtransactions are used around individual SQL statements
52866 ** that are contained within a BEGIN...COMMIT block.  If a constraint
52867 ** error occurs within the statement, the effect of that one statement
52868 ** can be rolled back without having to rollback the entire transaction.
52869 **
52870 ** A statement sub-transaction is implemented as an anonymous savepoint. The
52871 ** value passed as the second parameter is the total number of savepoints,
52872 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
52873 ** are no active savepoints and no other statement-transactions open,
52874 ** iStatement is 1. This anonymous savepoint can be released or rolled back
52875 ** using the sqlcipher3BtreeSavepoint() function.
52876 */
52877 SQLCIPHER_PRIVATE int sqlcipher3BtreeBeginStmt(Btree *p, int iStatement){
52878   int rc;
52879   BtShared *pBt = p->pBt;
52880   sqlcipher3BtreeEnter(p);
52881   assert( p->inTrans==TRANS_WRITE );
52882   assert( pBt->readOnly==0 );
52883   assert( iStatement>0 );
52884   assert( iStatement>p->db->nSavepoint );
52885   assert( pBt->inTransaction==TRANS_WRITE );
52886   /* At the pager level, a statement transaction is a savepoint with
52887   ** an index greater than all savepoints created explicitly using
52888   ** SQL statements. It is illegal to open, release or rollback any
52889   ** such savepoints while the statement transaction savepoint is active.
52890   */
52891   rc = sqlcipher3PagerOpenSavepoint(pBt->pPager, iStatement);
52892   sqlcipher3BtreeLeave(p);
52893   return rc;
52894 }
52895
52896 /*
52897 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
52898 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
52899 ** savepoint identified by parameter iSavepoint, depending on the value 
52900 ** of op.
52901 **
52902 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
52903 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
52904 ** contents of the entire transaction are rolled back. This is different
52905 ** from a normal transaction rollback, as no locks are released and the
52906 ** transaction remains open.
52907 */
52908 SQLCIPHER_PRIVATE int sqlcipher3BtreeSavepoint(Btree *p, int op, int iSavepoint){
52909   int rc = SQLCIPHER_OK;
52910   if( p && p->inTrans==TRANS_WRITE ){
52911     BtShared *pBt = p->pBt;
52912     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52913     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
52914     sqlcipher3BtreeEnter(p);
52915     rc = sqlcipher3PagerSavepoint(pBt->pPager, op, iSavepoint);
52916     if( rc==SQLCIPHER_OK ){
52917       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
52918       rc = newDatabase(pBt);
52919       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
52920
52921       /* The database size was written into the offset 28 of the header
52922       ** when the transaction started, so we know that the value at offset
52923       ** 28 is nonzero. */
52924       assert( pBt->nPage>0 );
52925     }
52926     sqlcipher3BtreeLeave(p);
52927   }
52928   return rc;
52929 }
52930
52931 /*
52932 ** Create a new cursor for the BTree whose root is on the page
52933 ** iTable. If a read-only cursor is requested, it is assumed that
52934 ** the caller already has at least a read-only transaction open
52935 ** on the database already. If a write-cursor is requested, then
52936 ** the caller is assumed to have an open write transaction.
52937 **
52938 ** If wrFlag==0, then the cursor can only be used for reading.
52939 ** If wrFlag==1, then the cursor can be used for reading or for
52940 ** writing if other conditions for writing are also met.  These
52941 ** are the conditions that must be met in order for writing to
52942 ** be allowed:
52943 **
52944 ** 1:  The cursor must have been opened with wrFlag==1
52945 **
52946 ** 2:  Other database connections that share the same pager cache
52947 **     but which are not in the READ_UNCOMMITTED state may not have
52948 **     cursors open with wrFlag==0 on the same table.  Otherwise
52949 **     the changes made by this write cursor would be visible to
52950 **     the read cursors in the other database connection.
52951 **
52952 ** 3:  The database must be writable (not on read-only media)
52953 **
52954 ** 4:  There must be an active transaction.
52955 **
52956 ** No checking is done to make sure that page iTable really is the
52957 ** root page of a b-tree.  If it is not, then the cursor acquired
52958 ** will not work correctly.
52959 **
52960 ** It is assumed that the sqlcipher3BtreeCursorZero() has been called
52961 ** on pCur to initialize the memory space prior to invoking this routine.
52962 */
52963 static int btreeCursor(
52964   Btree *p,                              /* The btree */
52965   int iTable,                            /* Root page of table to open */
52966   int wrFlag,                            /* 1 to write. 0 read-only */
52967   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
52968   BtCursor *pCur                         /* Space for new cursor */
52969 ){
52970   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
52971
52972   assert( sqlcipher3BtreeHoldsMutex(p) );
52973   assert( wrFlag==0 || wrFlag==1 );
52974
52975   /* The following assert statements verify that if this is a sharable 
52976   ** b-tree database, the connection is holding the required table locks, 
52977   ** and that no other connection has any open cursor that conflicts with 
52978   ** this lock.  */
52979   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
52980   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
52981
52982   /* Assert that the caller has opened the required transaction. */
52983   assert( p->inTrans>TRANS_NONE );
52984   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
52985   assert( pBt->pPage1 && pBt->pPage1->aData );
52986
52987   if( NEVER(wrFlag && pBt->readOnly) ){
52988     return SQLCIPHER_READONLY;
52989   }
52990   if( iTable==1 && btreePagecount(pBt)==0 ){
52991     assert( wrFlag==0 );
52992     iTable = 0;
52993   }
52994
52995   /* Now that no other errors can occur, finish filling in the BtCursor
52996   ** variables and link the cursor into the BtShared list.  */
52997   pCur->pgnoRoot = (Pgno)iTable;
52998   pCur->iPage = -1;
52999   pCur->pKeyInfo = pKeyInfo;
53000   pCur->pBtree = p;
53001   pCur->pBt = pBt;
53002   pCur->wrFlag = (u8)wrFlag;
53003   pCur->pNext = pBt->pCursor;
53004   if( pCur->pNext ){
53005     pCur->pNext->pPrev = pCur;
53006   }
53007   pBt->pCursor = pCur;
53008   pCur->eState = CURSOR_INVALID;
53009   pCur->cachedRowid = 0;
53010   return SQLCIPHER_OK;
53011 }
53012 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursor(
53013   Btree *p,                                   /* The btree */
53014   int iTable,                                 /* Root page of table to open */
53015   int wrFlag,                                 /* 1 to write. 0 read-only */
53016   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
53017   BtCursor *pCur                              /* Write new cursor here */
53018 ){
53019   int rc;
53020   sqlcipher3BtreeEnter(p);
53021   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
53022   sqlcipher3BtreeLeave(p);
53023   return rc;
53024 }
53025
53026 /*
53027 ** Return the size of a BtCursor object in bytes.
53028 **
53029 ** This interfaces is needed so that users of cursors can preallocate
53030 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
53031 ** to users so they cannot do the sizeof() themselves - they must call
53032 ** this routine.
53033 */
53034 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorSize(void){
53035   return ROUND8(sizeof(BtCursor));
53036 }
53037
53038 /*
53039 ** Initialize memory that will be converted into a BtCursor object.
53040 **
53041 ** The simple approach here would be to memset() the entire object
53042 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
53043 ** do not need to be zeroed and they are large, so we can save a lot
53044 ** of run-time by skipping the initialization of those elements.
53045 */
53046 SQLCIPHER_PRIVATE void sqlcipher3BtreeCursorZero(BtCursor *p){
53047   memset(p, 0, offsetof(BtCursor, iPage));
53048 }
53049
53050 /*
53051 ** Set the cached rowid value of every cursor in the same database file
53052 ** as pCur and having the same root page number as pCur.  The value is
53053 ** set to iRowid.
53054 **
53055 ** Only positive rowid values are considered valid for this cache.
53056 ** The cache is initialized to zero, indicating an invalid cache.
53057 ** A btree will work fine with zero or negative rowids.  We just cannot
53058 ** cache zero or negative rowids, which means tables that use zero or
53059 ** negative rowids might run a little slower.  But in practice, zero
53060 ** or negative rowids are very uncommon so this should not be a problem.
53061 */
53062 SQLCIPHER_PRIVATE void sqlcipher3BtreeSetCachedRowid(BtCursor *pCur, sqlcipher3_int64 iRowid){
53063   BtCursor *p;
53064   for(p=pCur->pBt->pCursor; p; p=p->pNext){
53065     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53066   }
53067   assert( pCur->cachedRowid==iRowid );
53068 }
53069
53070 /*
53071 ** Return the cached rowid for the given cursor.  A negative or zero
53072 ** return value indicates that the rowid cache is invalid and should be
53073 ** ignored.  If the rowid cache has never before been set, then a
53074 ** zero is returned.
53075 */
53076 SQLCIPHER_PRIVATE sqlcipher3_int64 sqlcipher3BtreeGetCachedRowid(BtCursor *pCur){
53077   return pCur->cachedRowid;
53078 }
53079
53080 /*
53081 ** Close a cursor.  The read lock on the database file is released
53082 ** when the last cursor is closed.
53083 */
53084 SQLCIPHER_PRIVATE int sqlcipher3BtreeCloseCursor(BtCursor *pCur){
53085   Btree *pBtree = pCur->pBtree;
53086   if( pBtree ){
53087     int i;
53088     BtShared *pBt = pCur->pBt;
53089     sqlcipher3BtreeEnter(pBtree);
53090     sqlcipher3BtreeClearCursor(pCur);
53091     if( pCur->pPrev ){
53092       pCur->pPrev->pNext = pCur->pNext;
53093     }else{
53094       pBt->pCursor = pCur->pNext;
53095     }
53096     if( pCur->pNext ){
53097       pCur->pNext->pPrev = pCur->pPrev;
53098     }
53099     for(i=0; i<=pCur->iPage; i++){
53100       releasePage(pCur->apPage[i]);
53101     }
53102     unlockBtreeIfUnused(pBt);
53103     invalidateOverflowCache(pCur);
53104     /* sqlcipher3_free(pCur); */
53105     sqlcipher3BtreeLeave(pBtree);
53106   }
53107   return SQLCIPHER_OK;
53108 }
53109
53110 /*
53111 ** Make sure the BtCursor* given in the argument has a valid
53112 ** BtCursor.info structure.  If it is not already valid, call
53113 ** btreeParseCell() to fill it in.
53114 **
53115 ** BtCursor.info is a cache of the information in the current cell.
53116 ** Using this cache reduces the number of calls to btreeParseCell().
53117 **
53118 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
53119 ** compiler to crash when getCellInfo() is implemented as a macro.
53120 ** But there is a measureable speed advantage to using the macro on gcc
53121 ** (when less compiler optimizations like -Os or -O0 are used and the
53122 ** compiler is not doing agressive inlining.)  So we use a real function
53123 ** for MSVC and a macro for everything else.  Ticket #2457.
53124 */
53125 #ifndef NDEBUG
53126   static void assertCellInfo(BtCursor *pCur){
53127     CellInfo info;
53128     int iPage = pCur->iPage;
53129     memset(&info, 0, sizeof(info));
53130     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53131     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53132   }
53133 #else
53134   #define assertCellInfo(x)
53135 #endif
53136 #ifdef _MSC_VER
53137   /* Use a real function in MSVC to work around bugs in that compiler. */
53138   static void getCellInfo(BtCursor *pCur){
53139     if( pCur->info.nSize==0 ){
53140       int iPage = pCur->iPage;
53141       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53142       pCur->validNKey = 1;
53143     }else{
53144       assertCellInfo(pCur);
53145     }
53146   }
53147 #else /* if not _MSC_VER */
53148   /* Use a macro in all other compilers so that the function is inlined */
53149 #define getCellInfo(pCur)                                                      \
53150   if( pCur->info.nSize==0 ){                                                   \
53151     int iPage = pCur->iPage;                                                   \
53152     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53153     pCur->validNKey = 1;                                                       \
53154   }else{                                                                       \
53155     assertCellInfo(pCur);                                                      \
53156   }
53157 #endif /* _MSC_VER */
53158
53159 #ifndef NDEBUG  /* The next routine used only within assert() statements */
53160 /*
53161 ** Return true if the given BtCursor is valid.  A valid cursor is one
53162 ** that is currently pointing to a row in a (non-empty) table.
53163 ** This is a verification routine is used only within assert() statements.
53164 */
53165 SQLCIPHER_PRIVATE int sqlcipher3BtreeCursorIsValid(BtCursor *pCur){
53166   return pCur && pCur->eState==CURSOR_VALID;
53167 }
53168 #endif /* NDEBUG */
53169
53170 /*
53171 ** Set *pSize to the size of the buffer needed to hold the value of
53172 ** the key for the current entry.  If the cursor is not pointing
53173 ** to a valid entry, *pSize is set to 0. 
53174 **
53175 ** For a table with the INTKEY flag set, this routine returns the key
53176 ** itself, not the number of bytes in the key.
53177 **
53178 ** The caller must position the cursor prior to invoking this routine.
53179 ** 
53180 ** This routine cannot fail.  It always returns SQLCIPHER_OK.  
53181 */
53182 SQLCIPHER_PRIVATE int sqlcipher3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53183   assert( cursorHoldsMutex(pCur) );
53184   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53185   if( pCur->eState!=CURSOR_VALID ){
53186     *pSize = 0;
53187   }else{
53188     getCellInfo(pCur);
53189     *pSize = pCur->info.nKey;
53190   }
53191   return SQLCIPHER_OK;
53192 }
53193
53194 /*
53195 ** Set *pSize to the number of bytes of data in the entry the
53196 ** cursor currently points to.
53197 **
53198 ** The caller must guarantee that the cursor is pointing to a non-NULL
53199 ** valid entry.  In other words, the calling procedure must guarantee
53200 ** that the cursor has Cursor.eState==CURSOR_VALID.
53201 **
53202 ** Failure is not possible.  This function always returns SQLCIPHER_OK.
53203 ** It might just as well be a procedure (returning void) but we continue
53204 ** to return an integer result code for historical reasons.
53205 */
53206 SQLCIPHER_PRIVATE int sqlcipher3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53207   assert( cursorHoldsMutex(pCur) );
53208   assert( pCur->eState==CURSOR_VALID );
53209   getCellInfo(pCur);
53210   *pSize = pCur->info.nData;
53211   return SQLCIPHER_OK;
53212 }
53213
53214 /*
53215 ** Given the page number of an overflow page in the database (parameter
53216 ** ovfl), this function finds the page number of the next page in the 
53217 ** linked list of overflow pages. If possible, it uses the auto-vacuum
53218 ** pointer-map data instead of reading the content of page ovfl to do so. 
53219 **
53220 ** If an error occurs an SQLite error code is returned. Otherwise:
53221 **
53222 ** The page number of the next overflow page in the linked list is 
53223 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
53224 ** list, *pPgnoNext is set to zero. 
53225 **
53226 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
53227 ** to page number pOvfl was obtained, then *ppPage is set to point to that
53228 ** reference. It is the responsibility of the caller to call releasePage()
53229 ** on *ppPage to free the reference. In no reference was obtained (because
53230 ** the pointer-map was used to obtain the value for *pPgnoNext), then
53231 ** *ppPage is set to zero.
53232 */
53233 static int getOverflowPage(
53234   BtShared *pBt,               /* The database file */
53235   Pgno ovfl,                   /* Current overflow page number */
53236   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53237   Pgno *pPgnoNext              /* OUT: Next overflow page number */
53238 ){
53239   Pgno next = 0;
53240   MemPage *pPage = 0;
53241   int rc = SQLCIPHER_OK;
53242
53243   assert( sqlcipher3_mutex_held(pBt->mutex) );
53244   assert(pPgnoNext);
53245
53246 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
53247   /* Try to find the next page in the overflow list using the
53248   ** autovacuum pointer-map pages. Guess that the next page in 
53249   ** the overflow list is page number (ovfl+1). If that guess turns 
53250   ** out to be wrong, fall back to loading the data of page 
53251   ** number ovfl to determine the next page number.
53252   */
53253   if( pBt->autoVacuum ){
53254     Pgno pgno;
53255     Pgno iGuess = ovfl+1;
53256     u8 eType;
53257
53258     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53259       iGuess++;
53260     }
53261
53262     if( iGuess<=btreePagecount(pBt) ){
53263       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53264       if( rc==SQLCIPHER_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53265         next = iGuess;
53266         rc = SQLCIPHER_DONE;
53267       }
53268     }
53269   }
53270 #endif
53271
53272   assert( next==0 || rc==SQLCIPHER_DONE );
53273   if( rc==SQLCIPHER_OK ){
53274     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
53275     assert( rc==SQLCIPHER_OK || pPage==0 );
53276     if( rc==SQLCIPHER_OK ){
53277       next = get4byte(pPage->aData);
53278     }
53279   }
53280
53281   *pPgnoNext = next;
53282   if( ppPage ){
53283     *ppPage = pPage;
53284   }else{
53285     releasePage(pPage);
53286   }
53287   return (rc==SQLCIPHER_DONE ? SQLCIPHER_OK : rc);
53288 }
53289
53290 /*
53291 ** Copy data from a buffer to a page, or from a page to a buffer.
53292 **
53293 ** pPayload is a pointer to data stored on database page pDbPage.
53294 ** If argument eOp is false, then nByte bytes of data are copied
53295 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53296 ** then sqlcipher3PagerWrite() is called on pDbPage and nByte bytes
53297 ** of data are copied from the buffer pBuf to pPayload.
53298 **
53299 ** SQLCIPHER_OK is returned on success, otherwise an error code.
53300 */
53301 static int copyPayload(
53302   void *pPayload,           /* Pointer to page data */
53303   void *pBuf,               /* Pointer to buffer */
53304   int nByte,                /* Number of bytes to copy */
53305   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53306   DbPage *pDbPage           /* Page containing pPayload */
53307 ){
53308   if( eOp ){
53309     /* Copy data from buffer to page (a write operation) */
53310     int rc = sqlcipher3PagerWrite(pDbPage);
53311     if( rc!=SQLCIPHER_OK ){
53312       return rc;
53313     }
53314     memcpy(pPayload, pBuf, nByte);
53315   }else{
53316     /* Copy data from page to buffer (a read operation) */
53317     memcpy(pBuf, pPayload, nByte);
53318   }
53319   return SQLCIPHER_OK;
53320 }
53321
53322 /*
53323 ** This function is used to read or overwrite payload information
53324 ** for the entry that the pCur cursor is pointing to. If the eOp
53325 ** parameter is 0, this is a read operation (data copied into
53326 ** buffer pBuf). If it is non-zero, a write (data copied from
53327 ** buffer pBuf).
53328 **
53329 ** A total of "amt" bytes are read or written beginning at "offset".
53330 ** Data is read to or from the buffer pBuf.
53331 **
53332 ** The content being read or written might appear on the main page
53333 ** or be scattered out on multiple overflow pages.
53334 **
53335 ** If the BtCursor.isIncrblobHandle flag is set, and the current
53336 ** cursor entry uses one or more overflow pages, this function
53337 ** allocates space for and lazily popluates the overflow page-list 
53338 ** cache array (BtCursor.aOverflow). Subsequent calls use this
53339 ** cache to make seeking to the supplied offset more efficient.
53340 **
53341 ** Once an overflow page-list cache has been allocated, it may be
53342 ** invalidated if some other cursor writes to the same table, or if
53343 ** the cursor is moved to a different row. Additionally, in auto-vacuum
53344 ** mode, the following events may invalidate an overflow page-list cache.
53345 **
53346 **   * An incremental vacuum,
53347 **   * A commit in auto_vacuum="full" mode,
53348 **   * Creating a table (may require moving an overflow page).
53349 */
53350 static int accessPayload(
53351   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53352   u32 offset,          /* Begin reading this far into payload */
53353   u32 amt,             /* Read this many bytes */
53354   unsigned char *pBuf, /* Write the bytes into this buffer */ 
53355   int eOp              /* zero to read. non-zero to write. */
53356 ){
53357   unsigned char *aPayload;
53358   int rc = SQLCIPHER_OK;
53359   u32 nKey;
53360   int iIdx = 0;
53361   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53362   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53363
53364   assert( pPage );
53365   assert( pCur->eState==CURSOR_VALID );
53366   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53367   assert( cursorHoldsMutex(pCur) );
53368
53369   getCellInfo(pCur);
53370   aPayload = pCur->info.pCell + pCur->info.nHeader;
53371   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53372
53373   if( NEVER(offset+amt > nKey+pCur->info.nData) 
53374    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53375   ){
53376     /* Trying to read or write past the end of the data is an error */
53377     return SQLCIPHER_CORRUPT_BKPT;
53378   }
53379
53380   /* Check if data must be read/written to/from the btree page itself. */
53381   if( offset<pCur->info.nLocal ){
53382     int a = amt;
53383     if( a+offset>pCur->info.nLocal ){
53384       a = pCur->info.nLocal - offset;
53385     }
53386     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53387     offset = 0;
53388     pBuf += a;
53389     amt -= a;
53390   }else{
53391     offset -= pCur->info.nLocal;
53392   }
53393
53394   if( rc==SQLCIPHER_OK && amt>0 ){
53395     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53396     Pgno nextPage;
53397
53398     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53399
53400 #ifndef SQLCIPHER_OMIT_INCRBLOB
53401     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53402     ** has not been allocated, allocate it now. The array is sized at
53403     ** one entry for each overflow page in the overflow chain. The
53404     ** page number of the first overflow page is stored in aOverflow[0],
53405     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53406     ** (the cache is lazily populated).
53407     */
53408     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53409       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53410       pCur->aOverflow = (Pgno *)sqlcipher3MallocZero(sizeof(Pgno)*nOvfl);
53411       /* nOvfl is always positive.  If it were zero, fetchPayload would have
53412       ** been used instead of this routine. */
53413       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53414         rc = SQLCIPHER_NOMEM;
53415       }
53416     }
53417
53418     /* If the overflow page-list cache has been allocated and the
53419     ** entry for the first required overflow page is valid, skip
53420     ** directly to it.
53421     */
53422     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53423       iIdx = (offset/ovflSize);
53424       nextPage = pCur->aOverflow[iIdx];
53425       offset = (offset%ovflSize);
53426     }
53427 #endif
53428
53429     for( ; rc==SQLCIPHER_OK && amt>0 && nextPage; iIdx++){
53430
53431 #ifndef SQLCIPHER_OMIT_INCRBLOB
53432       /* If required, populate the overflow page-list cache. */
53433       if( pCur->aOverflow ){
53434         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53435         pCur->aOverflow[iIdx] = nextPage;
53436       }
53437 #endif
53438
53439       if( offset>=ovflSize ){
53440         /* The only reason to read this page is to obtain the page
53441         ** number for the next page in the overflow chain. The page
53442         ** data is not required. So first try to lookup the overflow
53443         ** page-list cache, if any, then fall back to the getOverflowPage()
53444         ** function.
53445         */
53446 #ifndef SQLCIPHER_OMIT_INCRBLOB
53447         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53448           nextPage = pCur->aOverflow[iIdx+1];
53449         } else 
53450 #endif
53451           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53452         offset -= ovflSize;
53453       }else{
53454         /* Need to read this page properly. It contains some of the
53455         ** range of data that is being read (eOp==0) or written (eOp!=0).
53456         */
53457 #ifdef SQLCIPHER_DIRECT_OVERFLOW_READ
53458         sqlcipher3_file *fd;
53459 #endif
53460         int a = amt;
53461         if( a + offset > ovflSize ){
53462           a = ovflSize - offset;
53463         }
53464
53465 #ifdef SQLCIPHER_DIRECT_OVERFLOW_READ
53466         /* If all the following are true:
53467         **
53468         **   1) this is a read operation, and 
53469         **   2) data is required from the start of this overflow page, and
53470         **   3) the database is file-backed, and
53471         **   4) there is no open write-transaction, and
53472         **   5) the database is not a WAL database,
53473         **
53474         ** then data can be read directly from the database file into the
53475         ** output buffer, bypassing the page-cache altogether. This speeds
53476         ** up loading large records that span many overflow pages.
53477         */
53478         if( eOp==0                                             /* (1) */
53479          && offset==0                                          /* (2) */
53480          && pBt->inTransaction==TRANS_READ                     /* (4) */
53481          && (fd = sqlcipher3PagerFile(pBt->pPager))->pMethods     /* (3) */
53482          && pBt->pPage1->aData[19]==0x01                       /* (5) */
53483         ){
53484           u8 aSave[4];
53485           u8 *aWrite = &pBuf[-4];
53486           memcpy(aSave, aWrite, 4);
53487           rc = sqlcipher3OsRead(fd, aWrite, a+4, pBt->pageSize * (nextPage-1));
53488           nextPage = get4byte(aWrite);
53489           memcpy(aWrite, aSave, 4);
53490         }else
53491 #endif
53492
53493         {
53494           DbPage *pDbPage;
53495           rc = sqlcipher3PagerGet(pBt->pPager, nextPage, &pDbPage);
53496           if( rc==SQLCIPHER_OK ){
53497             aPayload = sqlcipher3PagerGetData(pDbPage);
53498             nextPage = get4byte(aPayload);
53499             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53500             sqlcipher3PagerUnref(pDbPage);
53501             offset = 0;
53502           }
53503         }
53504         amt -= a;
53505         pBuf += a;
53506       }
53507     }
53508   }
53509
53510   if( rc==SQLCIPHER_OK && amt>0 ){
53511     return SQLCIPHER_CORRUPT_BKPT;
53512   }
53513   return rc;
53514 }
53515
53516 /*
53517 ** Read part of the key associated with cursor pCur.  Exactly
53518 ** "amt" bytes will be transfered into pBuf[].  The transfer
53519 ** begins at "offset".
53520 **
53521 ** The caller must ensure that pCur is pointing to a valid row
53522 ** in the table.
53523 **
53524 ** Return SQLCIPHER_OK on success or an error code if anything goes
53525 ** wrong.  An error is returned if "offset+amt" is larger than
53526 ** the available payload.
53527 */
53528 SQLCIPHER_PRIVATE int sqlcipher3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53529   assert( cursorHoldsMutex(pCur) );
53530   assert( pCur->eState==CURSOR_VALID );
53531   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53532   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53533   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53534 }
53535
53536 /*
53537 ** Read part of the data associated with cursor pCur.  Exactly
53538 ** "amt" bytes will be transfered into pBuf[].  The transfer
53539 ** begins at "offset".
53540 **
53541 ** Return SQLCIPHER_OK on success or an error code if anything goes
53542 ** wrong.  An error is returned if "offset+amt" is larger than
53543 ** the available payload.
53544 */
53545 SQLCIPHER_PRIVATE int sqlcipher3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53546   int rc;
53547
53548 #ifndef SQLCIPHER_OMIT_INCRBLOB
53549   if ( pCur->eState==CURSOR_INVALID ){
53550     return SQLCIPHER_ABORT;
53551   }
53552 #endif
53553
53554   assert( cursorHoldsMutex(pCur) );
53555   rc = restoreCursorPosition(pCur);
53556   if( rc==SQLCIPHER_OK ){
53557     assert( pCur->eState==CURSOR_VALID );
53558     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53559     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53560     rc = accessPayload(pCur, offset, amt, pBuf, 0);
53561   }
53562   return rc;
53563 }
53564
53565 /*
53566 ** Return a pointer to payload information from the entry that the 
53567 ** pCur cursor is pointing to.  The pointer is to the beginning of
53568 ** the key if skipKey==0 and it points to the beginning of data if
53569 ** skipKey==1.  The number of bytes of available key/data is written
53570 ** into *pAmt.  If *pAmt==0, then the value returned will not be
53571 ** a valid pointer.
53572 **
53573 ** This routine is an optimization.  It is common for the entire key
53574 ** and data to fit on the local page and for there to be no overflow
53575 ** pages.  When that is so, this routine can be used to access the
53576 ** key and data without making a copy.  If the key and/or data spills
53577 ** onto overflow pages, then accessPayload() must be used to reassemble
53578 ** the key/data and copy it into a preallocated buffer.
53579 **
53580 ** The pointer returned by this routine looks directly into the cached
53581 ** page of the database.  The data might change or move the next time
53582 ** any btree routine is called.
53583 */
53584 static const unsigned char *fetchPayload(
53585   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53586   int *pAmt,           /* Write the number of available bytes here */
53587   int skipKey          /* read beginning at data if this is true */
53588 ){
53589   unsigned char *aPayload;
53590   MemPage *pPage;
53591   u32 nKey;
53592   u32 nLocal;
53593
53594   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53595   assert( pCur->eState==CURSOR_VALID );
53596   assert( cursorHoldsMutex(pCur) );
53597   pPage = pCur->apPage[pCur->iPage];
53598   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53599   if( NEVER(pCur->info.nSize==0) ){
53600     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53601                    &pCur->info);
53602   }
53603   aPayload = pCur->info.pCell;
53604   aPayload += pCur->info.nHeader;
53605   if( pPage->intKey ){
53606     nKey = 0;
53607   }else{
53608     nKey = (int)pCur->info.nKey;
53609   }
53610   if( skipKey ){
53611     aPayload += nKey;
53612     nLocal = pCur->info.nLocal - nKey;
53613   }else{
53614     nLocal = pCur->info.nLocal;
53615     assert( nLocal<=nKey );
53616   }
53617   *pAmt = nLocal;
53618   return aPayload;
53619 }
53620
53621
53622 /*
53623 ** For the entry that cursor pCur is point to, return as
53624 ** many bytes of the key or data as are available on the local
53625 ** b-tree page.  Write the number of available bytes into *pAmt.
53626 **
53627 ** The pointer returned is ephemeral.  The key/data may move
53628 ** or be destroyed on the next call to any Btree routine,
53629 ** including calls from other threads against the same cache.
53630 ** Hence, a mutex on the BtShared should be held prior to calling
53631 ** this routine.
53632 **
53633 ** These routines is used to get quick access to key and data
53634 ** in the common case where no overflow pages are used.
53635 */
53636 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53637   const void *p = 0;
53638   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53639   assert( cursorHoldsMutex(pCur) );
53640   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53641     p = (const void*)fetchPayload(pCur, pAmt, 0);
53642   }
53643   return p;
53644 }
53645 SQLCIPHER_PRIVATE const void *sqlcipher3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53646   const void *p = 0;
53647   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53648   assert( cursorHoldsMutex(pCur) );
53649   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53650     p = (const void*)fetchPayload(pCur, pAmt, 1);
53651   }
53652   return p;
53653 }
53654
53655
53656 /*
53657 ** Move the cursor down to a new child page.  The newPgno argument is the
53658 ** page number of the child page to move to.
53659 **
53660 ** This function returns SQLCIPHER_CORRUPT if the page-header flags field of
53661 ** the new child page does not match the flags field of the parent (i.e.
53662 ** if an intkey page appears to be the parent of a non-intkey page, or
53663 ** vice-versa).
53664 */
53665 static int moveToChild(BtCursor *pCur, u32 newPgno){
53666   int rc;
53667   int i = pCur->iPage;
53668   MemPage *pNewPage;
53669   BtShared *pBt = pCur->pBt;
53670
53671   assert( cursorHoldsMutex(pCur) );
53672   assert( pCur->eState==CURSOR_VALID );
53673   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53674   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53675     return SQLCIPHER_CORRUPT_BKPT;
53676   }
53677   rc = getAndInitPage(pBt, newPgno, &pNewPage);
53678   if( rc ) return rc;
53679   pCur->apPage[i+1] = pNewPage;
53680   pCur->aiIdx[i+1] = 0;
53681   pCur->iPage++;
53682
53683   pCur->info.nSize = 0;
53684   pCur->validNKey = 0;
53685   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53686     return SQLCIPHER_CORRUPT_BKPT;
53687   }
53688   return SQLCIPHER_OK;
53689 }
53690
53691 #ifndef NDEBUG
53692 /*
53693 ** Page pParent is an internal (non-leaf) tree page. This function 
53694 ** asserts that page number iChild is the left-child if the iIdx'th
53695 ** cell in page pParent. Or, if iIdx is equal to the total number of
53696 ** cells in pParent, that page number iChild is the right-child of
53697 ** the page.
53698 */
53699 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53700   assert( iIdx<=pParent->nCell );
53701   if( iIdx==pParent->nCell ){
53702     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53703   }else{
53704     assert( get4byte(findCell(pParent, iIdx))==iChild );
53705   }
53706 }
53707 #else
53708 #  define assertParentIndex(x,y,z) 
53709 #endif
53710
53711 /*
53712 ** Move the cursor up to the parent page.
53713 **
53714 ** pCur->idx is set to the cell index that contains the pointer
53715 ** to the page we are coming from.  If we are coming from the
53716 ** right-most child page then pCur->idx is set to one more than
53717 ** the largest cell index.
53718 */
53719 static void moveToParent(BtCursor *pCur){
53720   assert( cursorHoldsMutex(pCur) );
53721   assert( pCur->eState==CURSOR_VALID );
53722   assert( pCur->iPage>0 );
53723   assert( pCur->apPage[pCur->iPage] );
53724   assertParentIndex(
53725     pCur->apPage[pCur->iPage-1], 
53726     pCur->aiIdx[pCur->iPage-1], 
53727     pCur->apPage[pCur->iPage]->pgno
53728   );
53729   releasePage(pCur->apPage[pCur->iPage]);
53730   pCur->iPage--;
53731   pCur->info.nSize = 0;
53732   pCur->validNKey = 0;
53733 }
53734
53735 /*
53736 ** Move the cursor to point to the root page of its b-tree structure.
53737 **
53738 ** If the table has a virtual root page, then the cursor is moved to point
53739 ** to the virtual root page instead of the actual root page. A table has a
53740 ** virtual root page when the actual root page contains no cells and a 
53741 ** single child page. This can only happen with the table rooted at page 1.
53742 **
53743 ** If the b-tree structure is empty, the cursor state is set to 
53744 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53745 ** cell located on the root (or virtual root) page and the cursor state
53746 ** is set to CURSOR_VALID.
53747 **
53748 ** If this function returns successfully, it may be assumed that the
53749 ** page-header flags indicate that the [virtual] root-page is the expected 
53750 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
53751 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53752 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
53753 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53754 ** b-tree).
53755 */
53756 static int moveToRoot(BtCursor *pCur){
53757   MemPage *pRoot;
53758   int rc = SQLCIPHER_OK;
53759   Btree *p = pCur->pBtree;
53760   BtShared *pBt = p->pBt;
53761
53762   assert( cursorHoldsMutex(pCur) );
53763   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53764   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
53765   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
53766   if( pCur->eState>=CURSOR_REQUIRESEEK ){
53767     if( pCur->eState==CURSOR_FAULT ){
53768       assert( pCur->skipNext!=SQLCIPHER_OK );
53769       return pCur->skipNext;
53770     }
53771     sqlcipher3BtreeClearCursor(pCur);
53772   }
53773
53774   if( pCur->iPage>=0 ){
53775     int i;
53776     for(i=1; i<=pCur->iPage; i++){
53777       releasePage(pCur->apPage[i]);
53778     }
53779     pCur->iPage = 0;
53780   }else if( pCur->pgnoRoot==0 ){
53781     pCur->eState = CURSOR_INVALID;
53782     return SQLCIPHER_OK;
53783   }else{
53784     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
53785     if( rc!=SQLCIPHER_OK ){
53786       pCur->eState = CURSOR_INVALID;
53787       return rc;
53788     }
53789     pCur->iPage = 0;
53790
53791     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53792     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53793     ** NULL, the caller expects a table b-tree. If this is not the case,
53794     ** return an SQLCIPHER_CORRUPT error.  */
53795     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
53796     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
53797       return SQLCIPHER_CORRUPT_BKPT;
53798     }
53799   }
53800
53801   /* Assert that the root page is of the correct type. This must be the
53802   ** case as the call to this function that loaded the root-page (either
53803   ** this call or a previous invocation) would have detected corruption 
53804   ** if the assumption were not true, and it is not possible for the flags 
53805   ** byte to have been modified while this cursor is holding a reference
53806   ** to the page.  */
53807   pRoot = pCur->apPage[0];
53808   assert( pRoot->pgno==pCur->pgnoRoot );
53809   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
53810
53811   pCur->aiIdx[0] = 0;
53812   pCur->info.nSize = 0;
53813   pCur->atLast = 0;
53814   pCur->validNKey = 0;
53815
53816   if( pRoot->nCell==0 && !pRoot->leaf ){
53817     Pgno subpage;
53818     if( pRoot->pgno!=1 ) return SQLCIPHER_CORRUPT_BKPT;
53819     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
53820     pCur->eState = CURSOR_VALID;
53821     rc = moveToChild(pCur, subpage);
53822   }else{
53823     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
53824   }
53825   return rc;
53826 }
53827
53828 /*
53829 ** Move the cursor down to the left-most leaf entry beneath the
53830 ** entry to which it is currently pointing.
53831 **
53832 ** The left-most leaf is the one with the smallest key - the first
53833 ** in ascending order.
53834 */
53835 static int moveToLeftmost(BtCursor *pCur){
53836   Pgno pgno;
53837   int rc = SQLCIPHER_OK;
53838   MemPage *pPage;
53839
53840   assert( cursorHoldsMutex(pCur) );
53841   assert( pCur->eState==CURSOR_VALID );
53842   while( rc==SQLCIPHER_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53843     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53844     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
53845     rc = moveToChild(pCur, pgno);
53846   }
53847   return rc;
53848 }
53849
53850 /*
53851 ** Move the cursor down to the right-most leaf entry beneath the
53852 ** page to which it is currently pointing.  Notice the difference
53853 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
53854 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
53855 ** finds the right-most entry beneath the *page*.
53856 **
53857 ** The right-most entry is the one with the largest key - the last
53858 ** key in ascending order.
53859 */
53860 static int moveToRightmost(BtCursor *pCur){
53861   Pgno pgno;
53862   int rc = SQLCIPHER_OK;
53863   MemPage *pPage = 0;
53864
53865   assert( cursorHoldsMutex(pCur) );
53866   assert( pCur->eState==CURSOR_VALID );
53867   while( rc==SQLCIPHER_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53868     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53869     pCur->aiIdx[pCur->iPage] = pPage->nCell;
53870     rc = moveToChild(pCur, pgno);
53871   }
53872   if( rc==SQLCIPHER_OK ){
53873     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
53874     pCur->info.nSize = 0;
53875     pCur->validNKey = 0;
53876   }
53877   return rc;
53878 }
53879
53880 /* Move the cursor to the first entry in the table.  Return SQLCIPHER_OK
53881 ** on success.  Set *pRes to 0 if the cursor actually points to something
53882 ** or set *pRes to 1 if the table is empty.
53883 */
53884 SQLCIPHER_PRIVATE int sqlcipher3BtreeFirst(BtCursor *pCur, int *pRes){
53885   int rc;
53886
53887   assert( cursorHoldsMutex(pCur) );
53888   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53889   rc = moveToRoot(pCur);
53890   if( rc==SQLCIPHER_OK ){
53891     if( pCur->eState==CURSOR_INVALID ){
53892       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53893       *pRes = 1;
53894     }else{
53895       assert( pCur->apPage[pCur->iPage]->nCell>0 );
53896       *pRes = 0;
53897       rc = moveToLeftmost(pCur);
53898     }
53899   }
53900   return rc;
53901 }
53902
53903 /* Move the cursor to the last entry in the table.  Return SQLCIPHER_OK
53904 ** on success.  Set *pRes to 0 if the cursor actually points to something
53905 ** or set *pRes to 1 if the table is empty.
53906 */
53907 SQLCIPHER_PRIVATE int sqlcipher3BtreeLast(BtCursor *pCur, int *pRes){
53908   int rc;
53909  
53910   assert( cursorHoldsMutex(pCur) );
53911   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53912
53913   /* If the cursor already points to the last entry, this is a no-op. */
53914   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
53915 #ifdef SQLCIPHER_DEBUG
53916     /* This block serves to assert() that the cursor really does point 
53917     ** to the last entry in the b-tree. */
53918     int ii;
53919     for(ii=0; ii<pCur->iPage; ii++){
53920       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
53921     }
53922     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
53923     assert( pCur->apPage[pCur->iPage]->leaf );
53924 #endif
53925     return SQLCIPHER_OK;
53926   }
53927
53928   rc = moveToRoot(pCur);
53929   if( rc==SQLCIPHER_OK ){
53930     if( CURSOR_INVALID==pCur->eState ){
53931       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53932       *pRes = 1;
53933     }else{
53934       assert( pCur->eState==CURSOR_VALID );
53935       *pRes = 0;
53936       rc = moveToRightmost(pCur);
53937       pCur->atLast = rc==SQLCIPHER_OK ?1:0;
53938     }
53939   }
53940   return rc;
53941 }
53942
53943 /* Move the cursor so that it points to an entry near the key 
53944 ** specified by pIdxKey or intKey.   Return a success code.
53945 **
53946 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
53947 ** must be NULL.  For index tables, pIdxKey is used and intKey
53948 ** is ignored.
53949 **
53950 ** If an exact match is not found, then the cursor is always
53951 ** left pointing at a leaf page which would hold the entry if it
53952 ** were present.  The cursor might point to an entry that comes
53953 ** before or after the key.
53954 **
53955 ** An integer is written into *pRes which is the result of
53956 ** comparing the key with the entry to which the cursor is 
53957 ** pointing.  The meaning of the integer written into
53958 ** *pRes is as follows:
53959 **
53960 **     *pRes<0      The cursor is left pointing at an entry that
53961 **                  is smaller than intKey/pIdxKey or if the table is empty
53962 **                  and the cursor is therefore left point to nothing.
53963 **
53964 **     *pRes==0     The cursor is left pointing at an entry that
53965 **                  exactly matches intKey/pIdxKey.
53966 **
53967 **     *pRes>0      The cursor is left pointing at an entry that
53968 **                  is larger than intKey/pIdxKey.
53969 **
53970 */
53971 SQLCIPHER_PRIVATE int sqlcipher3BtreeMovetoUnpacked(
53972   BtCursor *pCur,          /* The cursor to be moved */
53973   UnpackedRecord *pIdxKey, /* Unpacked index key */
53974   i64 intKey,              /* The table key */
53975   int biasRight,           /* If true, bias the search to the high end */
53976   int *pRes                /* Write search results here */
53977 ){
53978   int rc;
53979
53980   assert( cursorHoldsMutex(pCur) );
53981   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
53982   assert( pRes );
53983   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
53984
53985   /* If the cursor is already positioned at the point we are trying
53986   ** to move to, then just return without doing any work */
53987   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
53988    && pCur->apPage[0]->intKey 
53989   ){
53990     if( pCur->info.nKey==intKey ){
53991       *pRes = 0;
53992       return SQLCIPHER_OK;
53993     }
53994     if( pCur->atLast && pCur->info.nKey<intKey ){
53995       *pRes = -1;
53996       return SQLCIPHER_OK;
53997     }
53998   }
53999
54000   rc = moveToRoot(pCur);
54001   if( rc ){
54002     return rc;
54003   }
54004   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
54005   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
54006   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
54007   if( pCur->eState==CURSOR_INVALID ){
54008     *pRes = -1;
54009     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54010     return SQLCIPHER_OK;
54011   }
54012   assert( pCur->apPage[0]->intKey || pIdxKey );
54013   for(;;){
54014     int lwr, upr, idx;
54015     Pgno chldPg;
54016     MemPage *pPage = pCur->apPage[pCur->iPage];
54017     int c;
54018
54019     /* pPage->nCell must be greater than zero. If this is the root-page
54020     ** the cursor would have been INVALID above and this for(;;) loop
54021     ** not run. If this is not the root-page, then the moveToChild() routine
54022     ** would have already detected db corruption. Similarly, pPage must
54023     ** be the right kind (index or table) of b-tree page. Otherwise
54024     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
54025     assert( pPage->nCell>0 );
54026     assert( pPage->intKey==(pIdxKey==0) );
54027     lwr = 0;
54028     upr = pPage->nCell-1;
54029     if( biasRight ){
54030       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54031     }else{
54032       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54033     }
54034     for(;;){
54035       u8 *pCell;                          /* Pointer to current cell in pPage */
54036
54037       assert( idx==pCur->aiIdx[pCur->iPage] );
54038       pCur->info.nSize = 0;
54039       pCell = findCell(pPage, idx) + pPage->childPtrSize;
54040       if( pPage->intKey ){
54041         i64 nCellKey;
54042         if( pPage->hasData ){
54043           u32 dummy;
54044           pCell += getVarint32(pCell, dummy);
54045         }
54046         getVarint(pCell, (u64*)&nCellKey);
54047         if( nCellKey==intKey ){
54048           c = 0;
54049         }else if( nCellKey<intKey ){
54050           c = -1;
54051         }else{
54052           assert( nCellKey>intKey );
54053           c = +1;
54054         }
54055         pCur->validNKey = 1;
54056         pCur->info.nKey = nCellKey;
54057       }else{
54058         /* The maximum supported page-size is 65536 bytes. This means that
54059         ** the maximum number of record bytes stored on an index B-Tree
54060         ** page is less than 16384 bytes and may be stored as a 2-byte
54061         ** varint. This information is used to attempt to avoid parsing 
54062         ** the entire cell by checking for the cases where the record is 
54063         ** stored entirely within the b-tree page by inspecting the first 
54064         ** 2 bytes of the cell.
54065         */
54066         int nCell = pCell[0];
54067         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
54068           /* This branch runs if the record-size field of the cell is a
54069           ** single byte varint and the record fits entirely on the main
54070           ** b-tree page.  */
54071           c = sqlcipher3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54072         }else if( !(pCell[1] & 0x80) 
54073           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54074         ){
54075           /* The record-size field is a 2 byte varint and the record 
54076           ** fits entirely on the main b-tree page.  */
54077           c = sqlcipher3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54078         }else{
54079           /* The record flows over onto one or more overflow pages. In
54080           ** this case the whole cell needs to be parsed, a buffer allocated
54081           ** and accessPayload() used to retrieve the record into the
54082           ** buffer before VdbeRecordCompare() can be called. */
54083           void *pCellKey;
54084           u8 * const pCellBody = pCell - pPage->childPtrSize;
54085           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54086           nCell = (int)pCur->info.nKey;
54087           pCellKey = sqlcipher3Malloc( nCell );
54088           if( pCellKey==0 ){
54089             rc = SQLCIPHER_NOMEM;
54090             goto moveto_finish;
54091           }
54092           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54093           if( rc ){
54094             sqlcipher3_free(pCellKey);
54095             goto moveto_finish;
54096           }
54097           c = sqlcipher3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54098           sqlcipher3_free(pCellKey);
54099         }
54100       }
54101       if( c==0 ){
54102         if( pPage->intKey && !pPage->leaf ){
54103           lwr = idx;
54104           break;
54105         }else{
54106           *pRes = 0;
54107           rc = SQLCIPHER_OK;
54108           goto moveto_finish;
54109         }
54110       }
54111       if( c<0 ){
54112         lwr = idx+1;
54113       }else{
54114         upr = idx-1;
54115       }
54116       if( lwr>upr ){
54117         break;
54118       }
54119       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54120     }
54121     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54122     assert( pPage->isInit );
54123     if( pPage->leaf ){
54124       chldPg = 0;
54125     }else if( lwr>=pPage->nCell ){
54126       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54127     }else{
54128       chldPg = get4byte(findCell(pPage, lwr));
54129     }
54130     if( chldPg==0 ){
54131       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54132       *pRes = c;
54133       rc = SQLCIPHER_OK;
54134       goto moveto_finish;
54135     }
54136     pCur->aiIdx[pCur->iPage] = (u16)lwr;
54137     pCur->info.nSize = 0;
54138     pCur->validNKey = 0;
54139     rc = moveToChild(pCur, chldPg);
54140     if( rc ) goto moveto_finish;
54141   }
54142 moveto_finish:
54143   return rc;
54144 }
54145
54146
54147 /*
54148 ** Return TRUE if the cursor is not pointing at an entry of the table.
54149 **
54150 ** TRUE will be returned after a call to sqlcipher3BtreeNext() moves
54151 ** past the last entry in the table or sqlcipher3BtreePrev() moves past
54152 ** the first entry.  TRUE is also returned if the table is empty.
54153 */
54154 SQLCIPHER_PRIVATE int sqlcipher3BtreeEof(BtCursor *pCur){
54155   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54156   ** have been deleted? This API will need to change to return an error code
54157   ** as well as the boolean result value.
54158   */
54159   return (CURSOR_VALID!=pCur->eState);
54160 }
54161
54162 /*
54163 ** Advance the cursor to the next entry in the database.  If
54164 ** successful then set *pRes=0.  If the cursor
54165 ** was already pointing to the last entry in the database before
54166 ** this routine was called, then set *pRes=1.
54167 */
54168 SQLCIPHER_PRIVATE int sqlcipher3BtreeNext(BtCursor *pCur, int *pRes){
54169   int rc;
54170   int idx;
54171   MemPage *pPage;
54172
54173   assert( cursorHoldsMutex(pCur) );
54174   rc = restoreCursorPosition(pCur);
54175   if( rc!=SQLCIPHER_OK ){
54176     return rc;
54177   }
54178   assert( pRes!=0 );
54179   if( CURSOR_INVALID==pCur->eState ){
54180     *pRes = 1;
54181     return SQLCIPHER_OK;
54182   }
54183   if( pCur->skipNext>0 ){
54184     pCur->skipNext = 0;
54185     *pRes = 0;
54186     return SQLCIPHER_OK;
54187   }
54188   pCur->skipNext = 0;
54189
54190   pPage = pCur->apPage[pCur->iPage];
54191   idx = ++pCur->aiIdx[pCur->iPage];
54192   assert( pPage->isInit );
54193   assert( idx<=pPage->nCell );
54194
54195   pCur->info.nSize = 0;
54196   pCur->validNKey = 0;
54197   if( idx>=pPage->nCell ){
54198     if( !pPage->leaf ){
54199       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54200       if( rc ) return rc;
54201       rc = moveToLeftmost(pCur);
54202       *pRes = 0;
54203       return rc;
54204     }
54205     do{
54206       if( pCur->iPage==0 ){
54207         *pRes = 1;
54208         pCur->eState = CURSOR_INVALID;
54209         return SQLCIPHER_OK;
54210       }
54211       moveToParent(pCur);
54212       pPage = pCur->apPage[pCur->iPage];
54213     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54214     *pRes = 0;
54215     if( pPage->intKey ){
54216       rc = sqlcipher3BtreeNext(pCur, pRes);
54217     }else{
54218       rc = SQLCIPHER_OK;
54219     }
54220     return rc;
54221   }
54222   *pRes = 0;
54223   if( pPage->leaf ){
54224     return SQLCIPHER_OK;
54225   }
54226   rc = moveToLeftmost(pCur);
54227   return rc;
54228 }
54229
54230
54231 /*
54232 ** Step the cursor to the back to the previous entry in the database.  If
54233 ** successful then set *pRes=0.  If the cursor
54234 ** was already pointing to the first entry in the database before
54235 ** this routine was called, then set *pRes=1.
54236 */
54237 SQLCIPHER_PRIVATE int sqlcipher3BtreePrevious(BtCursor *pCur, int *pRes){
54238   int rc;
54239   MemPage *pPage;
54240
54241   assert( cursorHoldsMutex(pCur) );
54242   rc = restoreCursorPosition(pCur);
54243   if( rc!=SQLCIPHER_OK ){
54244     return rc;
54245   }
54246   pCur->atLast = 0;
54247   if( CURSOR_INVALID==pCur->eState ){
54248     *pRes = 1;
54249     return SQLCIPHER_OK;
54250   }
54251   if( pCur->skipNext<0 ){
54252     pCur->skipNext = 0;
54253     *pRes = 0;
54254     return SQLCIPHER_OK;
54255   }
54256   pCur->skipNext = 0;
54257
54258   pPage = pCur->apPage[pCur->iPage];
54259   assert( pPage->isInit );
54260   if( !pPage->leaf ){
54261     int idx = pCur->aiIdx[pCur->iPage];
54262     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54263     if( rc ){
54264       return rc;
54265     }
54266     rc = moveToRightmost(pCur);
54267   }else{
54268     while( pCur->aiIdx[pCur->iPage]==0 ){
54269       if( pCur->iPage==0 ){
54270         pCur->eState = CURSOR_INVALID;
54271         *pRes = 1;
54272         return SQLCIPHER_OK;
54273       }
54274       moveToParent(pCur);
54275     }
54276     pCur->info.nSize = 0;
54277     pCur->validNKey = 0;
54278
54279     pCur->aiIdx[pCur->iPage]--;
54280     pPage = pCur->apPage[pCur->iPage];
54281     if( pPage->intKey && !pPage->leaf ){
54282       rc = sqlcipher3BtreePrevious(pCur, pRes);
54283     }else{
54284       rc = SQLCIPHER_OK;
54285     }
54286   }
54287   *pRes = 0;
54288   return rc;
54289 }
54290
54291 /*
54292 ** Allocate a new page from the database file.
54293 **
54294 ** The new page is marked as dirty.  (In other words, sqlcipher3PagerWrite()
54295 ** has already been called on the new page.)  The new page has also
54296 ** been referenced and the calling routine is responsible for calling
54297 ** sqlcipher3PagerUnref() on the new page when it is done.
54298 **
54299 ** SQLCIPHER_OK is returned on success.  Any other return value indicates
54300 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
54301 ** Do not invoke sqlcipher3PagerUnref() on *ppPage if an error is returned.
54302 **
54303 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
54304 ** locate a page close to the page number "nearby".  This can be used in an
54305 ** attempt to keep related pages close to each other in the database file,
54306 ** which in turn can make database access faster.
54307 **
54308 ** If the "exact" parameter is not 0, and the page-number nearby exists 
54309 ** anywhere on the free-list, then it is guarenteed to be returned. This
54310 ** is only used by auto-vacuum databases when allocating a new table.
54311 */
54312 static int allocateBtreePage(
54313   BtShared *pBt, 
54314   MemPage **ppPage, 
54315   Pgno *pPgno, 
54316   Pgno nearby,
54317   u8 exact
54318 ){
54319   MemPage *pPage1;
54320   int rc;
54321   u32 n;     /* Number of pages on the freelist */
54322   u32 k;     /* Number of leaves on the trunk of the freelist */
54323   MemPage *pTrunk = 0;
54324   MemPage *pPrevTrunk = 0;
54325   Pgno mxPage;     /* Total size of the database file */
54326
54327   assert( sqlcipher3_mutex_held(pBt->mutex) );
54328   pPage1 = pBt->pPage1;
54329   mxPage = btreePagecount(pBt);
54330   n = get4byte(&pPage1->aData[36]);
54331   testcase( n==mxPage-1 );
54332   if( n>=mxPage ){
54333     return SQLCIPHER_CORRUPT_BKPT;
54334   }
54335   if( n>0 ){
54336     /* There are pages on the freelist.  Reuse one of those pages. */
54337     Pgno iTrunk;
54338     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54339     
54340     /* If the 'exact' parameter was true and a query of the pointer-map
54341     ** shows that the page 'nearby' is somewhere on the free-list, then
54342     ** the entire-list will be searched for that page.
54343     */
54344 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54345     if( exact && nearby<=mxPage ){
54346       u8 eType;
54347       assert( nearby>0 );
54348       assert( pBt->autoVacuum );
54349       rc = ptrmapGet(pBt, nearby, &eType, 0);
54350       if( rc ) return rc;
54351       if( eType==PTRMAP_FREEPAGE ){
54352         searchList = 1;
54353       }
54354       *pPgno = nearby;
54355     }
54356 #endif
54357
54358     /* Decrement the free-list count by 1. Set iTrunk to the index of the
54359     ** first free-list trunk page. iPrevTrunk is initially 1.
54360     */
54361     rc = sqlcipher3PagerWrite(pPage1->pDbPage);
54362     if( rc ) return rc;
54363     put4byte(&pPage1->aData[36], n-1);
54364
54365     /* The code within this loop is run only once if the 'searchList' variable
54366     ** is not true. Otherwise, it runs once for each trunk-page on the
54367     ** free-list until the page 'nearby' is located.
54368     */
54369     do {
54370       pPrevTrunk = pTrunk;
54371       if( pPrevTrunk ){
54372         iTrunk = get4byte(&pPrevTrunk->aData[0]);
54373       }else{
54374         iTrunk = get4byte(&pPage1->aData[32]);
54375       }
54376       testcase( iTrunk==mxPage );
54377       if( iTrunk>mxPage ){
54378         rc = SQLCIPHER_CORRUPT_BKPT;
54379       }else{
54380         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54381       }
54382       if( rc ){
54383         pTrunk = 0;
54384         goto end_allocate_page;
54385       }
54386       assert( pTrunk!=0 );
54387       assert( pTrunk->aData!=0 );
54388
54389       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54390       if( k==0 && !searchList ){
54391         /* The trunk has no leaves and the list is not being searched. 
54392         ** So extract the trunk page itself and use it as the newly 
54393         ** allocated page */
54394         assert( pPrevTrunk==0 );
54395         rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54396         if( rc ){
54397           goto end_allocate_page;
54398         }
54399         *pPgno = iTrunk;
54400         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54401         *ppPage = pTrunk;
54402         pTrunk = 0;
54403         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54404       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54405         /* Value of k is out of range.  Database corruption */
54406         rc = SQLCIPHER_CORRUPT_BKPT;
54407         goto end_allocate_page;
54408 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54409       }else if( searchList && nearby==iTrunk ){
54410         /* The list is being searched and this trunk page is the page
54411         ** to allocate, regardless of whether it has leaves.
54412         */
54413         assert( *pPgno==iTrunk );
54414         *ppPage = pTrunk;
54415         searchList = 0;
54416         rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54417         if( rc ){
54418           goto end_allocate_page;
54419         }
54420         if( k==0 ){
54421           if( !pPrevTrunk ){
54422             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54423           }else{
54424             rc = sqlcipher3PagerWrite(pPrevTrunk->pDbPage);
54425             if( rc!=SQLCIPHER_OK ){
54426               goto end_allocate_page;
54427             }
54428             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54429           }
54430         }else{
54431           /* The trunk page is required by the caller but it contains 
54432           ** pointers to free-list leaves. The first leaf becomes a trunk
54433           ** page in this case.
54434           */
54435           MemPage *pNewTrunk;
54436           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54437           if( iNewTrunk>mxPage ){ 
54438             rc = SQLCIPHER_CORRUPT_BKPT;
54439             goto end_allocate_page;
54440           }
54441           testcase( iNewTrunk==mxPage );
54442           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
54443           if( rc!=SQLCIPHER_OK ){
54444             goto end_allocate_page;
54445           }
54446           rc = sqlcipher3PagerWrite(pNewTrunk->pDbPage);
54447           if( rc!=SQLCIPHER_OK ){
54448             releasePage(pNewTrunk);
54449             goto end_allocate_page;
54450           }
54451           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54452           put4byte(&pNewTrunk->aData[4], k-1);
54453           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54454           releasePage(pNewTrunk);
54455           if( !pPrevTrunk ){
54456             assert( sqlcipher3PagerIswriteable(pPage1->pDbPage) );
54457             put4byte(&pPage1->aData[32], iNewTrunk);
54458           }else{
54459             rc = sqlcipher3PagerWrite(pPrevTrunk->pDbPage);
54460             if( rc ){
54461               goto end_allocate_page;
54462             }
54463             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54464           }
54465         }
54466         pTrunk = 0;
54467         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54468 #endif
54469       }else if( k>0 ){
54470         /* Extract a leaf from the trunk */
54471         u32 closest;
54472         Pgno iPage;
54473         unsigned char *aData = pTrunk->aData;
54474         if( nearby>0 ){
54475           u32 i;
54476           int dist;
54477           closest = 0;
54478           dist = sqlcipher3AbsInt32(get4byte(&aData[8]) - nearby);
54479           for(i=1; i<k; i++){
54480             int d2 = sqlcipher3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54481             if( d2<dist ){
54482               closest = i;
54483               dist = d2;
54484             }
54485           }
54486         }else{
54487           closest = 0;
54488         }
54489
54490         iPage = get4byte(&aData[8+closest*4]);
54491         testcase( iPage==mxPage );
54492         if( iPage>mxPage ){
54493           rc = SQLCIPHER_CORRUPT_BKPT;
54494           goto end_allocate_page;
54495         }
54496         testcase( iPage==mxPage );
54497         if( !searchList || iPage==nearby ){
54498           int noContent;
54499           *pPgno = iPage;
54500           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54501                  ": %d more free pages\n",
54502                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
54503           rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54504           if( rc ) goto end_allocate_page;
54505           if( closest<k-1 ){
54506             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54507           }
54508           put4byte(&aData[4], k-1);
54509           noContent = !btreeGetHasContent(pBt, *pPgno);
54510           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
54511           if( rc==SQLCIPHER_OK ){
54512             rc = sqlcipher3PagerWrite((*ppPage)->pDbPage);
54513             if( rc!=SQLCIPHER_OK ){
54514               releasePage(*ppPage);
54515             }
54516           }
54517           searchList = 0;
54518         }
54519       }
54520       releasePage(pPrevTrunk);
54521       pPrevTrunk = 0;
54522     }while( searchList );
54523   }else{
54524     /* There are no pages on the freelist, so create a new page at the
54525     ** end of the file */
54526     rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
54527     if( rc ) return rc;
54528     pBt->nPage++;
54529     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54530
54531 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54532     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54533       /* If *pPgno refers to a pointer-map page, allocate two new pages
54534       ** at the end of the file instead of one. The first allocated page
54535       ** becomes a new pointer-map page, the second is used by the caller.
54536       */
54537       MemPage *pPg = 0;
54538       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54539       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54540       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
54541       if( rc==SQLCIPHER_OK ){
54542         rc = sqlcipher3PagerWrite(pPg->pDbPage);
54543         releasePage(pPg);
54544       }
54545       if( rc ) return rc;
54546       pBt->nPage++;
54547       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54548     }
54549 #endif
54550     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54551     *pPgno = pBt->nPage;
54552
54553     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54554     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
54555     if( rc ) return rc;
54556     rc = sqlcipher3PagerWrite((*ppPage)->pDbPage);
54557     if( rc!=SQLCIPHER_OK ){
54558       releasePage(*ppPage);
54559     }
54560     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54561   }
54562
54563   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54564
54565 end_allocate_page:
54566   releasePage(pTrunk);
54567   releasePage(pPrevTrunk);
54568   if( rc==SQLCIPHER_OK ){
54569     if( sqlcipher3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54570       releasePage(*ppPage);
54571       return SQLCIPHER_CORRUPT_BKPT;
54572     }
54573     (*ppPage)->isInit = 0;
54574   }else{
54575     *ppPage = 0;
54576   }
54577   assert( rc!=SQLCIPHER_OK || sqlcipher3PagerIswriteable((*ppPage)->pDbPage) );
54578   return rc;
54579 }
54580
54581 /*
54582 ** This function is used to add page iPage to the database file free-list. 
54583 ** It is assumed that the page is not already a part of the free-list.
54584 **
54585 ** The value passed as the second argument to this function is optional.
54586 ** If the caller happens to have a pointer to the MemPage object 
54587 ** corresponding to page iPage handy, it may pass it as the second value. 
54588 ** Otherwise, it may pass NULL.
54589 **
54590 ** If a pointer to a MemPage object is passed as the second argument,
54591 ** its reference count is not altered by this function.
54592 */
54593 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54594   MemPage *pTrunk = 0;                /* Free-list trunk page */
54595   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
54596   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
54597   MemPage *pPage;                     /* Page being freed. May be NULL. */
54598   int rc;                             /* Return Code */
54599   int nFree;                          /* Initial number of pages on free-list */
54600
54601   assert( sqlcipher3_mutex_held(pBt->mutex) );
54602   assert( iPage>1 );
54603   assert( !pMemPage || pMemPage->pgno==iPage );
54604
54605   if( pMemPage ){
54606     pPage = pMemPage;
54607     sqlcipher3PagerRef(pPage->pDbPage);
54608   }else{
54609     pPage = btreePageLookup(pBt, iPage);
54610   }
54611
54612   /* Increment the free page count on pPage1 */
54613   rc = sqlcipher3PagerWrite(pPage1->pDbPage);
54614   if( rc ) goto freepage_out;
54615   nFree = get4byte(&pPage1->aData[36]);
54616   put4byte(&pPage1->aData[36], nFree+1);
54617
54618   if( pBt->secureDelete ){
54619     /* If the secure_delete option is enabled, then
54620     ** always fully overwrite deleted information with zeros.
54621     */
54622     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
54623      ||            ((rc = sqlcipher3PagerWrite(pPage->pDbPage))!=0)
54624     ){
54625       goto freepage_out;
54626     }
54627     memset(pPage->aData, 0, pPage->pBt->pageSize);
54628   }
54629
54630   /* If the database supports auto-vacuum, write an entry in the pointer-map
54631   ** to indicate that the page is free.
54632   */
54633   if( ISAUTOVACUUM ){
54634     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54635     if( rc ) goto freepage_out;
54636   }
54637
54638   /* Now manipulate the actual database free-list structure. There are two
54639   ** possibilities. If the free-list is currently empty, or if the first
54640   ** trunk page in the free-list is full, then this page will become a
54641   ** new free-list trunk page. Otherwise, it will become a leaf of the
54642   ** first trunk page in the current free-list. This block tests if it
54643   ** is possible to add the page as a new free-list leaf.
54644   */
54645   if( nFree!=0 ){
54646     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
54647
54648     iTrunk = get4byte(&pPage1->aData[32]);
54649     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54650     if( rc!=SQLCIPHER_OK ){
54651       goto freepage_out;
54652     }
54653
54654     nLeaf = get4byte(&pTrunk->aData[4]);
54655     assert( pBt->usableSize>32 );
54656     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54657       rc = SQLCIPHER_CORRUPT_BKPT;
54658       goto freepage_out;
54659     }
54660     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54661       /* In this case there is room on the trunk page to insert the page
54662       ** being freed as a new leaf.
54663       **
54664       ** Note that the trunk page is not really full until it contains
54665       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54666       ** coded.  But due to a coding error in versions of SQLite prior to
54667       ** 3.6.0, databases with freelist trunk pages holding more than
54668       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
54669       ** to maintain backwards compatibility with older versions of SQLite,
54670       ** we will continue to restrict the number of entries to usableSize/4 - 8
54671       ** for now.  At some point in the future (once everyone has upgraded
54672       ** to 3.6.0 or later) we should consider fixing the conditional above
54673       ** to read "usableSize/4-2" instead of "usableSize/4-8".
54674       */
54675       rc = sqlcipher3PagerWrite(pTrunk->pDbPage);
54676       if( rc==SQLCIPHER_OK ){
54677         put4byte(&pTrunk->aData[4], nLeaf+1);
54678         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54679         if( pPage && !pBt->secureDelete ){
54680           sqlcipher3PagerDontWrite(pPage->pDbPage);
54681         }
54682         rc = btreeSetHasContent(pBt, iPage);
54683       }
54684       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54685       goto freepage_out;
54686     }
54687   }
54688
54689   /* If control flows to this point, then it was not possible to add the
54690   ** the page being freed as a leaf page of the first trunk in the free-list.
54691   ** Possibly because the free-list is empty, or possibly because the 
54692   ** first trunk in the free-list is full. Either way, the page being freed
54693   ** will become the new first trunk page in the free-list.
54694   */
54695   if( pPage==0 && SQLCIPHER_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
54696     goto freepage_out;
54697   }
54698   rc = sqlcipher3PagerWrite(pPage->pDbPage);
54699   if( rc!=SQLCIPHER_OK ){
54700     goto freepage_out;
54701   }
54702   put4byte(pPage->aData, iTrunk);
54703   put4byte(&pPage->aData[4], 0);
54704   put4byte(&pPage1->aData[32], iPage);
54705   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54706
54707 freepage_out:
54708   if( pPage ){
54709     pPage->isInit = 0;
54710   }
54711   releasePage(pPage);
54712   releasePage(pTrunk);
54713   return rc;
54714 }
54715 static void freePage(MemPage *pPage, int *pRC){
54716   if( (*pRC)==SQLCIPHER_OK ){
54717     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54718   }
54719 }
54720
54721 /*
54722 ** Free any overflow pages associated with the given Cell.
54723 */
54724 static int clearCell(MemPage *pPage, unsigned char *pCell){
54725   BtShared *pBt = pPage->pBt;
54726   CellInfo info;
54727   Pgno ovflPgno;
54728   int rc;
54729   int nOvfl;
54730   u32 ovflPageSize;
54731
54732   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
54733   btreeParseCellPtr(pPage, pCell, &info);
54734   if( info.iOverflow==0 ){
54735     return SQLCIPHER_OK;  /* No overflow pages. Return without doing anything */
54736   }
54737   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
54738     return SQLCIPHER_CORRUPT;  /* Cell extends past end of page */
54739   }
54740   ovflPgno = get4byte(&pCell[info.iOverflow]);
54741   assert( pBt->usableSize > 4 );
54742   ovflPageSize = pBt->usableSize - 4;
54743   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
54744   assert( ovflPgno==0 || nOvfl>0 );
54745   while( nOvfl-- ){
54746     Pgno iNext = 0;
54747     MemPage *pOvfl = 0;
54748     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
54749       /* 0 is not a legal page number and page 1 cannot be an 
54750       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
54751       ** file the database must be corrupt. */
54752       return SQLCIPHER_CORRUPT_BKPT;
54753     }
54754     if( nOvfl ){
54755       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
54756       if( rc ) return rc;
54757     }
54758
54759     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
54760      && sqlcipher3PagerPageRefcount(pOvfl->pDbPage)!=1
54761     ){
54762       /* There is no reason any cursor should have an outstanding reference 
54763       ** to an overflow page belonging to a cell that is being deleted/updated.
54764       ** So if there exists more than one reference to this page, then it 
54765       ** must not really be an overflow page and the database must be corrupt. 
54766       ** It is helpful to detect this before calling freePage2(), as 
54767       ** freePage2() may zero the page contents if secure-delete mode is
54768       ** enabled. If this 'overflow' page happens to be a page that the
54769       ** caller is iterating through or using in some other way, this
54770       ** can be problematic.
54771       */
54772       rc = SQLCIPHER_CORRUPT_BKPT;
54773     }else{
54774       rc = freePage2(pBt, pOvfl, ovflPgno);
54775     }
54776
54777     if( pOvfl ){
54778       sqlcipher3PagerUnref(pOvfl->pDbPage);
54779     }
54780     if( rc ) return rc;
54781     ovflPgno = iNext;
54782   }
54783   return SQLCIPHER_OK;
54784 }
54785
54786 /*
54787 ** Create the byte sequence used to represent a cell on page pPage
54788 ** and write that byte sequence into pCell[].  Overflow pages are
54789 ** allocated and filled in as necessary.  The calling procedure
54790 ** is responsible for making sure sufficient space has been allocated
54791 ** for pCell[].
54792 **
54793 ** Note that pCell does not necessary need to point to the pPage->aData
54794 ** area.  pCell might point to some temporary storage.  The cell will
54795 ** be constructed in this temporary area then copied into pPage->aData
54796 ** later.
54797 */
54798 static int fillInCell(
54799   MemPage *pPage,                /* The page that contains the cell */
54800   unsigned char *pCell,          /* Complete text of the cell */
54801   const void *pKey, i64 nKey,    /* The key */
54802   const void *pData,int nData,   /* The data */
54803   int nZero,                     /* Extra zero bytes to append to pData */
54804   int *pnSize                    /* Write cell size here */
54805 ){
54806   int nPayload;
54807   const u8 *pSrc;
54808   int nSrc, n, rc;
54809   int spaceLeft;
54810   MemPage *pOvfl = 0;
54811   MemPage *pToRelease = 0;
54812   unsigned char *pPrior;
54813   unsigned char *pPayload;
54814   BtShared *pBt = pPage->pBt;
54815   Pgno pgnoOvfl = 0;
54816   int nHeader;
54817   CellInfo info;
54818
54819   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
54820
54821   /* pPage is not necessarily writeable since pCell might be auxiliary
54822   ** buffer space that is separate from the pPage buffer area */
54823   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
54824             || sqlcipher3PagerIswriteable(pPage->pDbPage) );
54825
54826   /* Fill in the header. */
54827   nHeader = 0;
54828   if( !pPage->leaf ){
54829     nHeader += 4;
54830   }
54831   if( pPage->hasData ){
54832     nHeader += putVarint(&pCell[nHeader], nData+nZero);
54833   }else{
54834     nData = nZero = 0;
54835   }
54836   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
54837   btreeParseCellPtr(pPage, pCell, &info);
54838   assert( info.nHeader==nHeader );
54839   assert( info.nKey==nKey );
54840   assert( info.nData==(u32)(nData+nZero) );
54841   
54842   /* Fill in the payload */
54843   nPayload = nData + nZero;
54844   if( pPage->intKey ){
54845     pSrc = pData;
54846     nSrc = nData;
54847     nData = 0;
54848   }else{ 
54849     if( NEVER(nKey>0x7fffffff || pKey==0) ){
54850       return SQLCIPHER_CORRUPT_BKPT;
54851     }
54852     nPayload += (int)nKey;
54853     pSrc = pKey;
54854     nSrc = (int)nKey;
54855   }
54856   *pnSize = info.nSize;
54857   spaceLeft = info.nLocal;
54858   pPayload = &pCell[nHeader];
54859   pPrior = &pCell[info.iOverflow];
54860
54861   while( nPayload>0 ){
54862     if( spaceLeft==0 ){
54863 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54864       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
54865       if( pBt->autoVacuum ){
54866         do{
54867           pgnoOvfl++;
54868         } while( 
54869           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
54870         );
54871       }
54872 #endif
54873       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
54874 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
54875       /* If the database supports auto-vacuum, and the second or subsequent
54876       ** overflow page is being allocated, add an entry to the pointer-map
54877       ** for that page now. 
54878       **
54879       ** If this is the first overflow page, then write a partial entry 
54880       ** to the pointer-map. If we write nothing to this pointer-map slot,
54881       ** then the optimistic overflow chain processing in clearCell()
54882       ** may misinterpret the uninitialised values and delete the
54883       ** wrong pages from the database.
54884       */
54885       if( pBt->autoVacuum && rc==SQLCIPHER_OK ){
54886         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
54887         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
54888         if( rc ){
54889           releasePage(pOvfl);
54890         }
54891       }
54892 #endif
54893       if( rc ){
54894         releasePage(pToRelease);
54895         return rc;
54896       }
54897
54898       /* If pToRelease is not zero than pPrior points into the data area
54899       ** of pToRelease.  Make sure pToRelease is still writeable. */
54900       assert( pToRelease==0 || sqlcipher3PagerIswriteable(pToRelease->pDbPage) );
54901
54902       /* If pPrior is part of the data area of pPage, then make sure pPage
54903       ** is still writeable */
54904       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
54905             || sqlcipher3PagerIswriteable(pPage->pDbPage) );
54906
54907       put4byte(pPrior, pgnoOvfl);
54908       releasePage(pToRelease);
54909       pToRelease = pOvfl;
54910       pPrior = pOvfl->aData;
54911       put4byte(pPrior, 0);
54912       pPayload = &pOvfl->aData[4];
54913       spaceLeft = pBt->usableSize - 4;
54914     }
54915     n = nPayload;
54916     if( n>spaceLeft ) n = spaceLeft;
54917
54918     /* If pToRelease is not zero than pPayload points into the data area
54919     ** of pToRelease.  Make sure pToRelease is still writeable. */
54920     assert( pToRelease==0 || sqlcipher3PagerIswriteable(pToRelease->pDbPage) );
54921
54922     /* If pPayload is part of the data area of pPage, then make sure pPage
54923     ** is still writeable */
54924     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
54925             || sqlcipher3PagerIswriteable(pPage->pDbPage) );
54926
54927     if( nSrc>0 ){
54928       if( n>nSrc ) n = nSrc;
54929       assert( pSrc );
54930       memcpy(pPayload, pSrc, n);
54931     }else{
54932       memset(pPayload, 0, n);
54933     }
54934     nPayload -= n;
54935     pPayload += n;
54936     pSrc += n;
54937     nSrc -= n;
54938     spaceLeft -= n;
54939     if( nSrc==0 ){
54940       nSrc = nData;
54941       pSrc = pData;
54942     }
54943   }
54944   releasePage(pToRelease);
54945   return SQLCIPHER_OK;
54946 }
54947
54948 /*
54949 ** Remove the i-th cell from pPage.  This routine effects pPage only.
54950 ** The cell content is not freed or deallocated.  It is assumed that
54951 ** the cell content has been copied someplace else.  This routine just
54952 ** removes the reference to the cell from pPage.
54953 **
54954 ** "sz" must be the number of bytes in the cell.
54955 */
54956 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
54957   u32 pc;         /* Offset to cell content of cell being deleted */
54958   u8 *data;       /* pPage->aData */
54959   u8 *ptr;        /* Used to move bytes around within data[] */
54960   u8 *endPtr;     /* End of loop */
54961   int rc;         /* The return code */
54962   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
54963
54964   if( *pRC ) return;
54965
54966   assert( idx>=0 && idx<pPage->nCell );
54967   assert( sz==cellSize(pPage, idx) );
54968   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
54969   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
54970   data = pPage->aData;
54971   ptr = &data[pPage->cellOffset + 2*idx];
54972   pc = get2byte(ptr);
54973   hdr = pPage->hdrOffset;
54974   testcase( pc==get2byte(&data[hdr+5]) );
54975   testcase( pc+sz==pPage->pBt->usableSize );
54976   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
54977     *pRC = SQLCIPHER_CORRUPT_BKPT;
54978     return;
54979   }
54980   rc = freeSpace(pPage, pc, sz);
54981   if( rc ){
54982     *pRC = rc;
54983     return;
54984   }
54985   endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
54986   assert( (SQLCIPHER_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54987   while( ptr<endPtr ){
54988     *(u16*)ptr = *(u16*)&ptr[2];
54989     ptr += 2;
54990   }
54991   pPage->nCell--;
54992   put2byte(&data[hdr+3], pPage->nCell);
54993   pPage->nFree += 2;
54994 }
54995
54996 /*
54997 ** Insert a new cell on pPage at cell index "i".  pCell points to the
54998 ** content of the cell.
54999 **
55000 ** If the cell content will fit on the page, then put it there.  If it
55001 ** will not fit, then make a copy of the cell content into pTemp if
55002 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
55003 ** in pPage->aOvfl[] and make it point to the cell content (either
55004 ** in pTemp or the original pCell) and also record its index. 
55005 ** Allocating a new entry in pPage->aCell[] implies that 
55006 ** pPage->nOverflow is incremented.
55007 **
55008 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
55009 ** cell. The caller will overwrite them after this function returns. If
55010 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
55011 ** (but pCell+nSkip is always valid).
55012 */
55013 static void insertCell(
55014   MemPage *pPage,   /* Page into which we are copying */
55015   int i,            /* New cell becomes the i-th cell of the page */
55016   u8 *pCell,        /* Content of the new cell */
55017   int sz,           /* Bytes of content in pCell */
55018   u8 *pTemp,        /* Temp storage space for pCell, if needed */
55019   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
55020   int *pRC          /* Read and write return code from here */
55021 ){
55022   int idx = 0;      /* Where to write new cell content in data[] */
55023   int j;            /* Loop counter */
55024   int end;          /* First byte past the last cell pointer in data[] */
55025   int ins;          /* Index in data[] where new cell pointer is inserted */
55026   int cellOffset;   /* Address of first cell pointer in data[] */
55027   u8 *data;         /* The content of the whole page */
55028   u8 *ptr;          /* Used for moving information around in data[] */
55029   u8 *endPtr;       /* End of the loop */
55030
55031   int nSkip = (iChild ? 4 : 0);
55032
55033   if( *pRC ) return;
55034
55035   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55036   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55037   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
55038   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
55039   /* The cell should normally be sized correctly.  However, when moving a
55040   ** malformed cell from a leaf page to an interior page, if the cell size
55041   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55042   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
55043   ** the term after the || in the following assert(). */
55044   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55045   if( pPage->nOverflow || sz+2>pPage->nFree ){
55046     if( pTemp ){
55047       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55048       pCell = pTemp;
55049     }
55050     if( iChild ){
55051       put4byte(pCell, iChild);
55052     }
55053     j = pPage->nOverflow++;
55054     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
55055     pPage->aOvfl[j].pCell = pCell;
55056     pPage->aOvfl[j].idx = (u16)i;
55057   }else{
55058     int rc = sqlcipher3PagerWrite(pPage->pDbPage);
55059     if( rc!=SQLCIPHER_OK ){
55060       *pRC = rc;
55061       return;
55062     }
55063     assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
55064     data = pPage->aData;
55065     cellOffset = pPage->cellOffset;
55066     end = cellOffset + 2*pPage->nCell;
55067     ins = cellOffset + 2*i;
55068     rc = allocateSpace(pPage, sz, &idx);
55069     if( rc ){ *pRC = rc; return; }
55070     /* The allocateSpace() routine guarantees the following two properties
55071     ** if it returns success */
55072     assert( idx >= end+2 );
55073     assert( idx+sz <= (int)pPage->pBt->usableSize );
55074     pPage->nCell++;
55075     pPage->nFree -= (u16)(2 + sz);
55076     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55077     if( iChild ){
55078       put4byte(&data[idx], iChild);
55079     }
55080     ptr = &data[end];
55081     endPtr = &data[ins];
55082     assert( (SQLCIPHER_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55083     while( ptr>endPtr ){
55084       *(u16*)ptr = *(u16*)&ptr[-2];
55085       ptr -= 2;
55086     }
55087     put2byte(&data[ins], idx);
55088     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55089 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
55090     if( pPage->pBt->autoVacuum ){
55091       /* The cell may contain a pointer to an overflow page. If so, write
55092       ** the entry for the overflow page into the pointer map.
55093       */
55094       ptrmapPutOvflPtr(pPage, pCell, pRC);
55095     }
55096 #endif
55097   }
55098 }
55099
55100 /*
55101 ** Add a list of cells to a page.  The page should be initially empty.
55102 ** The cells are guaranteed to fit on the page.
55103 */
55104 static void assemblePage(
55105   MemPage *pPage,   /* The page to be assemblied */
55106   int nCell,        /* The number of cells to add to this page */
55107   u8 **apCell,      /* Pointers to cell bodies */
55108   u16 *aSize        /* Sizes of the cells */
55109 ){
55110   int i;            /* Loop counter */
55111   u8 *pCellptr;     /* Address of next cell pointer */
55112   int cellbody;     /* Address of next cell body */
55113   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55114   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55115   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55116
55117   assert( pPage->nOverflow==0 );
55118   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
55119   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55120             && (int)MX_CELL(pPage->pBt)<=10921);
55121   assert( sqlcipher3PagerIswriteable(pPage->pDbPage) );
55122
55123   /* Check that the page has just been zeroed by zeroPage() */
55124   assert( pPage->nCell==0 );
55125   assert( get2byteNotZero(&data[hdr+5])==nUsable );
55126
55127   pCellptr = &data[pPage->cellOffset + nCell*2];
55128   cellbody = nUsable;
55129   for(i=nCell-1; i>=0; i--){
55130     u16 sz = aSize[i];
55131     pCellptr -= 2;
55132     cellbody -= sz;
55133     put2byte(pCellptr, cellbody);
55134     memcpy(&data[cellbody], apCell[i], sz);
55135   }
55136   put2byte(&data[hdr+3], nCell);
55137   put2byte(&data[hdr+5], cellbody);
55138   pPage->nFree -= (nCell*2 + nUsable - cellbody);
55139   pPage->nCell = (u16)nCell;
55140 }
55141
55142 /*
55143 ** The following parameters determine how many adjacent pages get involved
55144 ** in a balancing operation.  NN is the number of neighbors on either side
55145 ** of the page that participate in the balancing operation.  NB is the
55146 ** total number of pages that participate, including the target page and
55147 ** NN neighbors on either side.
55148 **
55149 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
55150 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55151 ** in exchange for a larger degradation in INSERT and UPDATE performance.
55152 ** The value of NN appears to give the best results overall.
55153 */
55154 #define NN 1             /* Number of neighbors on either side of pPage */
55155 #define NB (NN*2+1)      /* Total pages involved in the balance */
55156
55157
55158 #ifndef SQLCIPHER_OMIT_QUICKBALANCE
55159 /*
55160 ** This version of balance() handles the common special case where
55161 ** a new entry is being inserted on the extreme right-end of the
55162 ** tree, in other words, when the new entry will become the largest
55163 ** entry in the tree.
55164 **
55165 ** Instead of trying to balance the 3 right-most leaf pages, just add
55166 ** a new page to the right-hand side and put the one new entry in
55167 ** that page.  This leaves the right side of the tree somewhat
55168 ** unbalanced.  But odds are that we will be inserting new entries
55169 ** at the end soon afterwards so the nearly empty page will quickly
55170 ** fill up.  On average.
55171 **
55172 ** pPage is the leaf page which is the right-most page in the tree.
55173 ** pParent is its parent.  pPage must have a single overflow entry
55174 ** which is also the right-most entry on the page.
55175 **
55176 ** The pSpace buffer is used to store a temporary copy of the divider
55177 ** cell that will be inserted into pParent. Such a cell consists of a 4
55178 ** byte page number followed by a variable length integer. In other
55179 ** words, at most 13 bytes. Hence the pSpace buffer must be at
55180 ** least 13 bytes in size.
55181 */
55182 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55183   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55184   MemPage *pNew;                       /* Newly allocated page */
55185   int rc;                              /* Return Code */
55186   Pgno pgnoNew;                        /* Page number of pNew */
55187
55188   assert( sqlcipher3_mutex_held(pPage->pBt->mutex) );
55189   assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55190   assert( pPage->nOverflow==1 );
55191
55192   /* This error condition is now caught prior to reaching this function */
55193   if( pPage->nCell<=0 ) return SQLCIPHER_CORRUPT_BKPT;
55194
55195   /* Allocate a new page. This page will become the right-sibling of 
55196   ** pPage. Make the parent page writable, so that the new divider cell
55197   ** may be inserted. If both these operations are successful, proceed.
55198   */
55199   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55200
55201   if( rc==SQLCIPHER_OK ){
55202
55203     u8 *pOut = &pSpace[4];
55204     u8 *pCell = pPage->aOvfl[0].pCell;
55205     u16 szCell = cellSizePtr(pPage, pCell);
55206     u8 *pStop;
55207
55208     assert( sqlcipher3PagerIswriteable(pNew->pDbPage) );
55209     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55210     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55211     assemblePage(pNew, 1, &pCell, &szCell);
55212
55213     /* If this is an auto-vacuum database, update the pointer map
55214     ** with entries for the new page, and any pointer from the 
55215     ** cell on the page to an overflow page. If either of these
55216     ** operations fails, the return code is set, but the contents
55217     ** of the parent page are still manipulated by thh code below.
55218     ** That is Ok, at this point the parent page is guaranteed to
55219     ** be marked as dirty. Returning an error code will cause a
55220     ** rollback, undoing any changes made to the parent page.
55221     */
55222     if( ISAUTOVACUUM ){
55223       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55224       if( szCell>pNew->minLocal ){
55225         ptrmapPutOvflPtr(pNew, pCell, &rc);
55226       }
55227     }
55228   
55229     /* Create a divider cell to insert into pParent. The divider cell
55230     ** consists of a 4-byte page number (the page number of pPage) and
55231     ** a variable length key value (which must be the same value as the
55232     ** largest key on pPage).
55233     **
55234     ** To find the largest key value on pPage, first find the right-most 
55235     ** cell on pPage. The first two fields of this cell are the 
55236     ** record-length (a variable length integer at most 32-bits in size)
55237     ** and the key value (a variable length integer, may have any value).
55238     ** The first of the while(...) loops below skips over the record-length
55239     ** field. The second while(...) loop copies the key value from the
55240     ** cell on pPage into the pSpace buffer.
55241     */
55242     pCell = findCell(pPage, pPage->nCell-1);
55243     pStop = &pCell[9];
55244     while( (*(pCell++)&0x80) && pCell<pStop );
55245     pStop = &pCell[9];
55246     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55247
55248     /* Insert the new divider cell into pParent. */
55249     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55250                0, pPage->pgno, &rc);
55251
55252     /* Set the right-child pointer of pParent to point to the new page. */
55253     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55254   
55255     /* Release the reference to the new page. */
55256     releasePage(pNew);
55257   }
55258
55259   return rc;
55260 }
55261 #endif /* SQLCIPHER_OMIT_QUICKBALANCE */
55262
55263 #if 0
55264 /*
55265 ** This function does not contribute anything to the operation of SQLite.
55266 ** it is sometimes activated temporarily while debugging code responsible 
55267 ** for setting pointer-map entries.
55268 */
55269 static int ptrmapCheckPages(MemPage **apPage, int nPage){
55270   int i, j;
55271   for(i=0; i<nPage; i++){
55272     Pgno n;
55273     u8 e;
55274     MemPage *pPage = apPage[i];
55275     BtShared *pBt = pPage->pBt;
55276     assert( pPage->isInit );
55277
55278     for(j=0; j<pPage->nCell; j++){
55279       CellInfo info;
55280       u8 *z;
55281      
55282       z = findCell(pPage, j);
55283       btreeParseCellPtr(pPage, z, &info);
55284       if( info.iOverflow ){
55285         Pgno ovfl = get4byte(&z[info.iOverflow]);
55286         ptrmapGet(pBt, ovfl, &e, &n);
55287         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55288       }
55289       if( !pPage->leaf ){
55290         Pgno child = get4byte(z);
55291         ptrmapGet(pBt, child, &e, &n);
55292         assert( n==pPage->pgno && e==PTRMAP_BTREE );
55293       }
55294     }
55295     if( !pPage->leaf ){
55296       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55297       ptrmapGet(pBt, child, &e, &n);
55298       assert( n==pPage->pgno && e==PTRMAP_BTREE );
55299     }
55300   }
55301   return 1;
55302 }
55303 #endif
55304
55305 /*
55306 ** This function is used to copy the contents of the b-tree node stored 
55307 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55308 ** the pointer-map entries for each child page are updated so that the
55309 ** parent page stored in the pointer map is page pTo. If pFrom contained
55310 ** any cells with overflow page pointers, then the corresponding pointer
55311 ** map entries are also updated so that the parent page is page pTo.
55312 **
55313 ** If pFrom is currently carrying any overflow cells (entries in the
55314 ** MemPage.aOvfl[] array), they are not copied to pTo. 
55315 **
55316 ** Before returning, page pTo is reinitialized using btreeInitPage().
55317 **
55318 ** The performance of this function is not critical. It is only used by 
55319 ** the balance_shallower() and balance_deeper() procedures, neither of
55320 ** which are called often under normal circumstances.
55321 */
55322 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55323   if( (*pRC)==SQLCIPHER_OK ){
55324     BtShared * const pBt = pFrom->pBt;
55325     u8 * const aFrom = pFrom->aData;
55326     u8 * const aTo = pTo->aData;
55327     int const iFromHdr = pFrom->hdrOffset;
55328     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55329     int rc;
55330     int iData;
55331   
55332   
55333     assert( pFrom->isInit );
55334     assert( pFrom->nFree>=iToHdr );
55335     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55336   
55337     /* Copy the b-tree node content from page pFrom to page pTo. */
55338     iData = get2byte(&aFrom[iFromHdr+5]);
55339     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55340     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55341   
55342     /* Reinitialize page pTo so that the contents of the MemPage structure
55343     ** match the new data. The initialization of pTo can actually fail under
55344     ** fairly obscure circumstances, even though it is a copy of initialized 
55345     ** page pFrom.
55346     */
55347     pTo->isInit = 0;
55348     rc = btreeInitPage(pTo);
55349     if( rc!=SQLCIPHER_OK ){
55350       *pRC = rc;
55351       return;
55352     }
55353   
55354     /* If this is an auto-vacuum database, update the pointer-map entries
55355     ** for any b-tree or overflow pages that pTo now contains the pointers to.
55356     */
55357     if( ISAUTOVACUUM ){
55358       *pRC = setChildPtrmaps(pTo);
55359     }
55360   }
55361 }
55362
55363 /*
55364 ** This routine redistributes cells on the iParentIdx'th child of pParent
55365 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
55366 ** same amount of free space. Usually a single sibling on either side of the
55367 ** page are used in the balancing, though both siblings might come from one
55368 ** side if the page is the first or last child of its parent. If the page 
55369 ** has fewer than 2 siblings (something which can only happen if the page
55370 ** is a root page or a child of a root page) then all available siblings
55371 ** participate in the balancing.
55372 **
55373 ** The number of siblings of the page might be increased or decreased by 
55374 ** one or two in an effort to keep pages nearly full but not over full. 
55375 **
55376 ** Note that when this routine is called, some of the cells on the page
55377 ** might not actually be stored in MemPage.aData[]. This can happen
55378 ** if the page is overfull. This routine ensures that all cells allocated
55379 ** to the page and its siblings fit into MemPage.aData[] before returning.
55380 **
55381 ** In the course of balancing the page and its siblings, cells may be
55382 ** inserted into or removed from the parent page (pParent). Doing so
55383 ** may cause the parent page to become overfull or underfull. If this
55384 ** happens, it is the responsibility of the caller to invoke the correct
55385 ** balancing routine to fix this problem (see the balance() routine). 
55386 **
55387 ** If this routine fails for any reason, it might leave the database
55388 ** in a corrupted state. So if this routine fails, the database should
55389 ** be rolled back.
55390 **
55391 ** The third argument to this function, aOvflSpace, is a pointer to a
55392 ** buffer big enough to hold one page. If while inserting cells into the parent
55393 ** page (pParent) the parent page becomes overfull, this buffer is
55394 ** used to store the parent's overflow cells. Because this function inserts
55395 ** a maximum of four divider cells into the parent page, and the maximum
55396 ** size of a cell stored within an internal node is always less than 1/4
55397 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55398 ** enough for all overflow cells.
55399 **
55400 ** If aOvflSpace is set to a null pointer, this function returns 
55401 ** SQLCIPHER_NOMEM.
55402 */
55403 static int balance_nonroot(
55404   MemPage *pParent,               /* Parent page of siblings being balanced */
55405   int iParentIdx,                 /* Index of "the page" in pParent */
55406   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55407   int isRoot                      /* True if pParent is a root-page */
55408 ){
55409   BtShared *pBt;               /* The whole database */
55410   int nCell = 0;               /* Number of cells in apCell[] */
55411   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55412   int nNew = 0;                /* Number of pages in apNew[] */
55413   int nOld;                    /* Number of pages in apOld[] */
55414   int i, j, k;                 /* Loop counters */
55415   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55416   int rc = SQLCIPHER_OK;          /* The return code */
55417   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55418   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55419   int usableSpace;             /* Bytes in pPage beyond the header */
55420   int pageFlags;               /* Value of pPage->aData[0] */
55421   int subtotal;                /* Subtotal of bytes in cells on one page */
55422   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55423   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55424   int szScratch;               /* Size of scratch memory requested */
55425   MemPage *apOld[NB];          /* pPage and up to two siblings */
55426   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55427   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55428   u8 *pRight;                  /* Location in parent of right-sibling pointer */
55429   u8 *apDiv[NB-1];             /* Divider cells in pParent */
55430   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55431   int szNew[NB+2];             /* Combined size of cells place on i-th page */
55432   u8 **apCell = 0;             /* All cells begin balanced */
55433   u16 *szCell;                 /* Local size of all cells in apCell[] */
55434   u8 *aSpace1;                 /* Space for copies of dividers cells */
55435   Pgno pgno;                   /* Temp var to store a page number in */
55436
55437   pBt = pParent->pBt;
55438   assert( sqlcipher3_mutex_held(pBt->mutex) );
55439   assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55440
55441 #if 0
55442   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55443 #endif
55444
55445   /* At this point pParent may have at most one overflow cell. And if
55446   ** this overflow cell is present, it must be the cell with 
55447   ** index iParentIdx. This scenario comes about when this function
55448   ** is called (indirectly) from sqlcipher3BtreeDelete().
55449   */
55450   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55451   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
55452
55453   if( !aOvflSpace ){
55454     return SQLCIPHER_NOMEM;
55455   }
55456
55457   /* Find the sibling pages to balance. Also locate the cells in pParent 
55458   ** that divide the siblings. An attempt is made to find NN siblings on 
55459   ** either side of pPage. More siblings are taken from one side, however, 
55460   ** if there are fewer than NN siblings on the other side. If pParent
55461   ** has NB or fewer children then all children of pParent are taken.  
55462   **
55463   ** This loop also drops the divider cells from the parent page. This
55464   ** way, the remainder of the function does not have to deal with any
55465   ** overflow cells in the parent page, since if any existed they will
55466   ** have already been removed.
55467   */
55468   i = pParent->nOverflow + pParent->nCell;
55469   if( i<2 ){
55470     nxDiv = 0;
55471     nOld = i+1;
55472   }else{
55473     nOld = 3;
55474     if( iParentIdx==0 ){                 
55475       nxDiv = 0;
55476     }else if( iParentIdx==i ){
55477       nxDiv = i-2;
55478     }else{
55479       nxDiv = iParentIdx-1;
55480     }
55481     i = 2;
55482   }
55483   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55484     pRight = &pParent->aData[pParent->hdrOffset+8];
55485   }else{
55486     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55487   }
55488   pgno = get4byte(pRight);
55489   while( 1 ){
55490     rc = getAndInitPage(pBt, pgno, &apOld[i]);
55491     if( rc ){
55492       memset(apOld, 0, (i+1)*sizeof(MemPage*));
55493       goto balance_cleanup;
55494     }
55495     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55496     if( (i--)==0 ) break;
55497
55498     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
55499       apDiv[i] = pParent->aOvfl[0].pCell;
55500       pgno = get4byte(apDiv[i]);
55501       szNew[i] = cellSizePtr(pParent, apDiv[i]);
55502       pParent->nOverflow = 0;
55503     }else{
55504       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55505       pgno = get4byte(apDiv[i]);
55506       szNew[i] = cellSizePtr(pParent, apDiv[i]);
55507
55508       /* Drop the cell from the parent page. apDiv[i] still points to
55509       ** the cell within the parent, even though it has been dropped.
55510       ** This is safe because dropping a cell only overwrites the first
55511       ** four bytes of it, and this function does not need the first
55512       ** four bytes of the divider cell. So the pointer is safe to use
55513       ** later on.  
55514       **
55515       ** But not if we are in secure-delete mode. In secure-delete mode,
55516       ** the dropCell() routine will overwrite the entire cell with zeroes.
55517       ** In this case, temporarily copy the cell into the aOvflSpace[]
55518       ** buffer. It will be copied out again as soon as the aSpace[] buffer
55519       ** is allocated.  */
55520       if( pBt->secureDelete ){
55521         int iOff;
55522
55523         iOff = SQLCIPHER_PTR_TO_INT(apDiv[i]) - SQLCIPHER_PTR_TO_INT(pParent->aData);
55524         if( (iOff+szNew[i])>(int)pBt->usableSize ){
55525           rc = SQLCIPHER_CORRUPT_BKPT;
55526           memset(apOld, 0, (i+1)*sizeof(MemPage*));
55527           goto balance_cleanup;
55528         }else{
55529           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55530           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55531         }
55532       }
55533       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55534     }
55535   }
55536
55537   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55538   ** alignment */
55539   nMaxCells = (nMaxCells + 3)&~3;
55540
55541   /*
55542   ** Allocate space for memory structures
55543   */
55544   k = pBt->pageSize + ROUND8(sizeof(MemPage));
55545   szScratch =
55546        nMaxCells*sizeof(u8*)                       /* apCell */
55547      + nMaxCells*sizeof(u16)                       /* szCell */
55548      + pBt->pageSize                               /* aSpace1 */
55549      + k*nOld;                                     /* Page copies (apCopy) */
55550   apCell = sqlcipher3ScratchMalloc( szScratch ); 
55551   if( apCell==0 ){
55552     rc = SQLCIPHER_NOMEM;
55553     goto balance_cleanup;
55554   }
55555   szCell = (u16*)&apCell[nMaxCells];
55556   aSpace1 = (u8*)&szCell[nMaxCells];
55557   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55558
55559   /*
55560   ** Load pointers to all cells on sibling pages and the divider cells
55561   ** into the local apCell[] array.  Make copies of the divider cells
55562   ** into space obtained from aSpace1[] and remove the the divider Cells
55563   ** from pParent.
55564   **
55565   ** If the siblings are on leaf pages, then the child pointers of the
55566   ** divider cells are stripped from the cells before they are copied
55567   ** into aSpace1[].  In this way, all cells in apCell[] are without
55568   ** child pointers.  If siblings are not leaves, then all cell in
55569   ** apCell[] include child pointers.  Either way, all cells in apCell[]
55570   ** are alike.
55571   **
55572   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
55573   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
55574   */
55575   leafCorrection = apOld[0]->leaf*4;
55576   leafData = apOld[0]->hasData;
55577   for(i=0; i<nOld; i++){
55578     int limit;
55579     
55580     /* Before doing anything else, take a copy of the i'th original sibling
55581     ** The rest of this function will use data from the copies rather
55582     ** that the original pages since the original pages will be in the
55583     ** process of being overwritten.  */
55584     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55585     memcpy(pOld, apOld[i], sizeof(MemPage));
55586     pOld->aData = (void*)&pOld[1];
55587     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55588
55589     limit = pOld->nCell+pOld->nOverflow;
55590     if( pOld->nOverflow>0 ){
55591       for(j=0; j<limit; j++){
55592         assert( nCell<nMaxCells );
55593         apCell[nCell] = findOverflowCell(pOld, j);
55594         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55595         nCell++;
55596       }
55597     }else{
55598       u8 *aData = pOld->aData;
55599       u16 maskPage = pOld->maskPage;
55600       u16 cellOffset = pOld->cellOffset;
55601       for(j=0; j<limit; j++){
55602         assert( nCell<nMaxCells );
55603         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55604         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55605         nCell++;
55606       }
55607     }       
55608     if( i<nOld-1 && !leafData){
55609       u16 sz = (u16)szNew[i];
55610       u8 *pTemp;
55611       assert( nCell<nMaxCells );
55612       szCell[nCell] = sz;
55613       pTemp = &aSpace1[iSpace1];
55614       iSpace1 += sz;
55615       assert( sz<=pBt->maxLocal+23 );
55616       assert( iSpace1 <= (int)pBt->pageSize );
55617       memcpy(pTemp, apDiv[i], sz);
55618       apCell[nCell] = pTemp+leafCorrection;
55619       assert( leafCorrection==0 || leafCorrection==4 );
55620       szCell[nCell] = szCell[nCell] - leafCorrection;
55621       if( !pOld->leaf ){
55622         assert( leafCorrection==0 );
55623         assert( pOld->hdrOffset==0 );
55624         /* The right pointer of the child page pOld becomes the left
55625         ** pointer of the divider cell */
55626         memcpy(apCell[nCell], &pOld->aData[8], 4);
55627       }else{
55628         assert( leafCorrection==4 );
55629         if( szCell[nCell]<4 ){
55630           /* Do not allow any cells smaller than 4 bytes. */
55631           szCell[nCell] = 4;
55632         }
55633       }
55634       nCell++;
55635     }
55636   }
55637
55638   /*
55639   ** Figure out the number of pages needed to hold all nCell cells.
55640   ** Store this number in "k".  Also compute szNew[] which is the total
55641   ** size of all cells on the i-th page and cntNew[] which is the index
55642   ** in apCell[] of the cell that divides page i from page i+1.  
55643   ** cntNew[k] should equal nCell.
55644   **
55645   ** Values computed by this block:
55646   **
55647   **           k: The total number of sibling pages
55648   **    szNew[i]: Spaced used on the i-th sibling page.
55649   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55650   **              the right of the i-th sibling page.
55651   ** usableSpace: Number of bytes of space available on each sibling.
55652   ** 
55653   */
55654   usableSpace = pBt->usableSize - 12 + leafCorrection;
55655   for(subtotal=k=i=0; i<nCell; i++){
55656     assert( i<nMaxCells );
55657     subtotal += szCell[i] + 2;
55658     if( subtotal > usableSpace ){
55659       szNew[k] = subtotal - szCell[i];
55660       cntNew[k] = i;
55661       if( leafData ){ i--; }
55662       subtotal = 0;
55663       k++;
55664       if( k>NB+1 ){ rc = SQLCIPHER_CORRUPT_BKPT; goto balance_cleanup; }
55665     }
55666   }
55667   szNew[k] = subtotal;
55668   cntNew[k] = nCell;
55669   k++;
55670
55671   /*
55672   ** The packing computed by the previous block is biased toward the siblings
55673   ** on the left side.  The left siblings are always nearly full, while the
55674   ** right-most sibling might be nearly empty.  This block of code attempts
55675   ** to adjust the packing of siblings to get a better balance.
55676   **
55677   ** This adjustment is more than an optimization.  The packing above might
55678   ** be so out of balance as to be illegal.  For example, the right-most
55679   ** sibling might be completely empty.  This adjustment is not optional.
55680   */
55681   for(i=k-1; i>0; i--){
55682     int szRight = szNew[i];  /* Size of sibling on the right */
55683     int szLeft = szNew[i-1]; /* Size of sibling on the left */
55684     int r;              /* Index of right-most cell in left sibling */
55685     int d;              /* Index of first cell to the left of right sibling */
55686
55687     r = cntNew[i-1] - 1;
55688     d = r + 1 - leafData;
55689     assert( d<nMaxCells );
55690     assert( r<nMaxCells );
55691     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
55692       szRight += szCell[d] + 2;
55693       szLeft -= szCell[r] + 2;
55694       cntNew[i-1]--;
55695       r = cntNew[i-1] - 1;
55696       d = r + 1 - leafData;
55697     }
55698     szNew[i] = szRight;
55699     szNew[i-1] = szLeft;
55700   }
55701
55702   /* Either we found one or more cells (cntnew[0])>0) or pPage is
55703   ** a virtual root page.  A virtual root page is when the real root
55704   ** page is page 1 and we are the only child of that page.
55705   */
55706   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55707
55708   TRACE(("BALANCE: old: %d %d %d  ",
55709     apOld[0]->pgno, 
55710     nOld>=2 ? apOld[1]->pgno : 0,
55711     nOld>=3 ? apOld[2]->pgno : 0
55712   ));
55713
55714   /*
55715   ** Allocate k new pages.  Reuse old pages where possible.
55716   */
55717   if( apOld[0]->pgno<=1 ){
55718     rc = SQLCIPHER_CORRUPT_BKPT;
55719     goto balance_cleanup;
55720   }
55721   pageFlags = apOld[0]->aData[0];
55722   for(i=0; i<k; i++){
55723     MemPage *pNew;
55724     if( i<nOld ){
55725       pNew = apNew[i] = apOld[i];
55726       apOld[i] = 0;
55727       rc = sqlcipher3PagerWrite(pNew->pDbPage);
55728       nNew++;
55729       if( rc ) goto balance_cleanup;
55730     }else{
55731       assert( i>0 );
55732       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
55733       if( rc ) goto balance_cleanup;
55734       apNew[i] = pNew;
55735       nNew++;
55736
55737       /* Set the pointer-map entry for the new sibling page. */
55738       if( ISAUTOVACUUM ){
55739         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
55740         if( rc!=SQLCIPHER_OK ){
55741           goto balance_cleanup;
55742         }
55743       }
55744     }
55745   }
55746
55747   /* Free any old pages that were not reused as new pages.
55748   */
55749   while( i<nOld ){
55750     freePage(apOld[i], &rc);
55751     if( rc ) goto balance_cleanup;
55752     releasePage(apOld[i]);
55753     apOld[i] = 0;
55754     i++;
55755   }
55756
55757   /*
55758   ** Put the new pages in accending order.  This helps to
55759   ** keep entries in the disk file in order so that a scan
55760   ** of the table is a linear scan through the file.  That
55761   ** in turn helps the operating system to deliver pages
55762   ** from the disk more rapidly.
55763   **
55764   ** An O(n^2) insertion sort algorithm is used, but since
55765   ** n is never more than NB (a small constant), that should
55766   ** not be a problem.
55767   **
55768   ** When NB==3, this one optimization makes the database
55769   ** about 25% faster for large insertions and deletions.
55770   */
55771   for(i=0; i<k-1; i++){
55772     int minV = apNew[i]->pgno;
55773     int minI = i;
55774     for(j=i+1; j<k; j++){
55775       if( apNew[j]->pgno<(unsigned)minV ){
55776         minI = j;
55777         minV = apNew[j]->pgno;
55778       }
55779     }
55780     if( minI>i ){
55781       MemPage *pT;
55782       pT = apNew[i];
55783       apNew[i] = apNew[minI];
55784       apNew[minI] = pT;
55785     }
55786   }
55787   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
55788     apNew[0]->pgno, szNew[0],
55789     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
55790     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
55791     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
55792     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
55793
55794   assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55795   put4byte(pRight, apNew[nNew-1]->pgno);
55796
55797   /*
55798   ** Evenly distribute the data in apCell[] across the new pages.
55799   ** Insert divider cells into pParent as necessary.
55800   */
55801   j = 0;
55802   for(i=0; i<nNew; i++){
55803     /* Assemble the new sibling page. */
55804     MemPage *pNew = apNew[i];
55805     assert( j<nMaxCells );
55806     zeroPage(pNew, pageFlags);
55807     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
55808     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
55809     assert( pNew->nOverflow==0 );
55810
55811     j = cntNew[i];
55812
55813     /* If the sibling page assembled above was not the right-most sibling,
55814     ** insert a divider cell into the parent page.
55815     */
55816     assert( i<nNew-1 || j==nCell );
55817     if( j<nCell ){
55818       u8 *pCell;
55819       u8 *pTemp;
55820       int sz;
55821
55822       assert( j<nMaxCells );
55823       pCell = apCell[j];
55824       sz = szCell[j] + leafCorrection;
55825       pTemp = &aOvflSpace[iOvflSpace];
55826       if( !pNew->leaf ){
55827         memcpy(&pNew->aData[8], pCell, 4);
55828       }else if( leafData ){
55829         /* If the tree is a leaf-data tree, and the siblings are leaves, 
55830         ** then there is no divider cell in apCell[]. Instead, the divider 
55831         ** cell consists of the integer key for the right-most cell of 
55832         ** the sibling-page assembled above only.
55833         */
55834         CellInfo info;
55835         j--;
55836         btreeParseCellPtr(pNew, apCell[j], &info);
55837         pCell = pTemp;
55838         sz = 4 + putVarint(&pCell[4], info.nKey);
55839         pTemp = 0;
55840       }else{
55841         pCell -= 4;
55842         /* Obscure case for non-leaf-data trees: If the cell at pCell was
55843         ** previously stored on a leaf node, and its reported size was 4
55844         ** bytes, then it may actually be smaller than this 
55845         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
55846         ** any cell). But it is important to pass the correct size to 
55847         ** insertCell(), so reparse the cell now.
55848         **
55849         ** Note that this can never happen in an SQLite data file, as all
55850         ** cells are at least 4 bytes. It only happens in b-trees used
55851         ** to evaluate "IN (SELECT ...)" and similar clauses.
55852         */
55853         if( szCell[j]==4 ){
55854           assert(leafCorrection==4);
55855           sz = cellSizePtr(pParent, pCell);
55856         }
55857       }
55858       iOvflSpace += sz;
55859       assert( sz<=pBt->maxLocal+23 );
55860       assert( iOvflSpace <= (int)pBt->pageSize );
55861       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
55862       if( rc!=SQLCIPHER_OK ) goto balance_cleanup;
55863       assert( sqlcipher3PagerIswriteable(pParent->pDbPage) );
55864
55865       j++;
55866       nxDiv++;
55867     }
55868   }
55869   assert( j==nCell );
55870   assert( nOld>0 );
55871   assert( nNew>0 );
55872   if( (pageFlags & PTF_LEAF)==0 ){
55873     u8 *zChild = &apCopy[nOld-1]->aData[8];
55874     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
55875   }
55876
55877   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
55878     /* The root page of the b-tree now contains no cells. The only sibling
55879     ** page is the right-child of the parent. Copy the contents of the
55880     ** child page into the parent, decreasing the overall height of the
55881     ** b-tree structure by one. This is described as the "balance-shallower"
55882     ** sub-algorithm in some documentation.
55883     **
55884     ** If this is an auto-vacuum database, the call to copyNodeContent() 
55885     ** sets all pointer-map entries corresponding to database image pages 
55886     ** for which the pointer is stored within the content being copied.
55887     **
55888     ** The second assert below verifies that the child page is defragmented
55889     ** (it must be, as it was just reconstructed using assemblePage()). This
55890     ** is important if the parent page happens to be page 1 of the database
55891     ** image.  */
55892     assert( nNew==1 );
55893     assert( apNew[0]->nFree == 
55894         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
55895     );
55896     copyNodeContent(apNew[0], pParent, &rc);
55897     freePage(apNew[0], &rc);
55898   }else if( ISAUTOVACUUM ){
55899     /* Fix the pointer-map entries for all the cells that were shifted around. 
55900     ** There are several different types of pointer-map entries that need to
55901     ** be dealt with by this routine. Some of these have been set already, but
55902     ** many have not. The following is a summary:
55903     **
55904     **   1) The entries associated with new sibling pages that were not
55905     **      siblings when this function was called. These have already
55906     **      been set. We don't need to worry about old siblings that were
55907     **      moved to the free-list - the freePage() code has taken care
55908     **      of those.
55909     **
55910     **   2) The pointer-map entries associated with the first overflow
55911     **      page in any overflow chains used by new divider cells. These 
55912     **      have also already been taken care of by the insertCell() code.
55913     **
55914     **   3) If the sibling pages are not leaves, then the child pages of
55915     **      cells stored on the sibling pages may need to be updated.
55916     **
55917     **   4) If the sibling pages are not internal intkey nodes, then any
55918     **      overflow pages used by these cells may need to be updated
55919     **      (internal intkey nodes never contain pointers to overflow pages).
55920     **
55921     **   5) If the sibling pages are not leaves, then the pointer-map
55922     **      entries for the right-child pages of each sibling may need
55923     **      to be updated.
55924     **
55925     ** Cases 1 and 2 are dealt with above by other code. The next
55926     ** block deals with cases 3 and 4 and the one after that, case 5. Since
55927     ** setting a pointer map entry is a relatively expensive operation, this
55928     ** code only sets pointer map entries for child or overflow pages that have
55929     ** actually moved between pages.  */
55930     MemPage *pNew = apNew[0];
55931     MemPage *pOld = apCopy[0];
55932     int nOverflow = pOld->nOverflow;
55933     int iNextOld = pOld->nCell + nOverflow;
55934     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
55935     j = 0;                             /* Current 'old' sibling page */
55936     k = 0;                             /* Current 'new' sibling page */
55937     for(i=0; i<nCell; i++){
55938       int isDivider = 0;
55939       while( i==iNextOld ){
55940         /* Cell i is the cell immediately following the last cell on old
55941         ** sibling page j. If the siblings are not leaf pages of an
55942         ** intkey b-tree, then cell i was a divider cell. */
55943         assert( j+1 < ArraySize(apCopy) );
55944         pOld = apCopy[++j];
55945         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
55946         if( pOld->nOverflow ){
55947           nOverflow = pOld->nOverflow;
55948           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
55949         }
55950         isDivider = !leafData;  
55951       }
55952
55953       assert(nOverflow>0 || iOverflow<i );
55954       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
55955       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
55956       if( i==iOverflow ){
55957         isDivider = 1;
55958         if( (--nOverflow)>0 ){
55959           iOverflow++;
55960         }
55961       }
55962
55963       if( i==cntNew[k] ){
55964         /* Cell i is the cell immediately following the last cell on new
55965         ** sibling page k. If the siblings are not leaf pages of an
55966         ** intkey b-tree, then cell i is a divider cell.  */
55967         pNew = apNew[++k];
55968         if( !leafData ) continue;
55969       }
55970       assert( j<nOld );
55971       assert( k<nNew );
55972
55973       /* If the cell was originally divider cell (and is not now) or
55974       ** an overflow cell, or if the cell was located on a different sibling
55975       ** page before the balancing, then the pointer map entries associated
55976       ** with any child or overflow pages need to be updated.  */
55977       if( isDivider || pOld->pgno!=pNew->pgno ){
55978         if( !leafCorrection ){
55979           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
55980         }
55981         if( szCell[i]>pNew->minLocal ){
55982           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
55983         }
55984       }
55985     }
55986
55987     if( !leafCorrection ){
55988       for(i=0; i<nNew; i++){
55989         u32 key = get4byte(&apNew[i]->aData[8]);
55990         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
55991       }
55992     }
55993
55994 #if 0
55995     /* The ptrmapCheckPages() contains assert() statements that verify that
55996     ** all pointer map pages are set correctly. This is helpful while 
55997     ** debugging. This is usually disabled because a corrupt database may
55998     ** cause an assert() statement to fail.  */
55999     ptrmapCheckPages(apNew, nNew);
56000     ptrmapCheckPages(&pParent, 1);
56001 #endif
56002   }
56003
56004   assert( pParent->isInit );
56005   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
56006           nOld, nNew, nCell));
56007
56008   /*
56009   ** Cleanup before returning.
56010   */
56011 balance_cleanup:
56012   sqlcipher3ScratchFree(apCell);
56013   for(i=0; i<nOld; i++){
56014     releasePage(apOld[i]);
56015   }
56016   for(i=0; i<nNew; i++){
56017     releasePage(apNew[i]);
56018   }
56019
56020   return rc;
56021 }
56022
56023
56024 /*
56025 ** This function is called when the root page of a b-tree structure is
56026 ** overfull (has one or more overflow pages).
56027 **
56028 ** A new child page is allocated and the contents of the current root
56029 ** page, including overflow cells, are copied into the child. The root
56030 ** page is then overwritten to make it an empty page with the right-child 
56031 ** pointer pointing to the new page.
56032 **
56033 ** Before returning, all pointer-map entries corresponding to pages 
56034 ** that the new child-page now contains pointers to are updated. The
56035 ** entry corresponding to the new right-child pointer of the root
56036 ** page is also updated.
56037 **
56038 ** If successful, *ppChild is set to contain a reference to the child 
56039 ** page and SQLCIPHER_OK is returned. In this case the caller is required
56040 ** to call releasePage() on *ppChild exactly once. If an error occurs,
56041 ** an error code is returned and *ppChild is set to 0.
56042 */
56043 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56044   int rc;                        /* Return value from subprocedures */
56045   MemPage *pChild = 0;           /* Pointer to a new child page */
56046   Pgno pgnoChild = 0;            /* Page number of the new child page */
56047   BtShared *pBt = pRoot->pBt;    /* The BTree */
56048
56049   assert( pRoot->nOverflow>0 );
56050   assert( sqlcipher3_mutex_held(pBt->mutex) );
56051
56052   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
56053   ** page that will become the new right-child of pPage. Copy the contents
56054   ** of the node stored on pRoot into the new child page.
56055   */
56056   rc = sqlcipher3PagerWrite(pRoot->pDbPage);
56057   if( rc==SQLCIPHER_OK ){
56058     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56059     copyNodeContent(pRoot, pChild, &rc);
56060     if( ISAUTOVACUUM ){
56061       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56062     }
56063   }
56064   if( rc ){
56065     *ppChild = 0;
56066     releasePage(pChild);
56067     return rc;
56068   }
56069   assert( sqlcipher3PagerIswriteable(pChild->pDbPage) );
56070   assert( sqlcipher3PagerIswriteable(pRoot->pDbPage) );
56071   assert( pChild->nCell==pRoot->nCell );
56072
56073   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56074
56075   /* Copy the overflow cells from pRoot to pChild */
56076   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
56077   pChild->nOverflow = pRoot->nOverflow;
56078
56079   /* Zero the contents of pRoot. Then install pChild as the right-child. */
56080   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56081   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56082
56083   *ppChild = pChild;
56084   return SQLCIPHER_OK;
56085 }
56086
56087 /*
56088 ** The page that pCur currently points to has just been modified in
56089 ** some way. This function figures out if this modification means the
56090 ** tree needs to be balanced, and if so calls the appropriate balancing 
56091 ** routine. Balancing routines are:
56092 **
56093 **   balance_quick()
56094 **   balance_deeper()
56095 **   balance_nonroot()
56096 */
56097 static int balance(BtCursor *pCur){
56098   int rc = SQLCIPHER_OK;
56099   const int nMin = pCur->pBt->usableSize * 2 / 3;
56100   u8 aBalanceQuickSpace[13];
56101   u8 *pFree = 0;
56102
56103   TESTONLY( int balance_quick_called = 0 );
56104   TESTONLY( int balance_deeper_called = 0 );
56105
56106   do {
56107     int iPage = pCur->iPage;
56108     MemPage *pPage = pCur->apPage[iPage];
56109
56110     if( iPage==0 ){
56111       if( pPage->nOverflow ){
56112         /* The root page of the b-tree is overfull. In this case call the
56113         ** balance_deeper() function to create a new child for the root-page
56114         ** and copy the current contents of the root-page to it. The
56115         ** next iteration of the do-loop will balance the child page.
56116         */ 
56117         assert( (balance_deeper_called++)==0 );
56118         rc = balance_deeper(pPage, &pCur->apPage[1]);
56119         if( rc==SQLCIPHER_OK ){
56120           pCur->iPage = 1;
56121           pCur->aiIdx[0] = 0;
56122           pCur->aiIdx[1] = 0;
56123           assert( pCur->apPage[1]->nOverflow );
56124         }
56125       }else{
56126         break;
56127       }
56128     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56129       break;
56130     }else{
56131       MemPage * const pParent = pCur->apPage[iPage-1];
56132       int const iIdx = pCur->aiIdx[iPage-1];
56133
56134       rc = sqlcipher3PagerWrite(pParent->pDbPage);
56135       if( rc==SQLCIPHER_OK ){
56136 #ifndef SQLCIPHER_OMIT_QUICKBALANCE
56137         if( pPage->hasData
56138          && pPage->nOverflow==1
56139          && pPage->aOvfl[0].idx==pPage->nCell
56140          && pParent->pgno!=1
56141          && pParent->nCell==iIdx
56142         ){
56143           /* Call balance_quick() to create a new sibling of pPage on which
56144           ** to store the overflow cell. balance_quick() inserts a new cell
56145           ** into pParent, which may cause pParent overflow. If this
56146           ** happens, the next interation of the do-loop will balance pParent 
56147           ** use either balance_nonroot() or balance_deeper(). Until this
56148           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56149           ** buffer. 
56150           **
56151           ** The purpose of the following assert() is to check that only a
56152           ** single call to balance_quick() is made for each call to this
56153           ** function. If this were not verified, a subtle bug involving reuse
56154           ** of the aBalanceQuickSpace[] might sneak in.
56155           */
56156           assert( (balance_quick_called++)==0 );
56157           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56158         }else
56159 #endif
56160         {
56161           /* In this case, call balance_nonroot() to redistribute cells
56162           ** between pPage and up to 2 of its sibling pages. This involves
56163           ** modifying the contents of pParent, which may cause pParent to
56164           ** become overfull or underfull. The next iteration of the do-loop
56165           ** will balance the parent page to correct this.
56166           ** 
56167           ** If the parent page becomes overfull, the overflow cell or cells
56168           ** are stored in the pSpace buffer allocated immediately below. 
56169           ** A subsequent iteration of the do-loop will deal with this by
56170           ** calling balance_nonroot() (balance_deeper() may be called first,
56171           ** but it doesn't deal with overflow cells - just moves them to a
56172           ** different page). Once this subsequent call to balance_nonroot() 
56173           ** has completed, it is safe to release the pSpace buffer used by
56174           ** the previous call, as the overflow cell data will have been 
56175           ** copied either into the body of a database page or into the new
56176           ** pSpace buffer passed to the latter call to balance_nonroot().
56177           */
56178           u8 *pSpace = sqlcipher3PageMalloc(pCur->pBt->pageSize);
56179           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
56180           if( pFree ){
56181             /* If pFree is not NULL, it points to the pSpace buffer used 
56182             ** by a previous call to balance_nonroot(). Its contents are
56183             ** now stored either on real database pages or within the 
56184             ** new pSpace buffer, so it may be safely freed here. */
56185             sqlcipher3PageFree(pFree);
56186           }
56187
56188           /* The pSpace buffer will be freed after the next call to
56189           ** balance_nonroot(), or just before this function returns, whichever
56190           ** comes first. */
56191           pFree = pSpace;
56192         }
56193       }
56194
56195       pPage->nOverflow = 0;
56196
56197       /* The next iteration of the do-loop balances the parent page. */
56198       releasePage(pPage);
56199       pCur->iPage--;
56200     }
56201   }while( rc==SQLCIPHER_OK );
56202
56203   if( pFree ){
56204     sqlcipher3PageFree(pFree);
56205   }
56206   return rc;
56207 }
56208
56209
56210 /*
56211 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56212 ** and the data is given by (pData,nData).  The cursor is used only to
56213 ** define what table the record should be inserted into.  The cursor
56214 ** is left pointing at a random location.
56215 **
56216 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
56217 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56218 **
56219 ** If the seekResult parameter is non-zero, then a successful call to
56220 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56221 ** been performed. seekResult is the search result returned (a negative
56222 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
56223 ** a positive value if pCur points at an etry that is larger than 
56224 ** (pKey, nKey)). 
56225 **
56226 ** If the seekResult parameter is non-zero, then the caller guarantees that
56227 ** cursor pCur is pointing at the existing copy of a row that is to be
56228 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56229 ** point to any entry or to no entry at all and so this function has to seek
56230 ** the cursor before the new key can be inserted.
56231 */
56232 SQLCIPHER_PRIVATE int sqlcipher3BtreeInsert(
56233   BtCursor *pCur,                /* Insert data into the table of this cursor */
56234   const void *pKey, i64 nKey,    /* The key of the new record */
56235   const void *pData, int nData,  /* The data of the new record */
56236   int nZero,                     /* Number of extra 0 bytes to append to data */
56237   int appendBias,                /* True if this is likely an append */
56238   int seekResult                 /* Result of prior MovetoUnpacked() call */
56239 ){
56240   int rc;
56241   int loc = seekResult;          /* -1: before desired location  +1: after */
56242   int szNew = 0;
56243   int idx;
56244   MemPage *pPage;
56245   Btree *p = pCur->pBtree;
56246   BtShared *pBt = p->pBt;
56247   unsigned char *oldCell;
56248   unsigned char *newCell = 0;
56249
56250   if( pCur->eState==CURSOR_FAULT ){
56251     assert( pCur->skipNext!=SQLCIPHER_OK );
56252     return pCur->skipNext;
56253   }
56254
56255   assert( cursorHoldsMutex(pCur) );
56256   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
56257   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56258
56259   /* Assert that the caller has been consistent. If this cursor was opened
56260   ** expecting an index b-tree, then the caller should be inserting blob
56261   ** keys with no associated data. If the cursor was opened expecting an
56262   ** intkey table, the caller should be inserting integer keys with a
56263   ** blob of associated data.  */
56264   assert( (pKey==0)==(pCur->pKeyInfo==0) );
56265
56266   /* If this is an insert into a table b-tree, invalidate any incrblob 
56267   ** cursors open on the row being replaced (assuming this is a replace
56268   ** operation - if it is not, the following is a no-op).  */
56269   if( pCur->pKeyInfo==0 ){
56270     invalidateIncrblobCursors(p, nKey, 0);
56271   }
56272
56273   /* Save the positions of any other cursors open on this table.
56274   **
56275   ** In some cases, the call to btreeMoveto() below is a no-op. For
56276   ** example, when inserting data into a table with auto-generated integer
56277   ** keys, the VDBE layer invokes sqlcipher3BtreeLast() to figure out the 
56278   ** integer key to use. It then calls this function to actually insert the 
56279   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56280   ** that the cursor is already where it needs to be and returns without
56281   ** doing any work. To avoid thwarting these optimizations, it is important
56282   ** not to clear the cursor here.
56283   */
56284   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56285   if( rc ) return rc;
56286   if( !loc ){
56287     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56288     if( rc ) return rc;
56289   }
56290   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56291
56292   pPage = pCur->apPage[pCur->iPage];
56293   assert( pPage->intKey || nKey>=0 );
56294   assert( pPage->leaf || !pPage->intKey );
56295
56296   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56297           pCur->pgnoRoot, nKey, nData, pPage->pgno,
56298           loc==0 ? "overwrite" : "new entry"));
56299   assert( pPage->isInit );
56300   allocateTempSpace(pBt);
56301   newCell = pBt->pTmpSpace;
56302   if( newCell==0 ) return SQLCIPHER_NOMEM;
56303   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56304   if( rc ) goto end_insert;
56305   assert( szNew==cellSizePtr(pPage, newCell) );
56306   assert( szNew <= MX_CELL_SIZE(pBt) );
56307   idx = pCur->aiIdx[pCur->iPage];
56308   if( loc==0 ){
56309     u16 szOld;
56310     assert( idx<pPage->nCell );
56311     rc = sqlcipher3PagerWrite(pPage->pDbPage);
56312     if( rc ){
56313       goto end_insert;
56314     }
56315     oldCell = findCell(pPage, idx);
56316     if( !pPage->leaf ){
56317       memcpy(newCell, oldCell, 4);
56318     }
56319     szOld = cellSizePtr(pPage, oldCell);
56320     rc = clearCell(pPage, oldCell);
56321     dropCell(pPage, idx, szOld, &rc);
56322     if( rc ) goto end_insert;
56323   }else if( loc<0 && pPage->nCell>0 ){
56324     assert( pPage->leaf );
56325     idx = ++pCur->aiIdx[pCur->iPage];
56326   }else{
56327     assert( pPage->leaf );
56328   }
56329   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56330   assert( rc!=SQLCIPHER_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56331
56332   /* If no error has occured and pPage has an overflow cell, call balance() 
56333   ** to redistribute the cells within the tree. Since balance() may move
56334   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56335   ** variables.
56336   **
56337   ** Previous versions of SQLite called moveToRoot() to move the cursor
56338   ** back to the root page as balance() used to invalidate the contents
56339   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56340   ** set the cursor state to "invalid". This makes common insert operations
56341   ** slightly faster.
56342   **
56343   ** There is a subtle but important optimization here too. When inserting
56344   ** multiple records into an intkey b-tree using a single cursor (as can
56345   ** happen while processing an "INSERT INTO ... SELECT" statement), it
56346   ** is advantageous to leave the cursor pointing to the last entry in
56347   ** the b-tree if possible. If the cursor is left pointing to the last
56348   ** entry in the table, and the next row inserted has an integer key
56349   ** larger than the largest existing key, it is possible to insert the
56350   ** row without seeking the cursor. This can be a big performance boost.
56351   */
56352   pCur->info.nSize = 0;
56353   pCur->validNKey = 0;
56354   if( rc==SQLCIPHER_OK && pPage->nOverflow ){
56355     rc = balance(pCur);
56356
56357     /* Must make sure nOverflow is reset to zero even if the balance()
56358     ** fails. Internal data structure corruption will result otherwise. 
56359     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56360     ** from trying to save the current position of the cursor.  */
56361     pCur->apPage[pCur->iPage]->nOverflow = 0;
56362     pCur->eState = CURSOR_INVALID;
56363   }
56364   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56365
56366 end_insert:
56367   return rc;
56368 }
56369
56370 /*
56371 ** Delete the entry that the cursor is pointing to.  The cursor
56372 ** is left pointing at a arbitrary location.
56373 */
56374 SQLCIPHER_PRIVATE int sqlcipher3BtreeDelete(BtCursor *pCur){
56375   Btree *p = pCur->pBtree;
56376   BtShared *pBt = p->pBt;              
56377   int rc;                              /* Return code */
56378   MemPage *pPage;                      /* Page to delete cell from */
56379   unsigned char *pCell;                /* Pointer to cell to delete */
56380   int iCellIdx;                        /* Index of cell to delete */
56381   int iCellDepth;                      /* Depth of node containing pCell */ 
56382
56383   assert( cursorHoldsMutex(pCur) );
56384   assert( pBt->inTransaction==TRANS_WRITE );
56385   assert( !pBt->readOnly );
56386   assert( pCur->wrFlag );
56387   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56388   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56389
56390   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
56391    || NEVER(pCur->eState!=CURSOR_VALID)
56392   ){
56393     return SQLCIPHER_ERROR;  /* Something has gone awry. */
56394   }
56395
56396   /* If this is a delete operation to remove a row from a table b-tree,
56397   ** invalidate any incrblob cursors open on the row being deleted.  */
56398   if( pCur->pKeyInfo==0 ){
56399     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56400   }
56401
56402   iCellDepth = pCur->iPage;
56403   iCellIdx = pCur->aiIdx[iCellDepth];
56404   pPage = pCur->apPage[iCellDepth];
56405   pCell = findCell(pPage, iCellIdx);
56406
56407   /* If the page containing the entry to delete is not a leaf page, move
56408   ** the cursor to the largest entry in the tree that is smaller than
56409   ** the entry being deleted. This cell will replace the cell being deleted
56410   ** from the internal node. The 'previous' entry is used for this instead
56411   ** of the 'next' entry, as the previous entry is always a part of the
56412   ** sub-tree headed by the child page of the cell being deleted. This makes
56413   ** balancing the tree following the delete operation easier.  */
56414   if( !pPage->leaf ){
56415     int notUsed;
56416     rc = sqlcipher3BtreePrevious(pCur, &notUsed);
56417     if( rc ) return rc;
56418   }
56419
56420   /* Save the positions of any other cursors open on this table before
56421   ** making any modifications. Make the page containing the entry to be 
56422   ** deleted writable. Then free any overflow pages associated with the 
56423   ** entry and finally remove the cell itself from within the page.  
56424   */
56425   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56426   if( rc ) return rc;
56427   rc = sqlcipher3PagerWrite(pPage->pDbPage);
56428   if( rc ) return rc;
56429   rc = clearCell(pPage, pCell);
56430   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56431   if( rc ) return rc;
56432
56433   /* If the cell deleted was not located on a leaf page, then the cursor
56434   ** is currently pointing to the largest entry in the sub-tree headed
56435   ** by the child-page of the cell that was just deleted from an internal
56436   ** node. The cell from the leaf node needs to be moved to the internal
56437   ** node to replace the deleted cell.  */
56438   if( !pPage->leaf ){
56439     MemPage *pLeaf = pCur->apPage[pCur->iPage];
56440     int nCell;
56441     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56442     unsigned char *pTmp;
56443
56444     pCell = findCell(pLeaf, pLeaf->nCell-1);
56445     nCell = cellSizePtr(pLeaf, pCell);
56446     assert( MX_CELL_SIZE(pBt) >= nCell );
56447
56448     allocateTempSpace(pBt);
56449     pTmp = pBt->pTmpSpace;
56450
56451     rc = sqlcipher3PagerWrite(pLeaf->pDbPage);
56452     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56453     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56454     if( rc ) return rc;
56455   }
56456
56457   /* Balance the tree. If the entry deleted was located on a leaf page,
56458   ** then the cursor still points to that page. In this case the first
56459   ** call to balance() repairs the tree, and the if(...) condition is
56460   ** never true.
56461   **
56462   ** Otherwise, if the entry deleted was on an internal node page, then
56463   ** pCur is pointing to the leaf page from which a cell was removed to
56464   ** replace the cell deleted from the internal node. This is slightly
56465   ** tricky as the leaf node may be underfull, and the internal node may
56466   ** be either under or overfull. In this case run the balancing algorithm
56467   ** on the leaf node first. If the balance proceeds far enough up the
56468   ** tree that we can be sure that any problem in the internal node has
56469   ** been corrected, so be it. Otherwise, after balancing the leaf node,
56470   ** walk the cursor up the tree to the internal node and balance it as 
56471   ** well.  */
56472   rc = balance(pCur);
56473   if( rc==SQLCIPHER_OK && pCur->iPage>iCellDepth ){
56474     while( pCur->iPage>iCellDepth ){
56475       releasePage(pCur->apPage[pCur->iPage--]);
56476     }
56477     rc = balance(pCur);
56478   }
56479
56480   if( rc==SQLCIPHER_OK ){
56481     moveToRoot(pCur);
56482   }
56483   return rc;
56484 }
56485
56486 /*
56487 ** Create a new BTree table.  Write into *piTable the page
56488 ** number for the root page of the new table.
56489 **
56490 ** The type of type is determined by the flags parameter.  Only the
56491 ** following values of flags are currently in use.  Other values for
56492 ** flags might not work:
56493 **
56494 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
56495 **     BTREE_ZERODATA                  Used for SQL indices
56496 */
56497 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56498   BtShared *pBt = p->pBt;
56499   MemPage *pRoot;
56500   Pgno pgnoRoot;
56501   int rc;
56502   int ptfFlags;          /* Page-type flage for the root page of new table */
56503
56504   assert( sqlcipher3BtreeHoldsMutex(p) );
56505   assert( pBt->inTransaction==TRANS_WRITE );
56506   assert( !pBt->readOnly );
56507
56508 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
56509   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56510   if( rc ){
56511     return rc;
56512   }
56513 #else
56514   if( pBt->autoVacuum ){
56515     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
56516     MemPage *pPageMove; /* The page to move to. */
56517
56518     /* Creating a new table may probably require moving an existing database
56519     ** to make room for the new tables root page. In case this page turns
56520     ** out to be an overflow page, delete all overflow page-map caches
56521     ** held by open cursors.
56522     */
56523     invalidateAllOverflowCache(pBt);
56524
56525     /* Read the value of meta[3] from the database to determine where the
56526     ** root page of the new table should go. meta[3] is the largest root-page
56527     ** created so far, so the new root-page is (meta[3]+1).
56528     */
56529     sqlcipher3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56530     pgnoRoot++;
56531
56532     /* The new root-page may not be allocated on a pointer-map page, or the
56533     ** PENDING_BYTE page.
56534     */
56535     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56536         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56537       pgnoRoot++;
56538     }
56539     assert( pgnoRoot>=3 );
56540
56541     /* Allocate a page. The page that currently resides at pgnoRoot will
56542     ** be moved to the allocated page (unless the allocated page happens
56543     ** to reside at pgnoRoot).
56544     */
56545     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
56546     if( rc!=SQLCIPHER_OK ){
56547       return rc;
56548     }
56549
56550     if( pgnoMove!=pgnoRoot ){
56551       /* pgnoRoot is the page that will be used for the root-page of
56552       ** the new table (assuming an error did not occur). But we were
56553       ** allocated pgnoMove. If required (i.e. if it was not allocated
56554       ** by extending the file), the current page at position pgnoMove
56555       ** is already journaled.
56556       */
56557       u8 eType = 0;
56558       Pgno iPtrPage = 0;
56559
56560       releasePage(pPageMove);
56561
56562       /* Move the page currently at pgnoRoot to pgnoMove. */
56563       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56564       if( rc!=SQLCIPHER_OK ){
56565         return rc;
56566       }
56567       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56568       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56569         rc = SQLCIPHER_CORRUPT_BKPT;
56570       }
56571       if( rc!=SQLCIPHER_OK ){
56572         releasePage(pRoot);
56573         return rc;
56574       }
56575       assert( eType!=PTRMAP_ROOTPAGE );
56576       assert( eType!=PTRMAP_FREEPAGE );
56577       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56578       releasePage(pRoot);
56579
56580       /* Obtain the page at pgnoRoot */
56581       if( rc!=SQLCIPHER_OK ){
56582         return rc;
56583       }
56584       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56585       if( rc!=SQLCIPHER_OK ){
56586         return rc;
56587       }
56588       rc = sqlcipher3PagerWrite(pRoot->pDbPage);
56589       if( rc!=SQLCIPHER_OK ){
56590         releasePage(pRoot);
56591         return rc;
56592       }
56593     }else{
56594       pRoot = pPageMove;
56595     } 
56596
56597     /* Update the pointer-map and meta-data with the new root-page number. */
56598     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56599     if( rc ){
56600       releasePage(pRoot);
56601       return rc;
56602     }
56603
56604     /* When the new root page was allocated, page 1 was made writable in
56605     ** order either to increase the database filesize, or to decrement the
56606     ** freelist count.  Hence, the sqlcipher3BtreeUpdateMeta() call cannot fail.
56607     */
56608     assert( sqlcipher3PagerIswriteable(pBt->pPage1->pDbPage) );
56609     rc = sqlcipher3BtreeUpdateMeta(p, 4, pgnoRoot);
56610     if( NEVER(rc) ){
56611       releasePage(pRoot);
56612       return rc;
56613     }
56614
56615   }else{
56616     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56617     if( rc ) return rc;
56618   }
56619 #endif
56620   assert( sqlcipher3PagerIswriteable(pRoot->pDbPage) );
56621   if( createTabFlags & BTREE_INTKEY ){
56622     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56623   }else{
56624     ptfFlags = PTF_ZERODATA | PTF_LEAF;
56625   }
56626   zeroPage(pRoot, ptfFlags);
56627   sqlcipher3PagerUnref(pRoot->pDbPage);
56628   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56629   *piTable = (int)pgnoRoot;
56630   return SQLCIPHER_OK;
56631 }
56632 SQLCIPHER_PRIVATE int sqlcipher3BtreeCreateTable(Btree *p, int *piTable, int flags){
56633   int rc;
56634   sqlcipher3BtreeEnter(p);
56635   rc = btreeCreateTable(p, piTable, flags);
56636   sqlcipher3BtreeLeave(p);
56637   return rc;
56638 }
56639
56640 /*
56641 ** Erase the given database page and all its children.  Return
56642 ** the page to the freelist.
56643 */
56644 static int clearDatabasePage(
56645   BtShared *pBt,           /* The BTree that contains the table */
56646   Pgno pgno,               /* Page number to clear */
56647   int freePageFlag,        /* Deallocate page if true */
56648   int *pnChange            /* Add number of Cells freed to this counter */
56649 ){
56650   MemPage *pPage;
56651   int rc;
56652   unsigned char *pCell;
56653   int i;
56654
56655   assert( sqlcipher3_mutex_held(pBt->mutex) );
56656   if( pgno>btreePagecount(pBt) ){
56657     return SQLCIPHER_CORRUPT_BKPT;
56658   }
56659
56660   rc = getAndInitPage(pBt, pgno, &pPage);
56661   if( rc ) return rc;
56662   for(i=0; i<pPage->nCell; i++){
56663     pCell = findCell(pPage, i);
56664     if( !pPage->leaf ){
56665       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56666       if( rc ) goto cleardatabasepage_out;
56667     }
56668     rc = clearCell(pPage, pCell);
56669     if( rc ) goto cleardatabasepage_out;
56670   }
56671   if( !pPage->leaf ){
56672     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56673     if( rc ) goto cleardatabasepage_out;
56674   }else if( pnChange ){
56675     assert( pPage->intKey );
56676     *pnChange += pPage->nCell;
56677   }
56678   if( freePageFlag ){
56679     freePage(pPage, &rc);
56680   }else if( (rc = sqlcipher3PagerWrite(pPage->pDbPage))==0 ){
56681     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56682   }
56683
56684 cleardatabasepage_out:
56685   releasePage(pPage);
56686   return rc;
56687 }
56688
56689 /*
56690 ** Delete all information from a single table in the database.  iTable is
56691 ** the page number of the root of the table.  After this routine returns,
56692 ** the root page is empty, but still exists.
56693 **
56694 ** This routine will fail with SQLCIPHER_LOCKED if there are any open
56695 ** read cursors on the table.  Open write cursors are moved to the
56696 ** root of the table.
56697 **
56698 ** If pnChange is not NULL, then table iTable must be an intkey table. The
56699 ** integer value pointed to by pnChange is incremented by the number of
56700 ** entries in the table.
56701 */
56702 SQLCIPHER_PRIVATE int sqlcipher3BtreeClearTable(Btree *p, int iTable, int *pnChange){
56703   int rc;
56704   BtShared *pBt = p->pBt;
56705   sqlcipher3BtreeEnter(p);
56706   assert( p->inTrans==TRANS_WRITE );
56707
56708   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
56709   ** is the root of a table b-tree - if it is not, the following call is
56710   ** a no-op).  */
56711   invalidateIncrblobCursors(p, 0, 1);
56712
56713   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
56714   if( SQLCIPHER_OK==rc ){
56715     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
56716   }
56717   sqlcipher3BtreeLeave(p);
56718   return rc;
56719 }
56720
56721 /*
56722 ** Erase all information in a table and add the root of the table to
56723 ** the freelist.  Except, the root of the principle table (the one on
56724 ** page 1) is never added to the freelist.
56725 **
56726 ** This routine will fail with SQLCIPHER_LOCKED if there are any open
56727 ** cursors on the table.
56728 **
56729 ** If AUTOVACUUM is enabled and the page at iTable is not the last
56730 ** root page in the database file, then the last root page 
56731 ** in the database file is moved into the slot formerly occupied by
56732 ** iTable and that last slot formerly occupied by the last root page
56733 ** is added to the freelist instead of iTable.  In this say, all
56734 ** root pages are kept at the beginning of the database file, which
56735 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
56736 ** page number that used to be the last root page in the file before
56737 ** the move.  If no page gets moved, *piMoved is set to 0.
56738 ** The last root page is recorded in meta[3] and the value of
56739 ** meta[3] is updated by this procedure.
56740 */
56741 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
56742   int rc;
56743   MemPage *pPage = 0;
56744   BtShared *pBt = p->pBt;
56745
56746   assert( sqlcipher3BtreeHoldsMutex(p) );
56747   assert( p->inTrans==TRANS_WRITE );
56748
56749   /* It is illegal to drop a table if any cursors are open on the
56750   ** database. This is because in auto-vacuum mode the backend may
56751   ** need to move another root-page to fill a gap left by the deleted
56752   ** root page. If an open cursor was using this page a problem would 
56753   ** occur.
56754   **
56755   ** This error is caught long before control reaches this point.
56756   */
56757   if( NEVER(pBt->pCursor) ){
56758     sqlcipher3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
56759     return SQLCIPHER_LOCKED_SHAREDCACHE;
56760   }
56761
56762   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
56763   if( rc ) return rc;
56764   rc = sqlcipher3BtreeClearTable(p, iTable, 0);
56765   if( rc ){
56766     releasePage(pPage);
56767     return rc;
56768   }
56769
56770   *piMoved = 0;
56771
56772   if( iTable>1 ){
56773 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
56774     freePage(pPage, &rc);
56775     releasePage(pPage);
56776 #else
56777     if( pBt->autoVacuum ){
56778       Pgno maxRootPgno;
56779       sqlcipher3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
56780
56781       if( iTable==maxRootPgno ){
56782         /* If the table being dropped is the table with the largest root-page
56783         ** number in the database, put the root page on the free list. 
56784         */
56785         freePage(pPage, &rc);
56786         releasePage(pPage);
56787         if( rc!=SQLCIPHER_OK ){
56788           return rc;
56789         }
56790       }else{
56791         /* The table being dropped does not have the largest root-page
56792         ** number in the database. So move the page that does into the 
56793         ** gap left by the deleted root-page.
56794         */
56795         MemPage *pMove;
56796         releasePage(pPage);
56797         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56798         if( rc!=SQLCIPHER_OK ){
56799           return rc;
56800         }
56801         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
56802         releasePage(pMove);
56803         if( rc!=SQLCIPHER_OK ){
56804           return rc;
56805         }
56806         pMove = 0;
56807         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56808         freePage(pMove, &rc);
56809         releasePage(pMove);
56810         if( rc!=SQLCIPHER_OK ){
56811           return rc;
56812         }
56813         *piMoved = maxRootPgno;
56814       }
56815
56816       /* Set the new 'max-root-page' value in the database header. This
56817       ** is the old value less one, less one more if that happens to
56818       ** be a root-page number, less one again if that is the
56819       ** PENDING_BYTE_PAGE.
56820       */
56821       maxRootPgno--;
56822       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
56823              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
56824         maxRootPgno--;
56825       }
56826       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
56827
56828       rc = sqlcipher3BtreeUpdateMeta(p, 4, maxRootPgno);
56829     }else{
56830       freePage(pPage, &rc);
56831       releasePage(pPage);
56832     }
56833 #endif
56834   }else{
56835     /* If sqlcipher3BtreeDropTable was called on page 1.
56836     ** This really never should happen except in a corrupt
56837     ** database. 
56838     */
56839     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
56840     releasePage(pPage);
56841   }
56842   return rc;  
56843 }
56844 SQLCIPHER_PRIVATE int sqlcipher3BtreeDropTable(Btree *p, int iTable, int *piMoved){
56845   int rc;
56846   sqlcipher3BtreeEnter(p);
56847   rc = btreeDropTable(p, iTable, piMoved);
56848   sqlcipher3BtreeLeave(p);
56849   return rc;
56850 }
56851
56852
56853 /*
56854 ** This function may only be called if the b-tree connection already
56855 ** has a read or write transaction open on the database.
56856 **
56857 ** Read the meta-information out of a database file.  Meta[0]
56858 ** is the number of free pages currently in the database.  Meta[1]
56859 ** through meta[15] are available for use by higher layers.  Meta[0]
56860 ** is read-only, the others are read/write.
56861 ** 
56862 ** The schema layer numbers meta values differently.  At the schema
56863 ** layer (and the SetCookie and ReadCookie opcodes) the number of
56864 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
56865 */
56866 SQLCIPHER_PRIVATE void sqlcipher3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
56867   BtShared *pBt = p->pBt;
56868
56869   sqlcipher3BtreeEnter(p);
56870   assert( p->inTrans>TRANS_NONE );
56871   assert( SQLCIPHER_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
56872   assert( pBt->pPage1 );
56873   assert( idx>=0 && idx<=15 );
56874
56875   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
56876
56877   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
56878   ** database, mark the database as read-only.  */
56879 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
56880   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
56881 #endif
56882
56883   sqlcipher3BtreeLeave(p);
56884 }
56885
56886 /*
56887 ** Write meta-information back into the database.  Meta[0] is
56888 ** read-only and may not be written.
56889 */
56890 SQLCIPHER_PRIVATE int sqlcipher3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
56891   BtShared *pBt = p->pBt;
56892   unsigned char *pP1;
56893   int rc;
56894   assert( idx>=1 && idx<=15 );
56895   sqlcipher3BtreeEnter(p);
56896   assert( p->inTrans==TRANS_WRITE );
56897   assert( pBt->pPage1!=0 );
56898   pP1 = pBt->pPage1->aData;
56899   rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
56900   if( rc==SQLCIPHER_OK ){
56901     put4byte(&pP1[36 + idx*4], iMeta);
56902 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
56903     if( idx==BTREE_INCR_VACUUM ){
56904       assert( pBt->autoVacuum || iMeta==0 );
56905       assert( iMeta==0 || iMeta==1 );
56906       pBt->incrVacuum = (u8)iMeta;
56907     }
56908 #endif
56909   }
56910   sqlcipher3BtreeLeave(p);
56911   return rc;
56912 }
56913
56914 #ifndef SQLCIPHER_OMIT_BTREECOUNT
56915 /*
56916 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
56917 ** number of entries in the b-tree and write the result to *pnEntry.
56918 **
56919 ** SQLCIPHER_OK is returned if the operation is successfully executed. 
56920 ** Otherwise, if an error is encountered (i.e. an IO error or database
56921 ** corruption) an SQLite error code is returned.
56922 */
56923 SQLCIPHER_PRIVATE int sqlcipher3BtreeCount(BtCursor *pCur, i64 *pnEntry){
56924   i64 nEntry = 0;                      /* Value to return in *pnEntry */
56925   int rc;                              /* Return code */
56926
56927   if( pCur->pgnoRoot==0 ){
56928     *pnEntry = 0;
56929     return SQLCIPHER_OK;
56930   }
56931   rc = moveToRoot(pCur);
56932
56933   /* Unless an error occurs, the following loop runs one iteration for each
56934   ** page in the B-Tree structure (not including overflow pages). 
56935   */
56936   while( rc==SQLCIPHER_OK ){
56937     int iIdx;                          /* Index of child node in parent */
56938     MemPage *pPage;                    /* Current page of the b-tree */
56939
56940     /* If this is a leaf page or the tree is not an int-key tree, then 
56941     ** this page contains countable entries. Increment the entry counter
56942     ** accordingly.
56943     */
56944     pPage = pCur->apPage[pCur->iPage];
56945     if( pPage->leaf || !pPage->intKey ){
56946       nEntry += pPage->nCell;
56947     }
56948
56949     /* pPage is a leaf node. This loop navigates the cursor so that it 
56950     ** points to the first interior cell that it points to the parent of
56951     ** the next page in the tree that has not yet been visited. The
56952     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
56953     ** of the page, or to the number of cells in the page if the next page
56954     ** to visit is the right-child of its parent.
56955     **
56956     ** If all pages in the tree have been visited, return SQLCIPHER_OK to the
56957     ** caller.
56958     */
56959     if( pPage->leaf ){
56960       do {
56961         if( pCur->iPage==0 ){
56962           /* All pages of the b-tree have been visited. Return successfully. */
56963           *pnEntry = nEntry;
56964           return SQLCIPHER_OK;
56965         }
56966         moveToParent(pCur);
56967       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
56968
56969       pCur->aiIdx[pCur->iPage]++;
56970       pPage = pCur->apPage[pCur->iPage];
56971     }
56972
56973     /* Descend to the child node of the cell that the cursor currently 
56974     ** points at. This is the right-child if (iIdx==pPage->nCell).
56975     */
56976     iIdx = pCur->aiIdx[pCur->iPage];
56977     if( iIdx==pPage->nCell ){
56978       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56979     }else{
56980       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
56981     }
56982   }
56983
56984   /* An error has occurred. Return an error code. */
56985   return rc;
56986 }
56987 #endif
56988
56989 /*
56990 ** Return the pager associated with a BTree.  This routine is used for
56991 ** testing and debugging only.
56992 */
56993 SQLCIPHER_PRIVATE Pager *sqlcipher3BtreePager(Btree *p){
56994   return p->pBt->pPager;
56995 }
56996
56997 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
56998 /*
56999 ** Append a message to the error message string.
57000 */
57001 static void checkAppendMsg(
57002   IntegrityCk *pCheck,
57003   char *zMsg1,
57004   const char *zFormat,
57005   ...
57006 ){
57007   va_list ap;
57008   if( !pCheck->mxErr ) return;
57009   pCheck->mxErr--;
57010   pCheck->nErr++;
57011   va_start(ap, zFormat);
57012   if( pCheck->errMsg.nChar ){
57013     sqlcipher3StrAccumAppend(&pCheck->errMsg, "\n", 1);
57014   }
57015   if( zMsg1 ){
57016     sqlcipher3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
57017   }
57018   sqlcipher3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
57019   va_end(ap);
57020   if( pCheck->errMsg.mallocFailed ){
57021     pCheck->mallocFailed = 1;
57022   }
57023 }
57024 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57025
57026 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
57027 /*
57028 ** Add 1 to the reference count for page iPage.  If this is the second
57029 ** reference to the page, add an error message to pCheck->zErrMsg.
57030 ** Return 1 if there are 2 ore more references to the page and 0 if
57031 ** if this is the first reference to the page.
57032 **
57033 ** Also check that the page number is in bounds.
57034 */
57035 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57036   if( iPage==0 ) return 1;
57037   if( iPage>pCheck->nPage ){
57038     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57039     return 1;
57040   }
57041   if( pCheck->anRef[iPage]==1 ){
57042     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57043     return 1;
57044   }
57045   return  (pCheck->anRef[iPage]++)>1;
57046 }
57047
57048 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57049 /*
57050 ** Check that the entry in the pointer-map for page iChild maps to 
57051 ** page iParent, pointer type ptrType. If not, append an error message
57052 ** to pCheck.
57053 */
57054 static void checkPtrmap(
57055   IntegrityCk *pCheck,   /* Integrity check context */
57056   Pgno iChild,           /* Child page number */
57057   u8 eType,              /* Expected pointer map type */
57058   Pgno iParent,          /* Expected pointer map parent page number */
57059   char *zContext         /* Context description (used for error msg) */
57060 ){
57061   int rc;
57062   u8 ePtrmapType = 0;
57063   Pgno iPtrmapParent = 0;
57064
57065   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57066   if( rc!=SQLCIPHER_OK ){
57067     if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57068     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57069     return;
57070   }
57071
57072   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57073     checkAppendMsg(pCheck, zContext, 
57074       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
57075       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57076   }
57077 }
57078 #endif
57079
57080 /*
57081 ** Check the integrity of the freelist or of an overflow page list.
57082 ** Verify that the number of pages on the list is N.
57083 */
57084 static void checkList(
57085   IntegrityCk *pCheck,  /* Integrity checking context */
57086   int isFreeList,       /* True for a freelist.  False for overflow page list */
57087   int iPage,            /* Page number for first page in the list */
57088   int N,                /* Expected number of pages in the list */
57089   char *zContext        /* Context for error messages */
57090 ){
57091   int i;
57092   int expected = N;
57093   int iFirst = iPage;
57094   while( N-- > 0 && pCheck->mxErr ){
57095     DbPage *pOvflPage;
57096     unsigned char *pOvflData;
57097     if( iPage<1 ){
57098       checkAppendMsg(pCheck, zContext,
57099          "%d of %d pages missing from overflow list starting at %d",
57100           N+1, expected, iFirst);
57101       break;
57102     }
57103     if( checkRef(pCheck, iPage, zContext) ) break;
57104     if( sqlcipher3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57105       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57106       break;
57107     }
57108     pOvflData = (unsigned char *)sqlcipher3PagerGetData(pOvflPage);
57109     if( isFreeList ){
57110       int n = get4byte(&pOvflData[4]);
57111 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57112       if( pCheck->pBt->autoVacuum ){
57113         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57114       }
57115 #endif
57116       if( n>(int)pCheck->pBt->usableSize/4-2 ){
57117         checkAppendMsg(pCheck, zContext,
57118            "freelist leaf count too big on page %d", iPage);
57119         N--;
57120       }else{
57121         for(i=0; i<n; i++){
57122           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57123 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57124           if( pCheck->pBt->autoVacuum ){
57125             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57126           }
57127 #endif
57128           checkRef(pCheck, iFreePage, zContext);
57129         }
57130         N -= n;
57131       }
57132     }
57133 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57134     else{
57135       /* If this database supports auto-vacuum and iPage is not the last
57136       ** page in this overflow list, check that the pointer-map entry for
57137       ** the following page matches iPage.
57138       */
57139       if( pCheck->pBt->autoVacuum && N>0 ){
57140         i = get4byte(pOvflData);
57141         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57142       }
57143     }
57144 #endif
57145     iPage = get4byte(pOvflData);
57146     sqlcipher3PagerUnref(pOvflPage);
57147   }
57148 }
57149 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57150
57151 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
57152 /*
57153 ** Do various sanity checks on a single page of a tree.  Return
57154 ** the tree depth.  Root pages return 0.  Parents of root pages
57155 ** return 1, and so forth.
57156 ** 
57157 ** These checks are done:
57158 **
57159 **      1.  Make sure that cells and freeblocks do not overlap
57160 **          but combine to completely cover the page.
57161 **  NO  2.  Make sure cell keys are in order.
57162 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
57163 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57164 **      5.  Check the integrity of overflow pages.
57165 **      6.  Recursively call checkTreePage on all children.
57166 **      7.  Verify that the depth of all children is the same.
57167 **      8.  Make sure this page is at least 33% full or else it is
57168 **          the root of the tree.
57169 */
57170 static int checkTreePage(
57171   IntegrityCk *pCheck,  /* Context for the sanity check */
57172   int iPage,            /* Page number of the page to check */
57173   char *zParentContext, /* Parent context */
57174   i64 *pnParentMinKey, 
57175   i64 *pnParentMaxKey
57176 ){
57177   MemPage *pPage;
57178   int i, rc, depth, d2, pgno, cnt;
57179   int hdr, cellStart;
57180   int nCell;
57181   u8 *data;
57182   BtShared *pBt;
57183   int usableSize;
57184   char zContext[100];
57185   char *hit = 0;
57186   i64 nMinKey = 0;
57187   i64 nMaxKey = 0;
57188
57189   sqlcipher3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57190
57191   /* Check that the page exists
57192   */
57193   pBt = pCheck->pBt;
57194   usableSize = pBt->usableSize;
57195   if( iPage==0 ) return 0;
57196   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57197   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57198     checkAppendMsg(pCheck, zContext,
57199        "unable to get the page. error code=%d", rc);
57200     return 0;
57201   }
57202
57203   /* Clear MemPage.isInit to make sure the corruption detection code in
57204   ** btreeInitPage() is executed.  */
57205   pPage->isInit = 0;
57206   if( (rc = btreeInitPage(pPage))!=0 ){
57207     assert( rc==SQLCIPHER_CORRUPT );  /* The only possible error from InitPage */
57208     checkAppendMsg(pCheck, zContext, 
57209                    "btreeInitPage() returns error code %d", rc);
57210     releasePage(pPage);
57211     return 0;
57212   }
57213
57214   /* Check out all the cells.
57215   */
57216   depth = 0;
57217   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57218     u8 *pCell;
57219     u32 sz;
57220     CellInfo info;
57221
57222     /* Check payload overflow pages
57223     */
57224     sqlcipher3_snprintf(sizeof(zContext), zContext,
57225              "On tree page %d cell %d: ", iPage, i);
57226     pCell = findCell(pPage,i);
57227     btreeParseCellPtr(pPage, pCell, &info);
57228     sz = info.nData;
57229     if( !pPage->intKey ) sz += (int)info.nKey;
57230     /* For intKey pages, check that the keys are in order.
57231     */
57232     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57233     else{
57234       if( info.nKey <= nMaxKey ){
57235         checkAppendMsg(pCheck, zContext, 
57236             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57237       }
57238       nMaxKey = info.nKey;
57239     }
57240     assert( sz==info.nPayload );
57241     if( (sz>info.nLocal) 
57242      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57243     ){
57244       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57245       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57246 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57247       if( pBt->autoVacuum ){
57248         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57249       }
57250 #endif
57251       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57252     }
57253
57254     /* Check sanity of left child page.
57255     */
57256     if( !pPage->leaf ){
57257       pgno = get4byte(pCell);
57258 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57259       if( pBt->autoVacuum ){
57260         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57261       }
57262 #endif
57263       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57264       if( i>0 && d2!=depth ){
57265         checkAppendMsg(pCheck, zContext, "Child page depth differs");
57266       }
57267       depth = d2;
57268     }
57269   }
57270
57271   if( !pPage->leaf ){
57272     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57273     sqlcipher3_snprintf(sizeof(zContext), zContext, 
57274                      "On page %d at right child: ", iPage);
57275 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57276     if( pBt->autoVacuum ){
57277       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57278     }
57279 #endif
57280     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57281   }
57282  
57283   /* For intKey leaf pages, check that the min/max keys are in order
57284   ** with any left/parent/right pages.
57285   */
57286   if( pPage->leaf && pPage->intKey ){
57287     /* if we are a left child page */
57288     if( pnParentMinKey ){
57289       /* if we are the left most child page */
57290       if( !pnParentMaxKey ){
57291         if( nMaxKey > *pnParentMinKey ){
57292           checkAppendMsg(pCheck, zContext, 
57293               "Rowid %lld out of order (max larger than parent min of %lld)",
57294               nMaxKey, *pnParentMinKey);
57295         }
57296       }else{
57297         if( nMinKey <= *pnParentMinKey ){
57298           checkAppendMsg(pCheck, zContext, 
57299               "Rowid %lld out of order (min less than parent min of %lld)",
57300               nMinKey, *pnParentMinKey);
57301         }
57302         if( nMaxKey > *pnParentMaxKey ){
57303           checkAppendMsg(pCheck, zContext, 
57304               "Rowid %lld out of order (max larger than parent max of %lld)",
57305               nMaxKey, *pnParentMaxKey);
57306         }
57307         *pnParentMinKey = nMaxKey;
57308       }
57309     /* else if we're a right child page */
57310     } else if( pnParentMaxKey ){
57311       if( nMinKey <= *pnParentMaxKey ){
57312         checkAppendMsg(pCheck, zContext, 
57313             "Rowid %lld out of order (min less than parent max of %lld)",
57314             nMinKey, *pnParentMaxKey);
57315       }
57316     }
57317   }
57318
57319   /* Check for complete coverage of the page
57320   */
57321   data = pPage->aData;
57322   hdr = pPage->hdrOffset;
57323   hit = sqlcipher3PageMalloc( pBt->pageSize );
57324   if( hit==0 ){
57325     pCheck->mallocFailed = 1;
57326   }else{
57327     int contentOffset = get2byteNotZero(&data[hdr+5]);
57328     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57329     memset(hit+contentOffset, 0, usableSize-contentOffset);
57330     memset(hit, 1, contentOffset);
57331     nCell = get2byte(&data[hdr+3]);
57332     cellStart = hdr + 12 - 4*pPage->leaf;
57333     for(i=0; i<nCell; i++){
57334       int pc = get2byte(&data[cellStart+i*2]);
57335       u32 size = 65536;
57336       int j;
57337       if( pc<=usableSize-4 ){
57338         size = cellSizePtr(pPage, &data[pc]);
57339       }
57340       if( (int)(pc+size-1)>=usableSize ){
57341         checkAppendMsg(pCheck, 0, 
57342             "Corruption detected in cell %d on page %d",i,iPage);
57343       }else{
57344         for(j=pc+size-1; j>=pc; j--) hit[j]++;
57345       }
57346     }
57347     i = get2byte(&data[hdr+1]);
57348     while( i>0 ){
57349       int size, j;
57350       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57351       size = get2byte(&data[i+2]);
57352       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57353       for(j=i+size-1; j>=i; j--) hit[j]++;
57354       j = get2byte(&data[i]);
57355       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57356       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57357       i = j;
57358     }
57359     for(i=cnt=0; i<usableSize; i++){
57360       if( hit[i]==0 ){
57361         cnt++;
57362       }else if( hit[i]>1 ){
57363         checkAppendMsg(pCheck, 0,
57364           "Multiple uses for byte %d of page %d", i, iPage);
57365         break;
57366       }
57367     }
57368     if( cnt!=data[hdr+7] ){
57369       checkAppendMsg(pCheck, 0, 
57370           "Fragmentation of %d bytes reported as %d on page %d",
57371           cnt, data[hdr+7], iPage);
57372     }
57373   }
57374   sqlcipher3PageFree(hit);
57375   releasePage(pPage);
57376   return depth+1;
57377 }
57378 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57379
57380 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
57381 /*
57382 ** This routine does a complete check of the given BTree file.  aRoot[] is
57383 ** an array of pages numbers were each page number is the root page of
57384 ** a table.  nRoot is the number of entries in aRoot.
57385 **
57386 ** A read-only or read-write transaction must be opened before calling
57387 ** this function.
57388 **
57389 ** Write the number of error seen in *pnErr.  Except for some memory
57390 ** allocation errors,  an error message held in memory obtained from
57391 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57392 ** returned.  If a memory allocation error occurs, NULL is returned.
57393 */
57394 SQLCIPHER_PRIVATE char *sqlcipher3BtreeIntegrityCheck(
57395   Btree *p,     /* The btree to be checked */
57396   int *aRoot,   /* An array of root pages numbers for individual trees */
57397   int nRoot,    /* Number of entries in aRoot[] */
57398   int mxErr,    /* Stop reporting errors after this many */
57399   int *pnErr    /* Write number of errors seen to this variable */
57400 ){
57401   Pgno i;
57402   int nRef;
57403   IntegrityCk sCheck;
57404   BtShared *pBt = p->pBt;
57405   char zErr[100];
57406
57407   sqlcipher3BtreeEnter(p);
57408   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57409   nRef = sqlcipher3PagerRefcount(pBt->pPager);
57410   sCheck.pBt = pBt;
57411   sCheck.pPager = pBt->pPager;
57412   sCheck.nPage = btreePagecount(sCheck.pBt);
57413   sCheck.mxErr = mxErr;
57414   sCheck.nErr = 0;
57415   sCheck.mallocFailed = 0;
57416   *pnErr = 0;
57417   if( sCheck.nPage==0 ){
57418     sqlcipher3BtreeLeave(p);
57419     return 0;
57420   }
57421   sCheck.anRef = sqlcipher3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
57422   if( !sCheck.anRef ){
57423     *pnErr = 1;
57424     sqlcipher3BtreeLeave(p);
57425     return 0;
57426   }
57427   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
57428   i = PENDING_BYTE_PAGE(pBt);
57429   if( i<=sCheck.nPage ){
57430     sCheck.anRef[i] = 1;
57431   }
57432   sqlcipher3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
57433   sCheck.errMsg.useMalloc = 2;
57434
57435   /* Check the integrity of the freelist
57436   */
57437   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57438             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57439
57440   /* Check all the tables.
57441   */
57442   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57443     if( aRoot[i]==0 ) continue;
57444 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
57445     if( pBt->autoVacuum && aRoot[i]>1 ){
57446       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57447     }
57448 #endif
57449     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57450   }
57451
57452   /* Make sure every page in the file is referenced
57453   */
57454   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57455 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
57456     if( sCheck.anRef[i]==0 ){
57457       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57458     }
57459 #else
57460     /* If the database supports auto-vacuum, make sure no tables contain
57461     ** references to pointer-map pages.
57462     */
57463     if( sCheck.anRef[i]==0 && 
57464        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57465       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57466     }
57467     if( sCheck.anRef[i]!=0 && 
57468        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57469       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57470     }
57471 #endif
57472   }
57473
57474   /* Make sure this analysis did not leave any unref() pages.
57475   ** This is an internal consistency check; an integrity check
57476   ** of the integrity check.
57477   */
57478   if( NEVER(nRef != sqlcipher3PagerRefcount(pBt->pPager)) ){
57479     checkAppendMsg(&sCheck, 0, 
57480       "Outstanding page count goes from %d to %d during this analysis",
57481       nRef, sqlcipher3PagerRefcount(pBt->pPager)
57482     );
57483   }
57484
57485   /* Clean  up and report errors.
57486   */
57487   sqlcipher3BtreeLeave(p);
57488   sqlcipher3_free(sCheck.anRef);
57489   if( sCheck.mallocFailed ){
57490     sqlcipher3StrAccumReset(&sCheck.errMsg);
57491     *pnErr = sCheck.nErr+1;
57492     return 0;
57493   }
57494   *pnErr = sCheck.nErr;
57495   if( sCheck.nErr==0 ) sqlcipher3StrAccumReset(&sCheck.errMsg);
57496   return sqlcipher3StrAccumFinish(&sCheck.errMsg);
57497 }
57498 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
57499
57500 /*
57501 ** Return the full pathname of the underlying database file.
57502 **
57503 ** The pager filename is invariant as long as the pager is
57504 ** open so it is safe to access without the BtShared mutex.
57505 */
57506 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetFilename(Btree *p){
57507   assert( p->pBt->pPager!=0 );
57508   return sqlcipher3PagerFilename(p->pBt->pPager);
57509 }
57510
57511 /*
57512 ** Return the pathname of the journal file for this database. The return
57513 ** value of this routine is the same regardless of whether the journal file
57514 ** has been created or not.
57515 **
57516 ** The pager journal filename is invariant as long as the pager is
57517 ** open so it is safe to access without the BtShared mutex.
57518 */
57519 SQLCIPHER_PRIVATE const char *sqlcipher3BtreeGetJournalname(Btree *p){
57520   assert( p->pBt->pPager!=0 );
57521   return sqlcipher3PagerJournalname(p->pBt->pPager);
57522 }
57523
57524 /*
57525 ** Return non-zero if a transaction is active.
57526 */
57527 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInTrans(Btree *p){
57528   assert( p==0 || sqlcipher3_mutex_held(p->db->mutex) );
57529   return (p && (p->inTrans==TRANS_WRITE));
57530 }
57531
57532 #ifndef SQLCIPHER_OMIT_WAL
57533 /*
57534 ** Run a checkpoint on the Btree passed as the first argument.
57535 **
57536 ** Return SQLCIPHER_LOCKED if this or any other connection has an open 
57537 ** transaction on the shared-cache the argument Btree is connected to.
57538 **
57539 ** Parameter eMode is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL or RESTART.
57540 */
57541 SQLCIPHER_PRIVATE int sqlcipher3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57542   int rc = SQLCIPHER_OK;
57543   if( p ){
57544     BtShared *pBt = p->pBt;
57545     sqlcipher3BtreeEnter(p);
57546     if( pBt->inTransaction!=TRANS_NONE ){
57547       rc = SQLCIPHER_LOCKED;
57548     }else{
57549       rc = sqlcipher3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57550     }
57551     sqlcipher3BtreeLeave(p);
57552   }
57553   return rc;
57554 }
57555 #endif
57556
57557 /*
57558 ** Return non-zero if a read (or write) transaction is active.
57559 */
57560 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInReadTrans(Btree *p){
57561   assert( p );
57562   assert( sqlcipher3_mutex_held(p->db->mutex) );
57563   return p->inTrans!=TRANS_NONE;
57564 }
57565
57566 SQLCIPHER_PRIVATE int sqlcipher3BtreeIsInBackup(Btree *p){
57567   assert( p );
57568   assert( sqlcipher3_mutex_held(p->db->mutex) );
57569   return p->nBackup!=0;
57570 }
57571
57572 /*
57573 ** This function returns a pointer to a blob of memory associated with
57574 ** a single shared-btree. The memory is used by client code for its own
57575 ** purposes (for example, to store a high-level schema associated with 
57576 ** the shared-btree). The btree layer manages reference counting issues.
57577 **
57578 ** The first time this is called on a shared-btree, nBytes bytes of memory
57579 ** are allocated, zeroed, and returned to the caller. For each subsequent 
57580 ** call the nBytes parameter is ignored and a pointer to the same blob
57581 ** of memory returned. 
57582 **
57583 ** If the nBytes parameter is 0 and the blob of memory has not yet been
57584 ** allocated, a null pointer is returned. If the blob has already been
57585 ** allocated, it is returned as normal.
57586 **
57587 ** Just before the shared-btree is closed, the function passed as the 
57588 ** xFree argument when the memory allocation was made is invoked on the 
57589 ** blob of allocated memory. The xFree function should not call sqlcipher3_free()
57590 ** on the memory, the btree layer does that.
57591 */
57592 SQLCIPHER_PRIVATE void *sqlcipher3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57593   BtShared *pBt = p->pBt;
57594   sqlcipher3BtreeEnter(p);
57595   if( !pBt->pSchema && nBytes ){
57596     pBt->pSchema = sqlcipher3DbMallocZero(0, nBytes);
57597     pBt->xFreeSchema = xFree;
57598   }
57599   sqlcipher3BtreeLeave(p);
57600   return pBt->pSchema;
57601 }
57602
57603 /*
57604 ** Return SQLCIPHER_LOCKED_SHAREDCACHE if another user of the same shared 
57605 ** btree as the argument handle holds an exclusive lock on the 
57606 ** sqlcipher_master table. Otherwise SQLCIPHER_OK.
57607 */
57608 SQLCIPHER_PRIVATE int sqlcipher3BtreeSchemaLocked(Btree *p){
57609   int rc;
57610   assert( sqlcipher3_mutex_held(p->db->mutex) );
57611   sqlcipher3BtreeEnter(p);
57612   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57613   assert( rc==SQLCIPHER_OK || rc==SQLCIPHER_LOCKED_SHAREDCACHE );
57614   sqlcipher3BtreeLeave(p);
57615   return rc;
57616 }
57617
57618
57619 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
57620 /*
57621 ** Obtain a lock on the table whose root page is iTab.  The
57622 ** lock is a write lock if isWritelock is true or a read lock
57623 ** if it is false.
57624 */
57625 SQLCIPHER_PRIVATE int sqlcipher3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57626   int rc = SQLCIPHER_OK;
57627   assert( p->inTrans!=TRANS_NONE );
57628   if( p->sharable ){
57629     u8 lockType = READ_LOCK + isWriteLock;
57630     assert( READ_LOCK+1==WRITE_LOCK );
57631     assert( isWriteLock==0 || isWriteLock==1 );
57632
57633     sqlcipher3BtreeEnter(p);
57634     rc = querySharedCacheTableLock(p, iTab, lockType);
57635     if( rc==SQLCIPHER_OK ){
57636       rc = setSharedCacheTableLock(p, iTab, lockType);
57637     }
57638     sqlcipher3BtreeLeave(p);
57639   }
57640   return rc;
57641 }
57642 #endif
57643
57644 #ifndef SQLCIPHER_OMIT_INCRBLOB
57645 /*
57646 ** Argument pCsr must be a cursor opened for writing on an 
57647 ** INTKEY table currently pointing at a valid table entry. 
57648 ** This function modifies the data stored as part of that entry.
57649 **
57650 ** Only the data content may only be modified, it is not possible to 
57651 ** change the length of the data stored. If this function is called with
57652 ** parameters that attempt to write past the end of the existing data,
57653 ** no modifications are made and SQLCIPHER_CORRUPT is returned.
57654 */
57655 SQLCIPHER_PRIVATE int sqlcipher3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57656   int rc;
57657   assert( cursorHoldsMutex(pCsr) );
57658   assert( sqlcipher3_mutex_held(pCsr->pBtree->db->mutex) );
57659   assert( pCsr->isIncrblobHandle );
57660
57661   rc = restoreCursorPosition(pCsr);
57662   if( rc!=SQLCIPHER_OK ){
57663     return rc;
57664   }
57665   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57666   if( pCsr->eState!=CURSOR_VALID ){
57667     return SQLCIPHER_ABORT;
57668   }
57669
57670   /* Check some assumptions: 
57671   **   (a) the cursor is open for writing,
57672   **   (b) there is a read/write transaction open,
57673   **   (c) the connection holds a write-lock on the table (if required),
57674   **   (d) there are no conflicting read-locks, and
57675   **   (e) the cursor points at a valid row of an intKey table.
57676   */
57677   if( !pCsr->wrFlag ){
57678     return SQLCIPHER_READONLY;
57679   }
57680   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
57681   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
57682   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
57683   assert( pCsr->apPage[pCsr->iPage]->intKey );
57684
57685   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
57686 }
57687
57688 /* 
57689 ** Set a flag on this cursor to cache the locations of pages from the 
57690 ** overflow list for the current row. This is used by cursors opened
57691 ** for incremental blob IO only.
57692 **
57693 ** This function sets a flag only. The actual page location cache
57694 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
57695 ** accessPayload() (the worker function for sqlcipher3BtreeData() and
57696 ** sqlcipher3BtreePutData()).
57697 */
57698 SQLCIPHER_PRIVATE void sqlcipher3BtreeCacheOverflow(BtCursor *pCur){
57699   assert( cursorHoldsMutex(pCur) );
57700   assert( sqlcipher3_mutex_held(pCur->pBtree->db->mutex) );
57701   invalidateOverflowCache(pCur);
57702   pCur->isIncrblobHandle = 1;
57703 }
57704 #endif
57705
57706 /*
57707 ** Set both the "read version" (single byte at byte offset 18) and 
57708 ** "write version" (single byte at byte offset 19) fields in the database
57709 ** header to iVersion.
57710 */
57711 SQLCIPHER_PRIVATE int sqlcipher3BtreeSetVersion(Btree *pBtree, int iVersion){
57712   BtShared *pBt = pBtree->pBt;
57713   int rc;                         /* Return code */
57714  
57715   assert( iVersion==1 || iVersion==2 );
57716
57717   /* If setting the version fields to 1, do not automatically open the
57718   ** WAL connection, even if the version fields are currently set to 2.
57719   */
57720   pBt->doNotUseWAL = (u8)(iVersion==1);
57721
57722   rc = sqlcipher3BtreeBeginTrans(pBtree, 0);
57723   if( rc==SQLCIPHER_OK ){
57724     u8 *aData = pBt->pPage1->aData;
57725     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
57726       rc = sqlcipher3BtreeBeginTrans(pBtree, 2);
57727       if( rc==SQLCIPHER_OK ){
57728         rc = sqlcipher3PagerWrite(pBt->pPage1->pDbPage);
57729         if( rc==SQLCIPHER_OK ){
57730           aData[18] = (u8)iVersion;
57731           aData[19] = (u8)iVersion;
57732         }
57733       }
57734     }
57735   }
57736
57737   pBt->doNotUseWAL = 0;
57738   return rc;
57739 }
57740
57741 /************** End of btree.c ***********************************************/
57742 /************** Begin file backup.c ******************************************/
57743 /*
57744 ** 2009 January 28
57745 **
57746 ** The author disclaims copyright to this source code.  In place of
57747 ** a legal notice, here is a blessing:
57748 **
57749 **    May you do good and not evil.
57750 **    May you find forgiveness for yourself and forgive others.
57751 **    May you share freely, never taking more than you give.
57752 **
57753 *************************************************************************
57754 ** This file contains the implementation of the sqlcipher3_backup_XXX() 
57755 ** API functions and the related features.
57756 */
57757
57758 /* Macro to find the minimum of two numeric values.
57759 */
57760 #ifndef MIN
57761 # define MIN(x,y) ((x)<(y)?(x):(y))
57762 #endif
57763
57764 /*
57765 ** Structure allocated for each backup operation.
57766 */
57767 struct sqlcipher3_backup {
57768   sqlcipher3* pDestDb;        /* Destination database handle */
57769   Btree *pDest;            /* Destination b-tree file */
57770   u32 iDestSchema;         /* Original schema cookie in destination */
57771   int bDestLocked;         /* True once a write-transaction is open on pDest */
57772
57773   Pgno iNext;              /* Page number of the next source page to copy */
57774   sqlcipher3* pSrcDb;         /* Source database handle */
57775   Btree *pSrc;             /* Source b-tree file */
57776
57777   int rc;                  /* Backup process error code */
57778
57779   /* These two variables are set by every call to backup_step(). They are
57780   ** read by calls to backup_remaining() and backup_pagecount().
57781   */
57782   Pgno nRemaining;         /* Number of pages left to copy */
57783   Pgno nPagecount;         /* Total number of pages to copy */
57784
57785   int isAttached;          /* True once backup has been registered with pager */
57786   sqlcipher3_backup *pNext;   /* Next backup associated with source pager */
57787 };
57788
57789 /*
57790 ** THREAD SAFETY NOTES:
57791 **
57792 **   Once it has been created using backup_init(), a single sqlcipher3_backup
57793 **   structure may be accessed via two groups of thread-safe entry points:
57794 **
57795 **     * Via the sqlcipher3_backup_XXX() API function backup_step() and 
57796 **       backup_finish(). Both these functions obtain the source database
57797 **       handle mutex and the mutex associated with the source BtShared 
57798 **       structure, in that order.
57799 **
57800 **     * Via the BackupUpdate() and BackupRestart() functions, which are
57801 **       invoked by the pager layer to report various state changes in
57802 **       the page cache associated with the source database. The mutex
57803 **       associated with the source database BtShared structure will always 
57804 **       be held when either of these functions are invoked.
57805 **
57806 **   The other sqlcipher3_backup_XXX() API functions, backup_remaining() and
57807 **   backup_pagecount() are not thread-safe functions. If they are called
57808 **   while some other thread is calling backup_step() or backup_finish(),
57809 **   the values returned may be invalid. There is no way for a call to
57810 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
57811 **   or backup_pagecount().
57812 **
57813 **   Depending on the SQLite configuration, the database handles and/or
57814 **   the Btree objects may have their own mutexes that require locking.
57815 **   Non-sharable Btrees (in-memory databases for example), do not have
57816 **   associated mutexes.
57817 */
57818
57819 /*
57820 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
57821 ** in connection handle pDb. If such a database cannot be found, return
57822 ** a NULL pointer and write an error message to pErrorDb.
57823 **
57824 ** If the "temp" database is requested, it may need to be opened by this 
57825 ** function. If an error occurs while doing so, return 0 and write an 
57826 ** error message to pErrorDb.
57827 */
57828 static Btree *findBtree(sqlcipher3 *pErrorDb, sqlcipher3 *pDb, const char *zDb){
57829   int i = sqlcipher3FindDbName(pDb, zDb);
57830
57831   if( i==1 ){
57832     Parse *pParse;
57833     int rc = 0;
57834     pParse = sqlcipher3StackAllocZero(pErrorDb, sizeof(*pParse));
57835     if( pParse==0 ){
57836       sqlcipher3Error(pErrorDb, SQLCIPHER_NOMEM, "out of memory");
57837       rc = SQLCIPHER_NOMEM;
57838     }else{
57839       pParse->db = pDb;
57840       if( sqlcipher3OpenTempDatabase(pParse) ){
57841         sqlcipher3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
57842         rc = SQLCIPHER_ERROR;
57843       }
57844       sqlcipher3DbFree(pErrorDb, pParse->zErrMsg);
57845       sqlcipher3StackFree(pErrorDb, pParse);
57846     }
57847     if( rc ){
57848       return 0;
57849     }
57850   }
57851
57852   if( i<0 ){
57853     sqlcipher3Error(pErrorDb, SQLCIPHER_ERROR, "unknown database %s", zDb);
57854     return 0;
57855   }
57856
57857   return pDb->aDb[i].pBt;
57858 }
57859
57860 /*
57861 ** Attempt to set the page size of the destination to match the page size
57862 ** of the source.
57863 */
57864 static int setDestPgsz(sqlcipher3_backup *p){
57865   int rc;
57866   rc = sqlcipher3BtreeSetPageSize(p->pDest,sqlcipher3BtreeGetPageSize(p->pSrc),-1,0);
57867   return rc;
57868 }
57869
57870 /*
57871 ** Create an sqlcipher3_backup process to copy the contents of zSrcDb from
57872 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
57873 ** a pointer to the new sqlcipher3_backup object.
57874 **
57875 ** If an error occurs, NULL is returned and an error code and error message
57876 ** stored in database handle pDestDb.
57877 */
57878 SQLCIPHER_API sqlcipher3_backup *sqlcipher3_backup_init(
57879   sqlcipher3* pDestDb,                     /* Database to write to */
57880   const char *zDestDb,                  /* Name of database within pDestDb */
57881   sqlcipher3* pSrcDb,                      /* Database connection to read from */
57882   const char *zSrcDb                    /* Name of database within pSrcDb */
57883 ){
57884   sqlcipher3_backup *p;                    /* Value to return */
57885
57886   /* Lock the source database handle. The destination database
57887   ** handle is not locked in this routine, but it is locked in
57888   ** sqlcipher3_backup_step(). The user is required to ensure that no
57889   ** other thread accesses the destination handle for the duration
57890   ** of the backup operation.  Any attempt to use the destination
57891   ** database connection while a backup is in progress may cause
57892   ** a malfunction or a deadlock.
57893   */
57894   sqlcipher3_mutex_enter(pSrcDb->mutex);
57895   sqlcipher3_mutex_enter(pDestDb->mutex);
57896
57897   if( pSrcDb==pDestDb ){
57898     sqlcipher3Error(
57899         pDestDb, SQLCIPHER_ERROR, "source and destination must be distinct"
57900     );
57901     p = 0;
57902   }else {
57903     /* Allocate space for a new sqlcipher3_backup object...
57904     ** EVIDENCE-OF: R-64852-21591 The sqlcipher3_backup object is created by a
57905     ** call to sqlcipher3_backup_init() and is destroyed by a call to
57906     ** sqlcipher3_backup_finish(). */
57907     p = (sqlcipher3_backup *)sqlcipher3_malloc(sizeof(sqlcipher3_backup));
57908     if( !p ){
57909       sqlcipher3Error(pDestDb, SQLCIPHER_NOMEM, 0);
57910     }
57911   }
57912
57913   /* If the allocation succeeded, populate the new object. */
57914   if( p ){
57915     memset(p, 0, sizeof(sqlcipher3_backup));
57916     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
57917     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
57918     p->pDestDb = pDestDb;
57919     p->pSrcDb = pSrcDb;
57920     p->iNext = 1;
57921     p->isAttached = 0;
57922
57923     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLCIPHER_NOMEM ){
57924       /* One (or both) of the named databases did not exist or an OOM
57925       ** error was hit.  The error has already been written into the
57926       ** pDestDb handle.  All that is left to do here is free the
57927       ** sqlcipher3_backup structure.
57928       */
57929       sqlcipher3_free(p);
57930       p = 0;
57931     }
57932   }
57933   if( p ){
57934     p->pSrc->nBackup++;
57935   }
57936
57937   sqlcipher3_mutex_leave(pDestDb->mutex);
57938   sqlcipher3_mutex_leave(pSrcDb->mutex);
57939   return p;
57940 }
57941
57942 /*
57943 ** Argument rc is an SQLite error code. Return true if this error is 
57944 ** considered fatal if encountered during a backup operation. All errors
57945 ** are considered fatal except for SQLCIPHER_BUSY and SQLCIPHER_LOCKED.
57946 */
57947 static int isFatalError(int rc){
57948   return (rc!=SQLCIPHER_OK && rc!=SQLCIPHER_BUSY && ALWAYS(rc!=SQLCIPHER_LOCKED));
57949 }
57950
57951 /*
57952 ** Parameter zSrcData points to a buffer containing the data for 
57953 ** page iSrcPg from the source database. Copy this data into the 
57954 ** destination database.
57955 */
57956 static int backupOnePage(sqlcipher3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
57957   Pager * const pDestPager = sqlcipher3BtreePager(p->pDest);
57958   const int nSrcPgsz = sqlcipher3BtreeGetPageSize(p->pSrc);
57959   int nDestPgsz = sqlcipher3BtreeGetPageSize(p->pDest);
57960   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
57961   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
57962 #ifdef SQLCIPHER_HAS_CODEC
57963   int nSrcReserve = sqlcipher3BtreeGetReserve(p->pSrc);
57964   int nDestReserve = sqlcipher3BtreeGetReserve(p->pDest);
57965 #endif
57966
57967   int rc = SQLCIPHER_OK;
57968   i64 iOff;
57969
57970   assert( p->bDestLocked );
57971   assert( !isFatalError(p->rc) );
57972   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
57973   assert( zSrcData );
57974
57975   /* Catch the case where the destination is an in-memory database and the
57976   ** page sizes of the source and destination differ. 
57977   */
57978   if( nSrcPgsz!=nDestPgsz && sqlcipher3PagerIsMemdb(pDestPager) ){
57979     rc = SQLCIPHER_READONLY;
57980   }
57981
57982 #ifdef SQLCIPHER_HAS_CODEC
57983   /* Backup is not possible if the page size of the destination is changing
57984   ** and a codec is in use.
57985   */
57986   if( nSrcPgsz!=nDestPgsz && sqlcipher3PagerGetCodec(pDestPager)!=0 ){
57987     rc = SQLCIPHER_READONLY;
57988   }
57989
57990   /* Backup is not possible if the number of bytes of reserve space differ
57991   ** between source and destination.  If there is a difference, try to
57992   ** fix the destination to agree with the source.  If that is not possible,
57993   ** then the backup cannot proceed.
57994   */
57995   if( nSrcReserve!=nDestReserve ){
57996     u32 newPgsz = nSrcPgsz;
57997     rc = sqlcipher3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
57998     if( rc==SQLCIPHER_OK && (int)newPgsz!=nSrcPgsz ) rc = SQLCIPHER_READONLY;
57999   }
58000 #endif
58001
58002   /* This loop runs once for each destination page spanned by the source 
58003   ** page. For each iteration, variable iOff is set to the byte offset
58004   ** of the destination page.
58005   */
58006   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLCIPHER_OK && iOff<iEnd; iOff+=nDestPgsz){
58007     DbPage *pDestPg = 0;
58008     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
58009     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
58010     if( SQLCIPHER_OK==(rc = sqlcipher3PagerGet(pDestPager, iDest, &pDestPg))
58011      && SQLCIPHER_OK==(rc = sqlcipher3PagerWrite(pDestPg))
58012     ){
58013       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
58014       u8 *zDestData = sqlcipher3PagerGetData(pDestPg);
58015       u8 *zOut = &zDestData[iOff%nDestPgsz];
58016
58017       /* Copy the data from the source page into the destination page.
58018       ** Then clear the Btree layer MemPage.isInit flag. Both this module
58019       ** and the pager code use this trick (clearing the first byte
58020       ** of the page 'extra' space to invalidate the Btree layers
58021       ** cached parse of the page). MemPage.isInit is marked 
58022       ** "MUST BE FIRST" for this purpose.
58023       */
58024       memcpy(zOut, zIn, nCopy);
58025       ((u8 *)sqlcipher3PagerGetExtra(pDestPg))[0] = 0;
58026     }
58027     sqlcipher3PagerUnref(pDestPg);
58028   }
58029
58030   return rc;
58031 }
58032
58033 /*
58034 ** If pFile is currently larger than iSize bytes, then truncate it to
58035 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58036 ** this function is a no-op.
58037 **
58038 ** Return SQLCIPHER_OK if everything is successful, or an SQLite error 
58039 ** code if an error occurs.
58040 */
58041 static int backupTruncateFile(sqlcipher3_file *pFile, i64 iSize){
58042   i64 iCurrent;
58043   int rc = sqlcipher3OsFileSize(pFile, &iCurrent);
58044   if( rc==SQLCIPHER_OK && iCurrent>iSize ){
58045     rc = sqlcipher3OsTruncate(pFile, iSize);
58046   }
58047   return rc;
58048 }
58049
58050 /*
58051 ** Register this backup object with the associated source pager for
58052 ** callbacks when pages are changed or the cache invalidated.
58053 */
58054 static void attachBackupObject(sqlcipher3_backup *p){
58055   sqlcipher3_backup **pp;
58056   assert( sqlcipher3BtreeHoldsMutex(p->pSrc) );
58057   pp = sqlcipher3PagerBackupPtr(sqlcipher3BtreePager(p->pSrc));
58058   p->pNext = *pp;
58059   *pp = p;
58060   p->isAttached = 1;
58061 }
58062
58063 /*
58064 ** Copy nPage pages from the source b-tree to the destination.
58065 */
58066 SQLCIPHER_API int sqlcipher3_backup_step(sqlcipher3_backup *p, int nPage){
58067   int rc;
58068   int destMode;       /* Destination journal mode */
58069   int pgszSrc = 0;    /* Source page size */
58070   int pgszDest = 0;   /* Destination page size */
58071
58072   sqlcipher3_mutex_enter(p->pSrcDb->mutex);
58073   sqlcipher3BtreeEnter(p->pSrc);
58074   if( p->pDestDb ){
58075     sqlcipher3_mutex_enter(p->pDestDb->mutex);
58076   }
58077
58078   rc = p->rc;
58079   if( !isFatalError(rc) ){
58080     Pager * const pSrcPager = sqlcipher3BtreePager(p->pSrc);     /* Source pager */
58081     Pager * const pDestPager = sqlcipher3BtreePager(p->pDest);   /* Dest pager */
58082     int ii;                            /* Iterator variable */
58083     int nSrcPage = -1;                 /* Size of source db in pages */
58084     int bCloseTrans = 0;               /* True if src db requires unlocking */
58085
58086     /* If the source pager is currently in a write-transaction, return
58087     ** SQLCIPHER_BUSY immediately.
58088     */
58089     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58090       rc = SQLCIPHER_BUSY;
58091     }else{
58092       rc = SQLCIPHER_OK;
58093     }
58094
58095     /* Lock the destination database, if it is not locked already. */
58096     if( SQLCIPHER_OK==rc && p->bDestLocked==0
58097      && SQLCIPHER_OK==(rc = sqlcipher3BtreeBeginTrans(p->pDest, 2)) 
58098     ){
58099       p->bDestLocked = 1;
58100       sqlcipher3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58101     }
58102
58103     /* If there is no open read-transaction on the source database, open
58104     ** one now. If a transaction is opened here, then it will be closed
58105     ** before this function exits.
58106     */
58107     if( rc==SQLCIPHER_OK && 0==sqlcipher3BtreeIsInReadTrans(p->pSrc) ){
58108       rc = sqlcipher3BtreeBeginTrans(p->pSrc, 0);
58109       bCloseTrans = 1;
58110     }
58111
58112     /* Do not allow backup if the destination database is in WAL mode
58113     ** and the page sizes are different between source and destination */
58114     pgszSrc = sqlcipher3BtreeGetPageSize(p->pSrc);
58115     pgszDest = sqlcipher3BtreeGetPageSize(p->pDest);
58116     destMode = sqlcipher3PagerGetJournalMode(sqlcipher3BtreePager(p->pDest));
58117     if( SQLCIPHER_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58118       rc = SQLCIPHER_READONLY;
58119     }
58120   
58121     /* Now that there is a read-lock on the source database, query the
58122     ** source pager for the number of pages in the database.
58123     */
58124     nSrcPage = (int)sqlcipher3BtreeLastPage(p->pSrc);
58125     assert( nSrcPage>=0 );
58126     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58127       const Pgno iSrcPg = p->iNext;                 /* Source page number */
58128       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58129         DbPage *pSrcPg;                             /* Source page object */
58130         rc = sqlcipher3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58131         if( rc==SQLCIPHER_OK ){
58132           rc = backupOnePage(p, iSrcPg, sqlcipher3PagerGetData(pSrcPg));
58133           sqlcipher3PagerUnref(pSrcPg);
58134         }
58135       }
58136       p->iNext++;
58137     }
58138     if( rc==SQLCIPHER_OK ){
58139       p->nPagecount = nSrcPage;
58140       p->nRemaining = nSrcPage+1-p->iNext;
58141       if( p->iNext>(Pgno)nSrcPage ){
58142         rc = SQLCIPHER_DONE;
58143       }else if( !p->isAttached ){
58144         attachBackupObject(p);
58145       }
58146     }
58147   
58148     /* Update the schema version field in the destination database. This
58149     ** is to make sure that the schema-version really does change in
58150     ** the case where the source and destination databases have the
58151     ** same schema version.
58152     */
58153     if( rc==SQLCIPHER_DONE ){
58154       rc = sqlcipher3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58155       if( rc==SQLCIPHER_OK ){
58156         if( p->pDestDb ){
58157           sqlcipher3ResetInternalSchema(p->pDestDb, -1);
58158         }
58159         if( destMode==PAGER_JOURNALMODE_WAL ){
58160           rc = sqlcipher3BtreeSetVersion(p->pDest, 2);
58161         }
58162       }
58163       if( rc==SQLCIPHER_OK ){
58164         int nDestTruncate;
58165         /* Set nDestTruncate to the final number of pages in the destination
58166         ** database. The complication here is that the destination page
58167         ** size may be different to the source page size. 
58168         **
58169         ** If the source page size is smaller than the destination page size, 
58170         ** round up. In this case the call to sqlcipher3OsTruncate() below will
58171         ** fix the size of the file. However it is important to call
58172         ** sqlcipher3PagerTruncateImage() here so that any pages in the 
58173         ** destination file that lie beyond the nDestTruncate page mark are
58174         ** journalled by PagerCommitPhaseOne() before they are destroyed
58175         ** by the file truncation.
58176         */
58177         assert( pgszSrc==sqlcipher3BtreeGetPageSize(p->pSrc) );
58178         assert( pgszDest==sqlcipher3BtreeGetPageSize(p->pDest) );
58179         if( pgszSrc<pgszDest ){
58180           int ratio = pgszDest/pgszSrc;
58181           nDestTruncate = (nSrcPage+ratio-1)/ratio;
58182           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58183             nDestTruncate--;
58184           }
58185         }else{
58186           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58187         }
58188         sqlcipher3PagerTruncateImage(pDestPager, nDestTruncate);
58189
58190         if( pgszSrc<pgszDest ){
58191           /* If the source page-size is smaller than the destination page-size,
58192           ** two extra things may need to happen:
58193           **
58194           **   * The destination may need to be truncated, and
58195           **
58196           **   * Data stored on the pages immediately following the 
58197           **     pending-byte page in the source database may need to be
58198           **     copied into the destination database.
58199           */
58200           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58201           sqlcipher3_file * const pFile = sqlcipher3PagerFile(pDestPager);
58202           i64 iOff;
58203           i64 iEnd;
58204
58205           assert( pFile );
58206           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58207                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58208              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58209           ));
58210
58211           /* This call ensures that all data required to recreate the original
58212           ** database has been stored in the journal for pDestPager and the
58213           ** journal synced to disk. So at this point we may safely modify
58214           ** the database file in any way, knowing that if a power failure
58215           ** occurs, the original database will be reconstructed from the 
58216           ** journal file.  */
58217           rc = sqlcipher3PagerCommitPhaseOne(pDestPager, 0, 1);
58218
58219           /* Write the extra pages and truncate the database file as required */
58220           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58221           for(
58222             iOff=PENDING_BYTE+pgszSrc; 
58223             rc==SQLCIPHER_OK && iOff<iEnd; 
58224             iOff+=pgszSrc
58225           ){
58226             PgHdr *pSrcPg = 0;
58227             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58228             rc = sqlcipher3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58229             if( rc==SQLCIPHER_OK ){
58230               u8 *zData = sqlcipher3PagerGetData(pSrcPg);
58231               rc = sqlcipher3OsWrite(pFile, zData, pgszSrc, iOff);
58232             }
58233             sqlcipher3PagerUnref(pSrcPg);
58234           }
58235           if( rc==SQLCIPHER_OK ){
58236             rc = backupTruncateFile(pFile, iSize);
58237           }
58238
58239           /* Sync the database file to disk. */
58240           if( rc==SQLCIPHER_OK ){
58241             rc = sqlcipher3PagerSync(pDestPager);
58242           }
58243         }else{
58244           rc = sqlcipher3PagerCommitPhaseOne(pDestPager, 0, 0);
58245         }
58246     
58247         /* Finish committing the transaction to the destination database. */
58248         if( SQLCIPHER_OK==rc
58249          && SQLCIPHER_OK==(rc = sqlcipher3BtreeCommitPhaseTwo(p->pDest, 0))
58250         ){
58251           rc = SQLCIPHER_DONE;
58252         }
58253       }
58254     }
58255   
58256     /* If bCloseTrans is true, then this function opened a read transaction
58257     ** on the source database. Close the read transaction here. There is
58258     ** no need to check the return values of the btree methods here, as
58259     ** "committing" a read-only transaction cannot fail.
58260     */
58261     if( bCloseTrans ){
58262       TESTONLY( int rc2 );
58263       TESTONLY( rc2  = ) sqlcipher3BtreeCommitPhaseOne(p->pSrc, 0);
58264       TESTONLY( rc2 |= ) sqlcipher3BtreeCommitPhaseTwo(p->pSrc, 0);
58265       assert( rc2==SQLCIPHER_OK );
58266     }
58267   
58268     if( rc==SQLCIPHER_IOERR_NOMEM ){
58269       rc = SQLCIPHER_NOMEM;
58270     }
58271     p->rc = rc;
58272   }
58273   if( p->pDestDb ){
58274     sqlcipher3_mutex_leave(p->pDestDb->mutex);
58275   }
58276   sqlcipher3BtreeLeave(p->pSrc);
58277   sqlcipher3_mutex_leave(p->pSrcDb->mutex);
58278   return rc;
58279 }
58280
58281 /*
58282 ** Release all resources associated with an sqlcipher3_backup* handle.
58283 */
58284 SQLCIPHER_API int sqlcipher3_backup_finish(sqlcipher3_backup *p){
58285   sqlcipher3_backup **pp;                 /* Ptr to head of pagers backup list */
58286   MUTEX_LOGIC( sqlcipher3_mutex *mutex; ) /* Mutex to protect source database */
58287   int rc;                              /* Value to return */
58288
58289   /* Enter the mutexes */
58290   if( p==0 ) return SQLCIPHER_OK;
58291   sqlcipher3_mutex_enter(p->pSrcDb->mutex);
58292   sqlcipher3BtreeEnter(p->pSrc);
58293   MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
58294   if( p->pDestDb ){
58295     sqlcipher3_mutex_enter(p->pDestDb->mutex);
58296   }
58297
58298   /* Detach this backup from the source pager. */
58299   if( p->pDestDb ){
58300     p->pSrc->nBackup--;
58301   }
58302   if( p->isAttached ){
58303     pp = sqlcipher3PagerBackupPtr(sqlcipher3BtreePager(p->pSrc));
58304     while( *pp!=p ){
58305       pp = &(*pp)->pNext;
58306     }
58307     *pp = p->pNext;
58308   }
58309
58310   /* If a transaction is still open on the Btree, roll it back. */
58311   sqlcipher3BtreeRollback(p->pDest);
58312
58313   /* Set the error code of the destination database handle. */
58314   rc = (p->rc==SQLCIPHER_DONE) ? SQLCIPHER_OK : p->rc;
58315   sqlcipher3Error(p->pDestDb, rc, 0);
58316
58317   /* Exit the mutexes and free the backup context structure. */
58318   if( p->pDestDb ){
58319     sqlcipher3_mutex_leave(p->pDestDb->mutex);
58320   }
58321   sqlcipher3BtreeLeave(p->pSrc);
58322   if( p->pDestDb ){
58323     /* EVIDENCE-OF: R-64852-21591 The sqlcipher3_backup object is created by a
58324     ** call to sqlcipher3_backup_init() and is destroyed by a call to
58325     ** sqlcipher3_backup_finish(). */
58326     sqlcipher3_free(p);
58327   }
58328   sqlcipher3_mutex_leave(mutex);
58329   return rc;
58330 }
58331
58332 /*
58333 ** Return the number of pages still to be backed up as of the most recent
58334 ** call to sqlcipher3_backup_step().
58335 */
58336 SQLCIPHER_API int sqlcipher3_backup_remaining(sqlcipher3_backup *p){
58337   return p->nRemaining;
58338 }
58339
58340 /*
58341 ** Return the total number of pages in the source database as of the most 
58342 ** recent call to sqlcipher3_backup_step().
58343 */
58344 SQLCIPHER_API int sqlcipher3_backup_pagecount(sqlcipher3_backup *p){
58345   return p->nPagecount;
58346 }
58347
58348 /*
58349 ** This function is called after the contents of page iPage of the
58350 ** source database have been modified. If page iPage has already been 
58351 ** copied into the destination database, then the data written to the
58352 ** destination is now invalidated. The destination copy of iPage needs
58353 ** to be updated with the new data before the backup operation is
58354 ** complete.
58355 **
58356 ** It is assumed that the mutex associated with the BtShared object
58357 ** corresponding to the source database is held when this function is
58358 ** called.
58359 */
58360 SQLCIPHER_PRIVATE void sqlcipher3BackupUpdate(sqlcipher3_backup *pBackup, Pgno iPage, const u8 *aData){
58361   sqlcipher3_backup *p;                   /* Iterator variable */
58362   for(p=pBackup; p; p=p->pNext){
58363     assert( sqlcipher3_mutex_held(p->pSrc->pBt->mutex) );
58364     if( !isFatalError(p->rc) && iPage<p->iNext ){
58365       /* The backup process p has already copied page iPage. But now it
58366       ** has been modified by a transaction on the source pager. Copy
58367       ** the new data into the backup.
58368       */
58369       int rc;
58370       assert( p->pDestDb );
58371       sqlcipher3_mutex_enter(p->pDestDb->mutex);
58372       rc = backupOnePage(p, iPage, aData);
58373       sqlcipher3_mutex_leave(p->pDestDb->mutex);
58374       assert( rc!=SQLCIPHER_BUSY && rc!=SQLCIPHER_LOCKED );
58375       if( rc!=SQLCIPHER_OK ){
58376         p->rc = rc;
58377       }
58378     }
58379   }
58380 }
58381
58382 /*
58383 ** Restart the backup process. This is called when the pager layer
58384 ** detects that the database has been modified by an external database
58385 ** connection. In this case there is no way of knowing which of the
58386 ** pages that have been copied into the destination database are still 
58387 ** valid and which are not, so the entire process needs to be restarted.
58388 **
58389 ** It is assumed that the mutex associated with the BtShared object
58390 ** corresponding to the source database is held when this function is
58391 ** called.
58392 */
58393 SQLCIPHER_PRIVATE void sqlcipher3BackupRestart(sqlcipher3_backup *pBackup){
58394   sqlcipher3_backup *p;                   /* Iterator variable */
58395   for(p=pBackup; p; p=p->pNext){
58396     assert( sqlcipher3_mutex_held(p->pSrc->pBt->mutex) );
58397     p->iNext = 1;
58398   }
58399 }
58400
58401 #ifndef SQLCIPHER_OMIT_VACUUM
58402 /*
58403 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
58404 ** must be active for both files.
58405 **
58406 ** The size of file pTo may be reduced by this operation. If anything 
58407 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
58408 ** transaction is committed before returning.
58409 */
58410 SQLCIPHER_PRIVATE int sqlcipher3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58411   int rc;
58412   sqlcipher3_file *pFd;              /* File descriptor for database pTo */
58413   sqlcipher3_backup b;
58414   sqlcipher3BtreeEnter(pTo);
58415   sqlcipher3BtreeEnter(pFrom);
58416
58417   assert( sqlcipher3BtreeIsInTrans(pTo) );
58418   pFd = sqlcipher3PagerFile(sqlcipher3BtreePager(pTo));
58419   if( pFd->pMethods ){
58420     i64 nByte = sqlcipher3BtreeGetPageSize(pFrom)*(i64)sqlcipher3BtreeLastPage(pFrom);
58421     sqlcipher3OsFileControl(pFd, SQLCIPHER_FCNTL_OVERWRITE, &nByte);
58422   }
58423
58424   /* Set up an sqlcipher3_backup object. sqlcipher3_backup.pDestDb must be set
58425   ** to 0. This is used by the implementations of sqlcipher3_backup_step()
58426   ** and sqlcipher3_backup_finish() to detect that they are being called
58427   ** from this function, not directly by the user.
58428   */
58429   memset(&b, 0, sizeof(b));
58430   b.pSrcDb = pFrom->db;
58431   b.pSrc = pFrom;
58432   b.pDest = pTo;
58433   b.iNext = 1;
58434
58435   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58436   ** file. By passing this as the number of pages to copy to
58437   ** sqlcipher3_backup_step(), we can guarantee that the copy finishes 
58438   ** within a single call (unless an error occurs). The assert() statement
58439   ** checks this assumption - (p->rc) should be set to either SQLCIPHER_DONE 
58440   ** or an error code.
58441   */
58442   sqlcipher3_backup_step(&b, 0x7FFFFFFF);
58443   assert( b.rc!=SQLCIPHER_OK );
58444   rc = sqlcipher3_backup_finish(&b);
58445   if( rc==SQLCIPHER_OK ){
58446     pTo->pBt->pageSizeFixed = 0;
58447   }else{
58448     sqlcipher3PagerClearCache(sqlcipher3BtreePager(b.pDest));
58449   }
58450
58451   assert( sqlcipher3BtreeIsInTrans(pTo)==0 );
58452   sqlcipher3BtreeLeave(pFrom);
58453   sqlcipher3BtreeLeave(pTo);
58454   return rc;
58455 }
58456 #endif /* SQLCIPHER_OMIT_VACUUM */
58457
58458 /************** End of backup.c **********************************************/
58459 /************** Begin file vdbemem.c *****************************************/
58460 /*
58461 ** 2004 May 26
58462 **
58463 ** The author disclaims copyright to this source code.  In place of
58464 ** a legal notice, here is a blessing:
58465 **
58466 **    May you do good and not evil.
58467 **    May you find forgiveness for yourself and forgive others.
58468 **    May you share freely, never taking more than you give.
58469 **
58470 *************************************************************************
58471 **
58472 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
58473 ** stores a single value in the VDBE.  Mem is an opaque structure visible
58474 ** only within the VDBE.  Interface routines refer to a Mem using the
58475 ** name sqlcipher_value
58476 */
58477
58478 /*
58479 ** Call sqlcipher3VdbeMemExpandBlob() on the supplied value (type Mem*)
58480 ** P if required.
58481 */
58482 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlcipher3VdbeMemExpandBlob(P):0)
58483
58484 /*
58485 ** If pMem is an object with a valid string representation, this routine
58486 ** ensures the internal encoding for the string representation is
58487 ** 'desiredEnc', one of SQLCIPHER_UTF8, SQLCIPHER_UTF16LE or SQLCIPHER_UTF16BE.
58488 **
58489 ** If pMem is not a string object, or the encoding of the string
58490 ** representation is already stored using the requested encoding, then this
58491 ** routine is a no-op.
58492 **
58493 ** SQLCIPHER_OK is returned if the conversion is successful (or not required).
58494 ** SQLCIPHER_NOMEM may be returned if a malloc() fails during conversion
58495 ** between formats.
58496 */
58497 SQLCIPHER_PRIVATE int sqlcipher3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58498   int rc;
58499   assert( (pMem->flags&MEM_RowSet)==0 );
58500   assert( desiredEnc==SQLCIPHER_UTF8 || desiredEnc==SQLCIPHER_UTF16LE
58501            || desiredEnc==SQLCIPHER_UTF16BE );
58502   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58503     return SQLCIPHER_OK;
58504   }
58505   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58506 #ifdef SQLCIPHER_OMIT_UTF16
58507   return SQLCIPHER_ERROR;
58508 #else
58509
58510   /* MemTranslate() may return SQLCIPHER_OK or SQLCIPHER_NOMEM. If NOMEM is returned,
58511   ** then the encoding of the value may not have changed.
58512   */
58513   rc = sqlcipher3VdbeMemTranslate(pMem, (u8)desiredEnc);
58514   assert(rc==SQLCIPHER_OK    || rc==SQLCIPHER_NOMEM);
58515   assert(rc==SQLCIPHER_OK    || pMem->enc!=desiredEnc);
58516   assert(rc==SQLCIPHER_NOMEM || pMem->enc==desiredEnc);
58517   return rc;
58518 #endif
58519 }
58520
58521 /*
58522 ** Make sure pMem->z points to a writable allocation of at least 
58523 ** n bytes.
58524 **
58525 ** If the memory cell currently contains string or blob data
58526 ** and the third argument passed to this function is true, the 
58527 ** current content of the cell is preserved. Otherwise, it may
58528 ** be discarded.  
58529 **
58530 ** This function sets the MEM_Dyn flag and clears any xDel callback.
58531 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
58532 ** not set, Mem.n is zeroed.
58533 */
58534 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemGrow(Mem *pMem, int n, int preserve){
58535   assert( 1 >=
58536     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58537     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
58538     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
58539     ((pMem->flags&MEM_Static) ? 1 : 0)
58540   );
58541   assert( (pMem->flags&MEM_RowSet)==0 );
58542
58543   if( n<32 ) n = 32;
58544   if( sqlcipher3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58545     if( preserve && pMem->z==pMem->zMalloc ){
58546       pMem->z = pMem->zMalloc = sqlcipher3DbReallocOrFree(pMem->db, pMem->z, n);
58547       preserve = 0;
58548     }else{
58549       sqlcipher3DbFree(pMem->db, pMem->zMalloc);
58550       pMem->zMalloc = sqlcipher3DbMallocRaw(pMem->db, n);
58551     }
58552   }
58553
58554   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58555     memcpy(pMem->zMalloc, pMem->z, pMem->n);
58556   }
58557   if( pMem->flags&MEM_Dyn && pMem->xDel ){
58558     pMem->xDel((void *)(pMem->z));
58559   }
58560
58561   pMem->z = pMem->zMalloc;
58562   if( pMem->z==0 ){
58563     pMem->flags = MEM_Null;
58564   }else{
58565     pMem->flags &= ~(MEM_Ephem|MEM_Static);
58566   }
58567   pMem->xDel = 0;
58568   return (pMem->z ? SQLCIPHER_OK : SQLCIPHER_NOMEM);
58569 }
58570
58571 /*
58572 ** Make the given Mem object MEM_Dyn.  In other words, make it so
58573 ** that any TEXT or BLOB content is stored in memory obtained from
58574 ** malloc().  In this way, we know that the memory is safe to be
58575 ** overwritten or altered.
58576 **
58577 ** Return SQLCIPHER_OK on success or SQLCIPHER_NOMEM if malloc fails.
58578 */
58579 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemMakeWriteable(Mem *pMem){
58580   int f;
58581   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58582   assert( (pMem->flags&MEM_RowSet)==0 );
58583   expandBlob(pMem);
58584   f = pMem->flags;
58585   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58586     if( sqlcipher3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58587       return SQLCIPHER_NOMEM;
58588     }
58589     pMem->z[pMem->n] = 0;
58590     pMem->z[pMem->n+1] = 0;
58591     pMem->flags |= MEM_Term;
58592 #ifdef SQLCIPHER_DEBUG
58593     pMem->pScopyFrom = 0;
58594 #endif
58595   }
58596
58597   return SQLCIPHER_OK;
58598 }
58599
58600 /*
58601 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
58602 ** blob stored in dynamically allocated space.
58603 */
58604 #ifndef SQLCIPHER_OMIT_INCRBLOB
58605 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemExpandBlob(Mem *pMem){
58606   if( pMem->flags & MEM_Zero ){
58607     int nByte;
58608     assert( pMem->flags&MEM_Blob );
58609     assert( (pMem->flags&MEM_RowSet)==0 );
58610     assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58611
58612     /* Set nByte to the number of bytes required to store the expanded blob. */
58613     nByte = pMem->n + pMem->u.nZero;
58614     if( nByte<=0 ){
58615       nByte = 1;
58616     }
58617     if( sqlcipher3VdbeMemGrow(pMem, nByte, 1) ){
58618       return SQLCIPHER_NOMEM;
58619     }
58620
58621     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
58622     pMem->n += pMem->u.nZero;
58623     pMem->flags &= ~(MEM_Zero|MEM_Term);
58624   }
58625   return SQLCIPHER_OK;
58626 }
58627 #endif
58628
58629
58630 /*
58631 ** Make sure the given Mem is \u0000 terminated.
58632 */
58633 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNulTerminate(Mem *pMem){
58634   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58635   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
58636     return SQLCIPHER_OK;   /* Nothing to do */
58637   }
58638   if( sqlcipher3VdbeMemGrow(pMem, pMem->n+2, 1) ){
58639     return SQLCIPHER_NOMEM;
58640   }
58641   pMem->z[pMem->n] = 0;
58642   pMem->z[pMem->n+1] = 0;
58643   pMem->flags |= MEM_Term;
58644   return SQLCIPHER_OK;
58645 }
58646
58647 /*
58648 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
58649 ** are converted using sqlcipher3_snprintf().  Converting a BLOB to a string
58650 ** is a no-op.
58651 **
58652 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
58653 **
58654 ** A MEM_Null value will never be passed to this function. This function is
58655 ** used for converting values to text for returning to the user (i.e. via
58656 ** sqlcipher3_value_text()), or for ensuring that values to be used as btree
58657 ** keys are strings. In the former case a NULL pointer is returned the
58658 ** user and the later is an internal programming error.
58659 */
58660 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemStringify(Mem *pMem, int enc){
58661   int rc = SQLCIPHER_OK;
58662   int fg = pMem->flags;
58663   const int nByte = 32;
58664
58665   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58666   assert( !(fg&MEM_Zero) );
58667   assert( !(fg&(MEM_Str|MEM_Blob)) );
58668   assert( fg&(MEM_Int|MEM_Real) );
58669   assert( (pMem->flags&MEM_RowSet)==0 );
58670   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58671
58672
58673   if( sqlcipher3VdbeMemGrow(pMem, nByte, 0) ){
58674     return SQLCIPHER_NOMEM;
58675   }
58676
58677   /* For a Real or Integer, use sqlcipher3_mprintf() to produce the UTF-8
58678   ** string representation of the value. Then, if the required encoding
58679   ** is UTF-16le or UTF-16be do a translation.
58680   ** 
58681   ** FIX ME: It would be better if sqlcipher3_snprintf() could do UTF-16.
58682   */
58683   if( fg & MEM_Int ){
58684     sqlcipher3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
58685   }else{
58686     assert( fg & MEM_Real );
58687     sqlcipher3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
58688   }
58689   pMem->n = sqlcipher3Strlen30(pMem->z);
58690   pMem->enc = SQLCIPHER_UTF8;
58691   pMem->flags |= MEM_Str|MEM_Term;
58692   sqlcipher3VdbeChangeEncoding(pMem, enc);
58693   return rc;
58694 }
58695
58696 /*
58697 ** Memory cell pMem contains the context of an aggregate function.
58698 ** This routine calls the finalize method for that function.  The
58699 ** result of the aggregate is stored back into pMem.
58700 **
58701 ** Return SQLCIPHER_ERROR if the finalizer reports an error.  SQLCIPHER_OK
58702 ** otherwise.
58703 */
58704 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
58705   int rc = SQLCIPHER_OK;
58706   if( ALWAYS(pFunc && pFunc->xFinalize) ){
58707     sqlcipher3_context ctx;
58708     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
58709     assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58710     memset(&ctx, 0, sizeof(ctx));
58711     ctx.s.flags = MEM_Null;
58712     ctx.s.db = pMem->db;
58713     ctx.pMem = pMem;
58714     ctx.pFunc = pFunc;
58715     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
58716     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
58717     sqlcipher3DbFree(pMem->db, pMem->zMalloc);
58718     memcpy(pMem, &ctx.s, sizeof(ctx.s));
58719     rc = ctx.isError;
58720   }
58721   return rc;
58722 }
58723
58724 /*
58725 ** If the memory cell contains a string value that must be freed by
58726 ** invoking an external callback, free it now. Calling this function
58727 ** does not free any Mem.zMalloc buffer.
58728 */
58729 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemReleaseExternal(Mem *p){
58730   assert( p->db==0 || sqlcipher3_mutex_held(p->db->mutex) );
58731   if( p->flags&MEM_Agg ){
58732     sqlcipher3VdbeMemFinalize(p, p->u.pDef);
58733     assert( (p->flags & MEM_Agg)==0 );
58734     sqlcipher3VdbeMemRelease(p);
58735   }else if( p->flags&MEM_Dyn && p->xDel ){
58736     assert( (p->flags&MEM_RowSet)==0 );
58737     p->xDel((void *)p->z);
58738     p->xDel = 0;
58739   }else if( p->flags&MEM_RowSet ){
58740     sqlcipher3RowSetClear(p->u.pRowSet);
58741   }else if( p->flags&MEM_Frame ){
58742     sqlcipher3VdbeMemSetNull(p);
58743   }
58744 }
58745
58746 /*
58747 ** Release any memory held by the Mem. This may leave the Mem in an
58748 ** inconsistent state, for example with (Mem.z==0) and
58749 ** (Mem.type==SQLCIPHER_TEXT).
58750 */
58751 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemRelease(Mem *p){
58752   MemReleaseExt(p);
58753   sqlcipher3DbFree(p->db, p->zMalloc);
58754   p->z = 0;
58755   p->zMalloc = 0;
58756   p->xDel = 0;
58757 }
58758
58759 /*
58760 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
58761 ** If the double is too large, return 0x8000000000000000.
58762 **
58763 ** Most systems appear to do this simply by assigning
58764 ** variables and without the extra range tests.  But
58765 ** there are reports that windows throws an expection
58766 ** if the floating point value is out of range. (See ticket #2880.)
58767 ** Because we do not completely understand the problem, we will
58768 ** take the conservative approach and always do range tests
58769 ** before attempting the conversion.
58770 */
58771 static i64 doubleToInt64(double r){
58772 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
58773   /* When floating-point is omitted, double and int64 are the same thing */
58774   return r;
58775 #else
58776   /*
58777   ** Many compilers we encounter do not define constants for the
58778   ** minimum and maximum 64-bit integers, or they define them
58779   ** inconsistently.  And many do not understand the "LL" notation.
58780   ** So we define our own static constants here using nothing
58781   ** larger than a 32-bit integer constant.
58782   */
58783   static const i64 maxInt = LARGEST_INT64;
58784   static const i64 minInt = SMALLEST_INT64;
58785
58786   if( r<(double)minInt ){
58787     return minInt;
58788   }else if( r>(double)maxInt ){
58789     /* minInt is correct here - not maxInt.  It turns out that assigning
58790     ** a very large positive number to an integer results in a very large
58791     ** negative integer.  This makes no sense, but it is what x86 hardware
58792     ** does so for compatibility we will do the same in software. */
58793     return minInt;
58794   }else{
58795     return (i64)r;
58796   }
58797 #endif
58798 }
58799
58800 /*
58801 ** Return some kind of integer value which is the best we can do
58802 ** at representing the value that *pMem describes as an integer.
58803 ** If pMem is an integer, then the value is exact.  If pMem is
58804 ** a floating-point then the value returned is the integer part.
58805 ** If pMem is a string or blob, then we make an attempt to convert
58806 ** it into a integer and return that.  If pMem represents an
58807 ** an SQL-NULL value, return 0.
58808 **
58809 ** If pMem represents a string value, its encoding might be changed.
58810 */
58811 SQLCIPHER_PRIVATE i64 sqlcipher3VdbeIntValue(Mem *pMem){
58812   int flags;
58813   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58814   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58815   flags = pMem->flags;
58816   if( flags & MEM_Int ){
58817     return pMem->u.i;
58818   }else if( flags & MEM_Real ){
58819     return doubleToInt64(pMem->r);
58820   }else if( flags & (MEM_Str|MEM_Blob) ){
58821     i64 value = 0;
58822     assert( pMem->z || pMem->n==0 );
58823     testcase( pMem->z==0 );
58824     sqlcipher3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
58825     return value;
58826   }else{
58827     return 0;
58828   }
58829 }
58830
58831 /*
58832 ** Return the best representation of pMem that we can get into a
58833 ** double.  If pMem is already a double or an integer, return its
58834 ** value.  If it is a string or blob, try to convert it to a double.
58835 ** If it is a NULL, return 0.0.
58836 */
58837 SQLCIPHER_PRIVATE double sqlcipher3VdbeRealValue(Mem *pMem){
58838   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58839   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58840   if( pMem->flags & MEM_Real ){
58841     return pMem->r;
58842   }else if( pMem->flags & MEM_Int ){
58843     return (double)pMem->u.i;
58844   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
58845     /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
58846     double val = (double)0;
58847     sqlcipher3AtoF(pMem->z, &val, pMem->n, pMem->enc);
58848     return val;
58849   }else{
58850     /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
58851     return (double)0;
58852   }
58853 }
58854
58855 /*
58856 ** The MEM structure is already a MEM_Real.  Try to also make it a
58857 ** MEM_Int if we can.
58858 */
58859 SQLCIPHER_PRIVATE void sqlcipher3VdbeIntegerAffinity(Mem *pMem){
58860   assert( pMem->flags & MEM_Real );
58861   assert( (pMem->flags & MEM_RowSet)==0 );
58862   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58863   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58864
58865   pMem->u.i = doubleToInt64(pMem->r);
58866
58867   /* Only mark the value as an integer if
58868   **
58869   **    (1) the round-trip conversion real->int->real is a no-op, and
58870   **    (2) The integer is neither the largest nor the smallest
58871   **        possible integer (ticket #3922)
58872   **
58873   ** The second and third terms in the following conditional enforces
58874   ** the second condition under the assumption that addition overflow causes
58875   ** values to wrap around.  On x86 hardware, the third term is always
58876   ** true and could be omitted.  But we leave it in because other
58877   ** architectures might behave differently.
58878   */
58879   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
58880       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
58881     pMem->flags |= MEM_Int;
58882   }
58883 }
58884
58885 /*
58886 ** Convert pMem to type integer.  Invalidate any prior representations.
58887 */
58888 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemIntegerify(Mem *pMem){
58889   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58890   assert( (pMem->flags & MEM_RowSet)==0 );
58891   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58892
58893   pMem->u.i = sqlcipher3VdbeIntValue(pMem);
58894   MemSetTypeFlag(pMem, MEM_Int);
58895   return SQLCIPHER_OK;
58896 }
58897
58898 /*
58899 ** Convert pMem so that it is of type MEM_Real.
58900 ** Invalidate any prior representations.
58901 */
58902 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemRealify(Mem *pMem){
58903   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58904   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58905
58906   pMem->r = sqlcipher3VdbeRealValue(pMem);
58907   MemSetTypeFlag(pMem, MEM_Real);
58908   return SQLCIPHER_OK;
58909 }
58910
58911 /*
58912 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
58913 ** Invalidate any prior representations.
58914 **
58915 ** Every effort is made to force the conversion, even if the input
58916 ** is a string that does not look completely like a number.  Convert
58917 ** as much of the string as we can and ignore the rest.
58918 */
58919 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemNumerify(Mem *pMem){
58920   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
58921     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
58922     assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
58923     if( 0==sqlcipher3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
58924       MemSetTypeFlag(pMem, MEM_Int);
58925     }else{
58926       pMem->r = sqlcipher3VdbeRealValue(pMem);
58927       MemSetTypeFlag(pMem, MEM_Real);
58928       sqlcipher3VdbeIntegerAffinity(pMem);
58929     }
58930   }
58931   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
58932   pMem->flags &= ~(MEM_Str|MEM_Blob);
58933   return SQLCIPHER_OK;
58934 }
58935
58936 /*
58937 ** Delete any previous value and set the value stored in *pMem to NULL.
58938 */
58939 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetNull(Mem *pMem){
58940   if( pMem->flags & MEM_Frame ){
58941     VdbeFrame *pFrame = pMem->u.pFrame;
58942     pFrame->pParent = pFrame->v->pDelFrame;
58943     pFrame->v->pDelFrame = pFrame;
58944   }
58945   if( pMem->flags & MEM_RowSet ){
58946     sqlcipher3RowSetClear(pMem->u.pRowSet);
58947   }
58948   MemSetTypeFlag(pMem, MEM_Null);
58949   pMem->type = SQLCIPHER_NULL;
58950 }
58951
58952 /*
58953 ** Delete any previous value and set the value to be a BLOB of length
58954 ** n containing all zeros.
58955 */
58956 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetZeroBlob(Mem *pMem, int n){
58957   sqlcipher3VdbeMemRelease(pMem);
58958   pMem->flags = MEM_Blob|MEM_Zero;
58959   pMem->type = SQLCIPHER_BLOB;
58960   pMem->n = 0;
58961   if( n<0 ) n = 0;
58962   pMem->u.nZero = n;
58963   pMem->enc = SQLCIPHER_UTF8;
58964
58965 #ifdef SQLCIPHER_OMIT_INCRBLOB
58966   sqlcipher3VdbeMemGrow(pMem, n, 0);
58967   if( pMem->z ){
58968     pMem->n = n;
58969     memset(pMem->z, 0, n);
58970   }
58971 #endif
58972 }
58973
58974 /*
58975 ** Delete any previous value and set the value stored in *pMem to val,
58976 ** manifest type INTEGER.
58977 */
58978 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetInt64(Mem *pMem, i64 val){
58979   sqlcipher3VdbeMemRelease(pMem);
58980   pMem->u.i = val;
58981   pMem->flags = MEM_Int;
58982   pMem->type = SQLCIPHER_INTEGER;
58983 }
58984
58985 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
58986 /*
58987 ** Delete any previous value and set the value stored in *pMem to val,
58988 ** manifest type REAL.
58989 */
58990 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetDouble(Mem *pMem, double val){
58991   if( sqlcipher3IsNaN(val) ){
58992     sqlcipher3VdbeMemSetNull(pMem);
58993   }else{
58994     sqlcipher3VdbeMemRelease(pMem);
58995     pMem->r = val;
58996     pMem->flags = MEM_Real;
58997     pMem->type = SQLCIPHER_FLOAT;
58998   }
58999 }
59000 #endif
59001
59002 /*
59003 ** Delete any previous value and set the value of pMem to be an
59004 ** empty boolean index.
59005 */
59006 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemSetRowSet(Mem *pMem){
59007   sqlcipher3 *db = pMem->db;
59008   assert( db!=0 );
59009   assert( (pMem->flags & MEM_RowSet)==0 );
59010   sqlcipher3VdbeMemRelease(pMem);
59011   pMem->zMalloc = sqlcipher3DbMallocRaw(db, 64);
59012   if( db->mallocFailed ){
59013     pMem->flags = MEM_Null;
59014   }else{
59015     assert( pMem->zMalloc );
59016     pMem->u.pRowSet = sqlcipher3RowSetInit(db, pMem->zMalloc, 
59017                                        sqlcipher3DbMallocSize(db, pMem->zMalloc));
59018     assert( pMem->u.pRowSet!=0 );
59019     pMem->flags = MEM_RowSet;
59020   }
59021 }
59022
59023 /*
59024 ** Return true if the Mem object contains a TEXT or BLOB that is
59025 ** too large - whose size exceeds SQLCIPHER_MAX_LENGTH.
59026 */
59027 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemTooBig(Mem *p){
59028   assert( p->db!=0 );
59029   if( p->flags & (MEM_Str|MEM_Blob) ){
59030     int n = p->n;
59031     if( p->flags & MEM_Zero ){
59032       n += p->u.nZero;
59033     }
59034     return n>p->db->aLimit[SQLCIPHER_LIMIT_LENGTH];
59035   }
59036   return 0; 
59037 }
59038
59039 #ifdef SQLCIPHER_DEBUG
59040 /*
59041 ** This routine prepares a memory cell for modication by breaking
59042 ** its link to a shallow copy and by marking any current shallow
59043 ** copies of this cell as invalid.
59044 **
59045 ** This is used for testing and debugging only - to make sure shallow
59046 ** copies are not misused.
59047 */
59048 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
59049   int i;
59050   Mem *pX;
59051   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59052     if( pX->pScopyFrom==pMem ){
59053       pX->flags |= MEM_Invalid;
59054       pX->pScopyFrom = 0;
59055     }
59056   }
59057   pMem->pScopyFrom = 0;
59058 }
59059 #endif /* SQLCIPHER_DEBUG */
59060
59061 /*
59062 ** Size of struct Mem not including the Mem.zMalloc member.
59063 */
59064 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59065
59066 /*
59067 ** Make an shallow copy of pFrom into pTo.  Prior contents of
59068 ** pTo are freed.  The pFrom->z field is not duplicated.  If
59069 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59070 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
59071 */
59072 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59073   assert( (pFrom->flags & MEM_RowSet)==0 );
59074   MemReleaseExt(pTo);
59075   memcpy(pTo, pFrom, MEMCELLSIZE);
59076   pTo->xDel = 0;
59077   if( (pFrom->flags&MEM_Static)==0 ){
59078     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59079     assert( srcType==MEM_Ephem || srcType==MEM_Static );
59080     pTo->flags |= srcType;
59081   }
59082 }
59083
59084 /*
59085 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
59086 ** freed before the copy is made.
59087 */
59088 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59089   int rc = SQLCIPHER_OK;
59090
59091   assert( (pFrom->flags & MEM_RowSet)==0 );
59092   MemReleaseExt(pTo);
59093   memcpy(pTo, pFrom, MEMCELLSIZE);
59094   pTo->flags &= ~MEM_Dyn;
59095
59096   if( pTo->flags&(MEM_Str|MEM_Blob) ){
59097     if( 0==(pFrom->flags&MEM_Static) ){
59098       pTo->flags |= MEM_Ephem;
59099       rc = sqlcipher3VdbeMemMakeWriteable(pTo);
59100     }
59101   }
59102
59103   return rc;
59104 }
59105
59106 /*
59107 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59108 ** freed. If pFrom contains ephemeral data, a copy is made.
59109 **
59110 ** pFrom contains an SQL NULL when this routine returns.
59111 */
59112 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemMove(Mem *pTo, Mem *pFrom){
59113   assert( pFrom->db==0 || sqlcipher3_mutex_held(pFrom->db->mutex) );
59114   assert( pTo->db==0 || sqlcipher3_mutex_held(pTo->db->mutex) );
59115   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59116
59117   sqlcipher3VdbeMemRelease(pTo);
59118   memcpy(pTo, pFrom, sizeof(Mem));
59119   pFrom->flags = MEM_Null;
59120   pFrom->xDel = 0;
59121   pFrom->zMalloc = 0;
59122 }
59123
59124 /*
59125 ** Change the value of a Mem to be a string or a BLOB.
59126 **
59127 ** The memory management strategy depends on the value of the xDel
59128 ** parameter. If the value passed is SQLCIPHER_TRANSIENT, then the 
59129 ** string is copied into a (possibly existing) buffer managed by the 
59130 ** Mem structure. Otherwise, any existing buffer is freed and the
59131 ** pointer copied.
59132 **
59133 ** If the string is too large (if it exceeds the SQLCIPHER_LIMIT_LENGTH
59134 ** size limit) then no memory allocation occurs.  If the string can be
59135 ** stored without allocating memory, then it is.  If a memory allocation
59136 ** is required to store the string, then value of pMem is unchanged.  In
59137 ** either case, SQLCIPHER_TOOBIG is returned.
59138 */
59139 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemSetStr(
59140   Mem *pMem,          /* Memory cell to set to string value */
59141   const char *z,      /* String pointer */
59142   int n,              /* Bytes in string, or negative */
59143   u8 enc,             /* Encoding of z.  0 for BLOBs */
59144   void (*xDel)(void*) /* Destructor function */
59145 ){
59146   int nByte = n;      /* New value for pMem->n */
59147   int iLimit;         /* Maximum allowed string or blob size */
59148   u16 flags = 0;      /* New value for pMem->flags */
59149
59150   assert( pMem->db==0 || sqlcipher3_mutex_held(pMem->db->mutex) );
59151   assert( (pMem->flags & MEM_RowSet)==0 );
59152
59153   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59154   if( !z ){
59155     sqlcipher3VdbeMemSetNull(pMem);
59156     return SQLCIPHER_OK;
59157   }
59158
59159   if( pMem->db ){
59160     iLimit = pMem->db->aLimit[SQLCIPHER_LIMIT_LENGTH];
59161   }else{
59162     iLimit = SQLCIPHER_MAX_LENGTH;
59163   }
59164   flags = (enc==0?MEM_Blob:MEM_Str);
59165   if( nByte<0 ){
59166     assert( enc!=0 );
59167     if( enc==SQLCIPHER_UTF8 ){
59168       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59169     }else{
59170       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59171     }
59172     flags |= MEM_Term;
59173   }
59174
59175   /* The following block sets the new values of Mem.z and Mem.xDel. It
59176   ** also sets a flag in local variable "flags" to indicate the memory
59177   ** management (one of MEM_Dyn or MEM_Static).
59178   */
59179   if( xDel==SQLCIPHER_TRANSIENT ){
59180     int nAlloc = nByte;
59181     if( flags&MEM_Term ){
59182       nAlloc += (enc==SQLCIPHER_UTF8?1:2);
59183     }
59184     if( nByte>iLimit ){
59185       return SQLCIPHER_TOOBIG;
59186     }
59187     if( sqlcipher3VdbeMemGrow(pMem, nAlloc, 0) ){
59188       return SQLCIPHER_NOMEM;
59189     }
59190     memcpy(pMem->z, z, nAlloc);
59191   }else if( xDel==SQLCIPHER_DYNAMIC ){
59192     sqlcipher3VdbeMemRelease(pMem);
59193     pMem->zMalloc = pMem->z = (char *)z;
59194     pMem->xDel = 0;
59195   }else{
59196     sqlcipher3VdbeMemRelease(pMem);
59197     pMem->z = (char *)z;
59198     pMem->xDel = xDel;
59199     flags |= ((xDel==SQLCIPHER_STATIC)?MEM_Static:MEM_Dyn);
59200   }
59201
59202   pMem->n = nByte;
59203   pMem->flags = flags;
59204   pMem->enc = (enc==0 ? SQLCIPHER_UTF8 : enc);
59205   pMem->type = (enc==0 ? SQLCIPHER_BLOB : SQLCIPHER_TEXT);
59206
59207 #ifndef SQLCIPHER_OMIT_UTF16
59208   if( pMem->enc!=SQLCIPHER_UTF8 && sqlcipher3VdbeMemHandleBom(pMem) ){
59209     return SQLCIPHER_NOMEM;
59210   }
59211 #endif
59212
59213   if( nByte>iLimit ){
59214     return SQLCIPHER_TOOBIG;
59215   }
59216
59217   return SQLCIPHER_OK;
59218 }
59219
59220 /*
59221 ** Compare the values contained by the two memory cells, returning
59222 ** negative, zero or positive if pMem1 is less than, equal to, or greater
59223 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59224 ** and reals) sorted numerically, followed by text ordered by the collating
59225 ** sequence pColl and finally blob's ordered by memcmp().
59226 **
59227 ** Two NULL values are considered equal by this function.
59228 */
59229 SQLCIPHER_PRIVATE int sqlcipher3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59230   int rc;
59231   int f1, f2;
59232   int combined_flags;
59233
59234   f1 = pMem1->flags;
59235   f2 = pMem2->flags;
59236   combined_flags = f1|f2;
59237   assert( (combined_flags & MEM_RowSet)==0 );
59238  
59239   /* If one value is NULL, it is less than the other. If both values
59240   ** are NULL, return 0.
59241   */
59242   if( combined_flags&MEM_Null ){
59243     return (f2&MEM_Null) - (f1&MEM_Null);
59244   }
59245
59246   /* If one value is a number and the other is not, the number is less.
59247   ** If both are numbers, compare as reals if one is a real, or as integers
59248   ** if both values are integers.
59249   */
59250   if( combined_flags&(MEM_Int|MEM_Real) ){
59251     if( !(f1&(MEM_Int|MEM_Real)) ){
59252       return 1;
59253     }
59254     if( !(f2&(MEM_Int|MEM_Real)) ){
59255       return -1;
59256     }
59257     if( (f1 & f2 & MEM_Int)==0 ){
59258       double r1, r2;
59259       if( (f1&MEM_Real)==0 ){
59260         r1 = (double)pMem1->u.i;
59261       }else{
59262         r1 = pMem1->r;
59263       }
59264       if( (f2&MEM_Real)==0 ){
59265         r2 = (double)pMem2->u.i;
59266       }else{
59267         r2 = pMem2->r;
59268       }
59269       if( r1<r2 ) return -1;
59270       if( r1>r2 ) return 1;
59271       return 0;
59272     }else{
59273       assert( f1&MEM_Int );
59274       assert( f2&MEM_Int );
59275       if( pMem1->u.i < pMem2->u.i ) return -1;
59276       if( pMem1->u.i > pMem2->u.i ) return 1;
59277       return 0;
59278     }
59279   }
59280
59281   /* If one value is a string and the other is a blob, the string is less.
59282   ** If both are strings, compare using the collating functions.
59283   */
59284   if( combined_flags&MEM_Str ){
59285     if( (f1 & MEM_Str)==0 ){
59286       return 1;
59287     }
59288     if( (f2 & MEM_Str)==0 ){
59289       return -1;
59290     }
59291
59292     assert( pMem1->enc==pMem2->enc );
59293     assert( pMem1->enc==SQLCIPHER_UTF8 || 
59294             pMem1->enc==SQLCIPHER_UTF16LE || pMem1->enc==SQLCIPHER_UTF16BE );
59295
59296     /* The collation sequence must be defined at this point, even if
59297     ** the user deletes the collation sequence after the vdbe program is
59298     ** compiled (this was not always the case).
59299     */
59300     assert( !pColl || pColl->xCmp );
59301
59302     if( pColl ){
59303       if( pMem1->enc==pColl->enc ){
59304         /* The strings are already in the correct encoding.  Call the
59305         ** comparison function directly */
59306         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59307       }else{
59308         const void *v1, *v2;
59309         int n1, n2;
59310         Mem c1;
59311         Mem c2;
59312         memset(&c1, 0, sizeof(c1));
59313         memset(&c2, 0, sizeof(c2));
59314         sqlcipher3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59315         sqlcipher3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59316         v1 = sqlcipher3ValueText((sqlcipher3_value*)&c1, pColl->enc);
59317         n1 = v1==0 ? 0 : c1.n;
59318         v2 = sqlcipher3ValueText((sqlcipher3_value*)&c2, pColl->enc);
59319         n2 = v2==0 ? 0 : c2.n;
59320         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59321         sqlcipher3VdbeMemRelease(&c1);
59322         sqlcipher3VdbeMemRelease(&c2);
59323         return rc;
59324       }
59325     }
59326     /* If a NULL pointer was passed as the collate function, fall through
59327     ** to the blob case and use memcmp().  */
59328   }
59329  
59330   /* Both values must be blobs.  Compare using memcmp().  */
59331   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59332   if( rc==0 ){
59333     rc = pMem1->n - pMem2->n;
59334   }
59335   return rc;
59336 }
59337
59338 /*
59339 ** Move data out of a btree key or data field and into a Mem structure.
59340 ** The data or key is taken from the entry that pCur is currently pointing
59341 ** to.  offset and amt determine what portion of the data or key to retrieve.
59342 ** key is true to get the key or false to get data.  The result is written
59343 ** into the pMem element.
59344 **
59345 ** The pMem structure is assumed to be uninitialized.  Any prior content
59346 ** is overwritten without being freed.
59347 **
59348 ** If this routine fails for any reason (malloc returns NULL or unable
59349 ** to read from the disk) then the pMem is left in an inconsistent state.
59350 */
59351 SQLCIPHER_PRIVATE int sqlcipher3VdbeMemFromBtree(
59352   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59353   int offset,       /* Offset from the start of data to return bytes from. */
59354   int amt,          /* Number of bytes to return. */
59355   int key,          /* If true, retrieve from the btree key, not data. */
59356   Mem *pMem         /* OUT: Return data in this Mem structure. */
59357 ){
59358   char *zData;        /* Data from the btree layer */
59359   int available = 0;  /* Number of bytes available on the local btree page */
59360   int rc = SQLCIPHER_OK; /* Return code */
59361
59362   assert( sqlcipher3BtreeCursorIsValid(pCur) );
59363
59364   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
59365   ** that both the BtShared and database handle mutexes are held. */
59366   assert( (pMem->flags & MEM_RowSet)==0 );
59367   if( key ){
59368     zData = (char *)sqlcipher3BtreeKeyFetch(pCur, &available);
59369   }else{
59370     zData = (char *)sqlcipher3BtreeDataFetch(pCur, &available);
59371   }
59372   assert( zData!=0 );
59373
59374   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59375     sqlcipher3VdbeMemRelease(pMem);
59376     pMem->z = &zData[offset];
59377     pMem->flags = MEM_Blob|MEM_Ephem;
59378   }else if( SQLCIPHER_OK==(rc = sqlcipher3VdbeMemGrow(pMem, amt+2, 0)) ){
59379     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59380     pMem->enc = 0;
59381     pMem->type = SQLCIPHER_BLOB;
59382     if( key ){
59383       rc = sqlcipher3BtreeKey(pCur, offset, amt, pMem->z);
59384     }else{
59385       rc = sqlcipher3BtreeData(pCur, offset, amt, pMem->z);
59386     }
59387     pMem->z[amt] = 0;
59388     pMem->z[amt+1] = 0;
59389     if( rc!=SQLCIPHER_OK ){
59390       sqlcipher3VdbeMemRelease(pMem);
59391     }
59392   }
59393   pMem->n = amt;
59394
59395   return rc;
59396 }
59397
59398 /* This function is only available internally, it is not part of the
59399 ** external API. It works in a similar way to sqlcipher3_value_text(),
59400 ** except the data returned is in the encoding specified by the second
59401 ** parameter, which must be one of SQLCIPHER_UTF16BE, SQLCIPHER_UTF16LE or
59402 ** SQLCIPHER_UTF8.
59403 **
59404 ** (2006-02-16:)  The enc value can be or-ed with SQLCIPHER_UTF16_ALIGNED.
59405 ** If that is the case, then the result must be aligned on an even byte
59406 ** boundary.
59407 */
59408 SQLCIPHER_PRIVATE const void *sqlcipher3ValueText(sqlcipher3_value* pVal, u8 enc){
59409   if( !pVal ) return 0;
59410
59411   assert( pVal->db==0 || sqlcipher3_mutex_held(pVal->db->mutex) );
59412   assert( (enc&3)==(enc&~SQLCIPHER_UTF16_ALIGNED) );
59413   assert( (pVal->flags & MEM_RowSet)==0 );
59414
59415   if( pVal->flags&MEM_Null ){
59416     return 0;
59417   }
59418   assert( (MEM_Blob>>3) == MEM_Str );
59419   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59420   expandBlob(pVal);
59421   if( pVal->flags&MEM_Str ){
59422     sqlcipher3VdbeChangeEncoding(pVal, enc & ~SQLCIPHER_UTF16_ALIGNED);
59423     if( (enc & SQLCIPHER_UTF16_ALIGNED)!=0 && 1==(1&SQLCIPHER_PTR_TO_INT(pVal->z)) ){
59424       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59425       if( sqlcipher3VdbeMemMakeWriteable(pVal)!=SQLCIPHER_OK ){
59426         return 0;
59427       }
59428     }
59429     sqlcipher3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
59430   }else{
59431     assert( (pVal->flags&MEM_Blob)==0 );
59432     sqlcipher3VdbeMemStringify(pVal, enc);
59433     assert( 0==(1&SQLCIPHER_PTR_TO_INT(pVal->z)) );
59434   }
59435   assert(pVal->enc==(enc & ~SQLCIPHER_UTF16_ALIGNED) || pVal->db==0
59436               || pVal->db->mallocFailed );
59437   if( pVal->enc==(enc & ~SQLCIPHER_UTF16_ALIGNED) ){
59438     return pVal->z;
59439   }else{
59440     return 0;
59441   }
59442 }
59443
59444 /*
59445 ** Create a new sqlcipher3_value object.
59446 */
59447 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3ValueNew(sqlcipher3 *db){
59448   Mem *p = sqlcipher3DbMallocZero(db, sizeof(*p));
59449   if( p ){
59450     p->flags = MEM_Null;
59451     p->type = SQLCIPHER_NULL;
59452     p->db = db;
59453   }
59454   return p;
59455 }
59456
59457 /*
59458 ** Create a new sqlcipher3_value object, containing the value of pExpr.
59459 **
59460 ** This only works for very simple expressions that consist of one constant
59461 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
59462 ** be converted directly into a value, then the value is allocated and
59463 ** a pointer written to *ppVal. The caller is responsible for deallocating
59464 ** the value by passing it to sqlcipher3ValueFree() later on. If the expression
59465 ** cannot be converted to a value, then *ppVal is set to NULL.
59466 */
59467 SQLCIPHER_PRIVATE int sqlcipher3ValueFromExpr(
59468   sqlcipher3 *db,              /* The database connection */
59469   Expr *pExpr,              /* The expression to evaluate */
59470   u8 enc,                   /* Encoding to use */
59471   u8 affinity,              /* Affinity to use */
59472   sqlcipher3_value **ppVal     /* Write the new value here */
59473 ){
59474   int op;
59475   char *zVal = 0;
59476   sqlcipher3_value *pVal = 0;
59477   int negInt = 1;
59478   const char *zNeg = "";
59479
59480   if( !pExpr ){
59481     *ppVal = 0;
59482     return SQLCIPHER_OK;
59483   }
59484   op = pExpr->op;
59485
59486   /* op can only be TK_REGISTER if we have compiled with SQLCIPHER_ENABLE_STAT3.
59487   ** The ifdef here is to enable us to achieve 100% branch test coverage even
59488   ** when SQLCIPHER_ENABLE_STAT3 is omitted.
59489   */
59490 #ifdef SQLCIPHER_ENABLE_STAT3
59491   if( op==TK_REGISTER ) op = pExpr->op2;
59492 #else
59493   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59494 #endif
59495
59496   /* Handle negative integers in a single step.  This is needed in the
59497   ** case when the value is -9223372036854775808.
59498   */
59499   if( op==TK_UMINUS
59500    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59501     pExpr = pExpr->pLeft;
59502     op = pExpr->op;
59503     negInt = -1;
59504     zNeg = "-";
59505   }
59506
59507   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59508     pVal = sqlcipher3ValueNew(db);
59509     if( pVal==0 ) goto no_mem;
59510     if( ExprHasProperty(pExpr, EP_IntValue) ){
59511       sqlcipher3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59512     }else{
59513       zVal = sqlcipher3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59514       if( zVal==0 ) goto no_mem;
59515       sqlcipher3ValueSetStr(pVal, -1, zVal, SQLCIPHER_UTF8, SQLCIPHER_DYNAMIC);
59516       if( op==TK_FLOAT ) pVal->type = SQLCIPHER_FLOAT;
59517     }
59518     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLCIPHER_AFF_NONE ){
59519       sqlcipher3ValueApplyAffinity(pVal, SQLCIPHER_AFF_NUMERIC, SQLCIPHER_UTF8);
59520     }else{
59521       sqlcipher3ValueApplyAffinity(pVal, affinity, SQLCIPHER_UTF8);
59522     }
59523     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59524     if( enc!=SQLCIPHER_UTF8 ){
59525       sqlcipher3VdbeChangeEncoding(pVal, enc);
59526     }
59527   }else if( op==TK_UMINUS ) {
59528     /* This branch happens for multiple negative signs.  Ex: -(-5) */
59529     if( SQLCIPHER_OK==sqlcipher3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59530       sqlcipher3VdbeMemNumerify(pVal);
59531       if( pVal->u.i==SMALLEST_INT64 ){
59532         pVal->flags &= MEM_Int;
59533         pVal->flags |= MEM_Real;
59534         pVal->r = (double)LARGEST_INT64;
59535       }else{
59536         pVal->u.i = -pVal->u.i;
59537       }
59538       pVal->r = -pVal->r;
59539       sqlcipher3ValueApplyAffinity(pVal, affinity, enc);
59540     }
59541   }else if( op==TK_NULL ){
59542     pVal = sqlcipher3ValueNew(db);
59543     if( pVal==0 ) goto no_mem;
59544   }
59545 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
59546   else if( op==TK_BLOB ){
59547     int nVal;
59548     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59549     assert( pExpr->u.zToken[1]=='\'' );
59550     pVal = sqlcipher3ValueNew(db);
59551     if( !pVal ) goto no_mem;
59552     zVal = &pExpr->u.zToken[2];
59553     nVal = sqlcipher3Strlen30(zVal)-1;
59554     assert( zVal[nVal]=='\'' );
59555     sqlcipher3VdbeMemSetStr(pVal, sqlcipher3HexToBlob(db, zVal, nVal), nVal/2,
59556                          0, SQLCIPHER_DYNAMIC);
59557   }
59558 #endif
59559
59560   if( pVal ){
59561     sqlcipher3VdbeMemStoreType(pVal);
59562   }
59563   *ppVal = pVal;
59564   return SQLCIPHER_OK;
59565
59566 no_mem:
59567   db->mallocFailed = 1;
59568   sqlcipher3DbFree(db, zVal);
59569   sqlcipher3ValueFree(pVal);
59570   *ppVal = 0;
59571   return SQLCIPHER_NOMEM;
59572 }
59573
59574 /*
59575 ** Change the string value of an sqlcipher3_value object
59576 */
59577 SQLCIPHER_PRIVATE void sqlcipher3ValueSetStr(
59578   sqlcipher3_value *v,     /* Value to be set */
59579   int n,                /* Length of string z */
59580   const void *z,        /* Text of the new string */
59581   u8 enc,               /* Encoding to use */
59582   void (*xDel)(void*)   /* Destructor for the string */
59583 ){
59584   if( v ) sqlcipher3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59585 }
59586
59587 /*
59588 ** Free an sqlcipher3_value object
59589 */
59590 SQLCIPHER_PRIVATE void sqlcipher3ValueFree(sqlcipher3_value *v){
59591   if( !v ) return;
59592   sqlcipher3VdbeMemRelease((Mem *)v);
59593   sqlcipher3DbFree(((Mem*)v)->db, v);
59594 }
59595
59596 /*
59597 ** Return the number of bytes in the sqlcipher3_value object assuming
59598 ** that it uses the encoding "enc"
59599 */
59600 SQLCIPHER_PRIVATE int sqlcipher3ValueBytes(sqlcipher3_value *pVal, u8 enc){
59601   Mem *p = (Mem*)pVal;
59602   if( (p->flags & MEM_Blob)!=0 || sqlcipher3ValueText(pVal, enc) ){
59603     if( p->flags & MEM_Zero ){
59604       return p->n + p->u.nZero;
59605     }else{
59606       return p->n;
59607     }
59608   }
59609   return 0;
59610 }
59611
59612 /************** End of vdbemem.c *********************************************/
59613 /************** Begin file vdbeaux.c *****************************************/
59614 /*
59615 ** 2003 September 6
59616 **
59617 ** The author disclaims copyright to this source code.  In place of
59618 ** a legal notice, here is a blessing:
59619 **
59620 **    May you do good and not evil.
59621 **    May you find forgiveness for yourself and forgive others.
59622 **    May you share freely, never taking more than you give.
59623 **
59624 *************************************************************************
59625 ** This file contains code used for creating, destroying, and populating
59626 ** a VDBE (or an "sqlcipher3_stmt" as it is known to the outside world.)  Prior
59627 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
59628 ** But that file was getting too big so this subroutines were split out.
59629 */
59630
59631
59632
59633 /*
59634 ** When debugging the code generator in a symbolic debugger, one can
59635 ** set the sqlcipher3VdbeAddopTrace to 1 and all opcodes will be printed
59636 ** as they are added to the instruction stream.
59637 */
59638 #ifdef SQLCIPHER_DEBUG
59639 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddopTrace = 0;
59640 #endif
59641
59642
59643 /*
59644 ** Create a new virtual database engine.
59645 */
59646 SQLCIPHER_PRIVATE Vdbe *sqlcipher3VdbeCreate(sqlcipher3 *db){
59647   Vdbe *p;
59648   p = sqlcipher3DbMallocZero(db, sizeof(Vdbe) );
59649   if( p==0 ) return 0;
59650   p->db = db;
59651   if( db->pVdbe ){
59652     db->pVdbe->pPrev = p;
59653   }
59654   p->pNext = db->pVdbe;
59655   p->pPrev = 0;
59656   db->pVdbe = p;
59657   p->magic = VDBE_MAGIC_INIT;
59658   return p;
59659 }
59660
59661 /*
59662 ** Remember the SQL string for a prepared statement.
59663 */
59664 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
59665   assert( isPrepareV2==1 || isPrepareV2==0 );
59666   if( p==0 ) return;
59667 #ifdef SQLCIPHER_OMIT_TRACE
59668   if( !isPrepareV2 ) return;
59669 #endif
59670   assert( p->zSql==0 );
59671   p->zSql = sqlcipher3DbStrNDup(p->db, z, n);
59672   p->isPrepareV2 = (u8)isPrepareV2;
59673 }
59674
59675 /*
59676 ** Return the SQL associated with a prepared statement
59677 */
59678 SQLCIPHER_API const char *sqlcipher3_sql(sqlcipher3_stmt *pStmt){
59679   Vdbe *p = (Vdbe *)pStmt;
59680   return (p && p->isPrepareV2) ? p->zSql : 0;
59681 }
59682
59683 /*
59684 ** Swap all content between two VDBE structures.
59685 */
59686 SQLCIPHER_PRIVATE void sqlcipher3VdbeSwap(Vdbe *pA, Vdbe *pB){
59687   Vdbe tmp, *pTmp;
59688   char *zTmp;
59689   tmp = *pA;
59690   *pA = *pB;
59691   *pB = tmp;
59692   pTmp = pA->pNext;
59693   pA->pNext = pB->pNext;
59694   pB->pNext = pTmp;
59695   pTmp = pA->pPrev;
59696   pA->pPrev = pB->pPrev;
59697   pB->pPrev = pTmp;
59698   zTmp = pA->zSql;
59699   pA->zSql = pB->zSql;
59700   pB->zSql = zTmp;
59701   pB->isPrepareV2 = pA->isPrepareV2;
59702 }
59703
59704 #ifdef SQLCIPHER_DEBUG
59705 /*
59706 ** Turn tracing on or off
59707 */
59708 SQLCIPHER_PRIVATE void sqlcipher3VdbeTrace(Vdbe *p, FILE *trace){
59709   p->trace = trace;
59710 }
59711 #endif
59712
59713 /*
59714 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
59715 ** it was.
59716 **
59717 ** If an out-of-memory error occurs while resizing the array, return
59718 ** SQLCIPHER_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
59719 ** unchanged (this is so that any opcodes already allocated can be 
59720 ** correctly deallocated along with the rest of the Vdbe).
59721 */
59722 static int growOpArray(Vdbe *p){
59723   VdbeOp *pNew;
59724   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
59725   pNew = sqlcipher3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
59726   if( pNew ){
59727     p->nOpAlloc = sqlcipher3DbMallocSize(p->db, pNew)/sizeof(Op);
59728     p->aOp = pNew;
59729   }
59730   return (pNew ? SQLCIPHER_OK : SQLCIPHER_NOMEM);
59731 }
59732
59733 /*
59734 ** Add a new instruction to the list of instructions current in the
59735 ** VDBE.  Return the address of the new instruction.
59736 **
59737 ** Parameters:
59738 **
59739 **    p               Pointer to the VDBE
59740 **
59741 **    op              The opcode for this instruction
59742 **
59743 **    p1, p2, p3      Operands
59744 **
59745 ** Use the sqlcipher3VdbeResolveLabel() function to fix an address and
59746 ** the sqlcipher3VdbeChangeP4() function to change the value of the P4
59747 ** operand.
59748 */
59749 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
59750   int i;
59751   VdbeOp *pOp;
59752
59753   i = p->nOp;
59754   assert( p->magic==VDBE_MAGIC_INIT );
59755   assert( op>0 && op<0xff );
59756   if( p->nOpAlloc<=i ){
59757     if( growOpArray(p) ){
59758       return 1;
59759     }
59760   }
59761   p->nOp++;
59762   pOp = &p->aOp[i];
59763   pOp->opcode = (u8)op;
59764   pOp->p5 = 0;
59765   pOp->p1 = p1;
59766   pOp->p2 = p2;
59767   pOp->p3 = p3;
59768   pOp->p4.p = 0;
59769   pOp->p4type = P4_NOTUSED;
59770 #ifdef SQLCIPHER_DEBUG
59771   pOp->zComment = 0;
59772   if( sqlcipher3VdbeAddopTrace ) sqlcipher3VdbePrintOp(0, i, &p->aOp[i]);
59773 #endif
59774 #ifdef VDBE_PROFILE
59775   pOp->cycles = 0;
59776   pOp->cnt = 0;
59777 #endif
59778   return i;
59779 }
59780 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp0(Vdbe *p, int op){
59781   return sqlcipher3VdbeAddOp3(p, op, 0, 0, 0);
59782 }
59783 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp1(Vdbe *p, int op, int p1){
59784   return sqlcipher3VdbeAddOp3(p, op, p1, 0, 0);
59785 }
59786 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
59787   return sqlcipher3VdbeAddOp3(p, op, p1, p2, 0);
59788 }
59789
59790
59791 /*
59792 ** Add an opcode that includes the p4 value as a pointer.
59793 */
59794 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4(
59795   Vdbe *p,            /* Add the opcode to this VM */
59796   int op,             /* The new opcode */
59797   int p1,             /* The P1 operand */
59798   int p2,             /* The P2 operand */
59799   int p3,             /* The P3 operand */
59800   const char *zP4,    /* The P4 operand */
59801   int p4type          /* P4 operand type */
59802 ){
59803   int addr = sqlcipher3VdbeAddOp3(p, op, p1, p2, p3);
59804   sqlcipher3VdbeChangeP4(p, addr, zP4, p4type);
59805   return addr;
59806 }
59807
59808 /*
59809 ** Add an OP_ParseSchema opcode.  This routine is broken out from
59810 ** sqlcipher3VdbeAddOp4() since it needs to also local all btrees.
59811 **
59812 ** The zWhere string must have been obtained from sqlcipher3_malloc().
59813 ** This routine will take ownership of the allocated memory.
59814 */
59815 SQLCIPHER_PRIVATE void sqlcipher3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
59816   int j;
59817   int addr = sqlcipher3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
59818   sqlcipher3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
59819   for(j=0; j<p->db->nDb; j++) sqlcipher3VdbeUsesBtree(p, j);
59820 }
59821
59822 /*
59823 ** Add an opcode that includes the p4 value as an integer.
59824 */
59825 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOp4Int(
59826   Vdbe *p,            /* Add the opcode to this VM */
59827   int op,             /* The new opcode */
59828   int p1,             /* The P1 operand */
59829   int p2,             /* The P2 operand */
59830   int p3,             /* The P3 operand */
59831   int p4              /* The P4 operand as an integer */
59832 ){
59833   int addr = sqlcipher3VdbeAddOp3(p, op, p1, p2, p3);
59834   sqlcipher3VdbeChangeP4(p, addr, SQLCIPHER_INT_TO_PTR(p4), P4_INT32);
59835   return addr;
59836 }
59837
59838 /*
59839 ** Create a new symbolic label for an instruction that has yet to be
59840 ** coded.  The symbolic label is really just a negative number.  The
59841 ** label can be used as the P2 value of an operation.  Later, when
59842 ** the label is resolved to a specific address, the VDBE will scan
59843 ** through its operation list and change all values of P2 which match
59844 ** the label into the resolved address.
59845 **
59846 ** The VDBE knows that a P2 value is a label because labels are
59847 ** always negative and P2 values are suppose to be non-negative.
59848 ** Hence, a negative P2 value is a label that has yet to be resolved.
59849 **
59850 ** Zero is returned if a malloc() fails.
59851 */
59852 SQLCIPHER_PRIVATE int sqlcipher3VdbeMakeLabel(Vdbe *p){
59853   int i;
59854   i = p->nLabel++;
59855   assert( p->magic==VDBE_MAGIC_INIT );
59856   if( i>=p->nLabelAlloc ){
59857     int n = p->nLabelAlloc*2 + 5;
59858     p->aLabel = sqlcipher3DbReallocOrFree(p->db, p->aLabel,
59859                                        n*sizeof(p->aLabel[0]));
59860     p->nLabelAlloc = sqlcipher3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
59861   }
59862   if( p->aLabel ){
59863     p->aLabel[i] = -1;
59864   }
59865   return -1-i;
59866 }
59867
59868 /*
59869 ** Resolve label "x" to be the address of the next instruction to
59870 ** be inserted.  The parameter "x" must have been obtained from
59871 ** a prior call to sqlcipher3VdbeMakeLabel().
59872 */
59873 SQLCIPHER_PRIVATE void sqlcipher3VdbeResolveLabel(Vdbe *p, int x){
59874   int j = -1-x;
59875   assert( p->magic==VDBE_MAGIC_INIT );
59876   assert( j>=0 && j<p->nLabel );
59877   if( p->aLabel ){
59878     p->aLabel[j] = p->nOp;
59879   }
59880 }
59881
59882 /*
59883 ** Mark the VDBE as one that can only be run one time.
59884 */
59885 SQLCIPHER_PRIVATE void sqlcipher3VdbeRunOnlyOnce(Vdbe *p){
59886   p->runOnlyOnce = 1;
59887 }
59888
59889 #ifdef SQLCIPHER_DEBUG /* sqlcipher3AssertMayAbort() logic */
59890
59891 /*
59892 ** The following type and function are used to iterate through all opcodes
59893 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
59894 ** invoke directly or indirectly. It should be used as follows:
59895 **
59896 **   Op *pOp;
59897 **   VdbeOpIter sIter;
59898 **
59899 **   memset(&sIter, 0, sizeof(sIter));
59900 **   sIter.v = v;                            // v is of type Vdbe* 
59901 **   while( (pOp = opIterNext(&sIter)) ){
59902 **     // Do something with pOp
59903 **   }
59904 **   sqlcipher3DbFree(v->db, sIter.apSub);
59905 ** 
59906 */
59907 typedef struct VdbeOpIter VdbeOpIter;
59908 struct VdbeOpIter {
59909   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
59910   SubProgram **apSub;        /* Array of subprograms */
59911   int nSub;                  /* Number of entries in apSub */
59912   int iAddr;                 /* Address of next instruction to return */
59913   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
59914 };
59915 static Op *opIterNext(VdbeOpIter *p){
59916   Vdbe *v = p->v;
59917   Op *pRet = 0;
59918   Op *aOp;
59919   int nOp;
59920
59921   if( p->iSub<=p->nSub ){
59922
59923     if( p->iSub==0 ){
59924       aOp = v->aOp;
59925       nOp = v->nOp;
59926     }else{
59927       aOp = p->apSub[p->iSub-1]->aOp;
59928       nOp = p->apSub[p->iSub-1]->nOp;
59929     }
59930     assert( p->iAddr<nOp );
59931
59932     pRet = &aOp[p->iAddr];
59933     p->iAddr++;
59934     if( p->iAddr==nOp ){
59935       p->iSub++;
59936       p->iAddr = 0;
59937     }
59938   
59939     if( pRet->p4type==P4_SUBPROGRAM ){
59940       int nByte = (p->nSub+1)*sizeof(SubProgram*);
59941       int j;
59942       for(j=0; j<p->nSub; j++){
59943         if( p->apSub[j]==pRet->p4.pProgram ) break;
59944       }
59945       if( j==p->nSub ){
59946         p->apSub = sqlcipher3DbReallocOrFree(v->db, p->apSub, nByte);
59947         if( !p->apSub ){
59948           pRet = 0;
59949         }else{
59950           p->apSub[p->nSub++] = pRet->p4.pProgram;
59951         }
59952       }
59953     }
59954   }
59955
59956   return pRet;
59957 }
59958
59959 /*
59960 ** Check if the program stored in the VM associated with pParse may
59961 ** throw an ABORT exception (causing the statement, but not entire transaction
59962 ** to be rolled back). This condition is true if the main program or any
59963 ** sub-programs contains any of the following:
59964 **
59965 **   *  OP_Halt with P1=SQLCIPHER_CONSTRAINT and P2=OE_Abort.
59966 **   *  OP_HaltIfNull with P1=SQLCIPHER_CONSTRAINT and P2=OE_Abort.
59967 **   *  OP_Destroy
59968 **   *  OP_VUpdate
59969 **   *  OP_VRename
59970 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
59971 **
59972 ** Then check that the value of Parse.mayAbort is true if an
59973 ** ABORT may be thrown, or false otherwise. Return true if it does
59974 ** match, or false otherwise. This function is intended to be used as
59975 ** part of an assert statement in the compiler. Similar to:
59976 **
59977 **   assert( sqlcipher3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
59978 */
59979 SQLCIPHER_PRIVATE int sqlcipher3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
59980   int hasAbort = 0;
59981   Op *pOp;
59982   VdbeOpIter sIter;
59983   memset(&sIter, 0, sizeof(sIter));
59984   sIter.v = v;
59985
59986   while( (pOp = opIterNext(&sIter))!=0 ){
59987     int opcode = pOp->opcode;
59988     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
59989 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
59990      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
59991 #endif
59992      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
59993       && (pOp->p1==SQLCIPHER_CONSTRAINT && pOp->p2==OE_Abort))
59994     ){
59995       hasAbort = 1;
59996       break;
59997     }
59998   }
59999   sqlcipher3DbFree(v->db, sIter.apSub);
60000
60001   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
60002   ** If malloc failed, then the while() loop above may not have iterated
60003   ** through all opcodes and hasAbort may be set incorrectly. Return
60004   ** true for this case to prevent the assert() in the callers frame
60005   ** from failing.  */
60006   return ( v->db->mallocFailed || hasAbort==mayAbort );
60007 }
60008 #endif /* SQLCIPHER_DEBUG - the sqlcipher3AssertMayAbort() function */
60009
60010 /*
60011 ** Loop through the program looking for P2 values that are negative
60012 ** on jump instructions.  Each such value is a label.  Resolve the
60013 ** label by setting the P2 value to its correct non-zero value.
60014 **
60015 ** This routine is called once after all opcodes have been inserted.
60016 **
60017 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
60018 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
60019 ** sqlcipher3VdbeMakeReady() to size the Vdbe.apArg[] array.
60020 **
60021 ** The Op.opflags field is set on all opcodes.
60022 */
60023 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
60024   int i;
60025   int nMaxArgs = *pMaxFuncArgs;
60026   Op *pOp;
60027   int *aLabel = p->aLabel;
60028   p->readOnly = 1;
60029   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60030     u8 opcode = pOp->opcode;
60031
60032     pOp->opflags = sqlcipher3OpcodeProperty[opcode];
60033     if( opcode==OP_Function || opcode==OP_AggStep ){
60034       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60035     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
60036       p->readOnly = 0;
60037 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
60038     }else if( opcode==OP_VUpdate ){
60039       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60040     }else if( opcode==OP_VFilter ){
60041       int n;
60042       assert( p->nOp - i >= 3 );
60043       assert( pOp[-1].opcode==OP_Integer );
60044       n = pOp[-1].p1;
60045       if( n>nMaxArgs ) nMaxArgs = n;
60046 #endif
60047     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
60048       pOp->p4.xAdvance = sqlcipher3BtreeNext;
60049       pOp->p4type = P4_ADVANCE;
60050     }else if( opcode==OP_Prev ){
60051       pOp->p4.xAdvance = sqlcipher3BtreePrevious;
60052       pOp->p4type = P4_ADVANCE;
60053     }
60054
60055     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60056       assert( -1-pOp->p2<p->nLabel );
60057       pOp->p2 = aLabel[-1-pOp->p2];
60058     }
60059   }
60060   sqlcipher3DbFree(p->db, p->aLabel);
60061   p->aLabel = 0;
60062
60063   *pMaxFuncArgs = nMaxArgs;
60064 }
60065
60066 /*
60067 ** Return the address of the next instruction to be inserted.
60068 */
60069 SQLCIPHER_PRIVATE int sqlcipher3VdbeCurrentAddr(Vdbe *p){
60070   assert( p->magic==VDBE_MAGIC_INIT );
60071   return p->nOp;
60072 }
60073
60074 /*
60075 ** This function returns a pointer to the array of opcodes associated with
60076 ** the Vdbe passed as the first argument. It is the callers responsibility
60077 ** to arrange for the returned array to be eventually freed using the 
60078 ** vdbeFreeOpArray() function.
60079 **
60080 ** Before returning, *pnOp is set to the number of entries in the returned
60081 ** array. Also, *pnMaxArg is set to the larger of its current value and 
60082 ** the number of entries in the Vdbe.apArg[] array required to execute the 
60083 ** returned program.
60084 */
60085 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60086   VdbeOp *aOp = p->aOp;
60087   assert( aOp && !p->db->mallocFailed );
60088
60089   /* Check that sqlcipher3VdbeUsesBtree() was not called on this VM */
60090   assert( p->btreeMask==0 );
60091
60092   resolveP2Values(p, pnMaxArg);
60093   *pnOp = p->nOp;
60094   p->aOp = 0;
60095   return aOp;
60096 }
60097
60098 /*
60099 ** Add a whole list of operations to the operation stack.  Return the
60100 ** address of the first operation added.
60101 */
60102 SQLCIPHER_PRIVATE int sqlcipher3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60103   int addr;
60104   assert( p->magic==VDBE_MAGIC_INIT );
60105   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60106     return 0;
60107   }
60108   addr = p->nOp;
60109   if( ALWAYS(nOp>0) ){
60110     int i;
60111     VdbeOpList const *pIn = aOp;
60112     for(i=0; i<nOp; i++, pIn++){
60113       int p2 = pIn->p2;
60114       VdbeOp *pOut = &p->aOp[i+addr];
60115       pOut->opcode = pIn->opcode;
60116       pOut->p1 = pIn->p1;
60117       if( p2<0 && (sqlcipher3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60118         pOut->p2 = addr + ADDR(p2);
60119       }else{
60120         pOut->p2 = p2;
60121       }
60122       pOut->p3 = pIn->p3;
60123       pOut->p4type = P4_NOTUSED;
60124       pOut->p4.p = 0;
60125       pOut->p5 = 0;
60126 #ifdef SQLCIPHER_DEBUG
60127       pOut->zComment = 0;
60128       if( sqlcipher3VdbeAddopTrace ){
60129         sqlcipher3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60130       }
60131 #endif
60132     }
60133     p->nOp += nOp;
60134   }
60135   return addr;
60136 }
60137
60138 /*
60139 ** Change the value of the P1 operand for a specific instruction.
60140 ** This routine is useful when a large program is loaded from a
60141 ** static array using sqlcipher3VdbeAddOpList but we want to make a
60142 ** few minor changes to the program.
60143 */
60144 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60145   assert( p!=0 );
60146   if( ((u32)p->nOp)>addr ){
60147     p->aOp[addr].p1 = val;
60148   }
60149 }
60150
60151 /*
60152 ** Change the value of the P2 operand for a specific instruction.
60153 ** This routine is useful for setting a jump destination.
60154 */
60155 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60156   assert( p!=0 );
60157   if( ((u32)p->nOp)>addr ){
60158     p->aOp[addr].p2 = val;
60159   }
60160 }
60161
60162 /*
60163 ** Change the value of the P3 operand for a specific instruction.
60164 */
60165 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60166   assert( p!=0 );
60167   if( ((u32)p->nOp)>addr ){
60168     p->aOp[addr].p3 = val;
60169   }
60170 }
60171
60172 /*
60173 ** Change the value of the P5 operand for the most recently
60174 ** added operation.
60175 */
60176 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP5(Vdbe *p, u8 val){
60177   assert( p!=0 );
60178   if( p->aOp ){
60179     assert( p->nOp>0 );
60180     p->aOp[p->nOp-1].p5 = val;
60181   }
60182 }
60183
60184 /*
60185 ** Change the P2 operand of instruction addr so that it points to
60186 ** the address of the next instruction to be coded.
60187 */
60188 SQLCIPHER_PRIVATE void sqlcipher3VdbeJumpHere(Vdbe *p, int addr){
60189   assert( addr>=0 || p->db->mallocFailed );
60190   if( addr>=0 ) sqlcipher3VdbeChangeP2(p, addr, p->nOp);
60191 }
60192
60193
60194 /*
60195 ** If the input FuncDef structure is ephemeral, then free it.  If
60196 ** the FuncDef is not ephermal, then do nothing.
60197 */
60198 static void freeEphemeralFunction(sqlcipher3 *db, FuncDef *pDef){
60199   if( ALWAYS(pDef) && (pDef->flags & SQLCIPHER_FUNC_EPHEM)!=0 ){
60200     sqlcipher3DbFree(db, pDef);
60201   }
60202 }
60203
60204 static void vdbeFreeOpArray(sqlcipher3 *, Op *, int);
60205
60206 /*
60207 ** Delete a P4 value if necessary.
60208 */
60209 static void freeP4(sqlcipher3 *db, int p4type, void *p4){
60210   if( p4 ){
60211     assert( db );
60212     switch( p4type ){
60213       case P4_REAL:
60214       case P4_INT64:
60215       case P4_DYNAMIC:
60216       case P4_KEYINFO:
60217       case P4_INTARRAY:
60218       case P4_KEYINFO_HANDOFF: {
60219         sqlcipher3DbFree(db, p4);
60220         break;
60221       }
60222       case P4_MPRINTF: {
60223         if( db->pnBytesFreed==0 ) sqlcipher3_free(p4);
60224         break;
60225       }
60226       case P4_VDBEFUNC: {
60227         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60228         freeEphemeralFunction(db, pVdbeFunc->pFunc);
60229         if( db->pnBytesFreed==0 ) sqlcipher3VdbeDeleteAuxData(pVdbeFunc, 0);
60230         sqlcipher3DbFree(db, pVdbeFunc);
60231         break;
60232       }
60233       case P4_FUNCDEF: {
60234         freeEphemeralFunction(db, (FuncDef*)p4);
60235         break;
60236       }
60237       case P4_MEM: {
60238         if( db->pnBytesFreed==0 ){
60239           sqlcipher3ValueFree((sqlcipher3_value*)p4);
60240         }else{
60241           Mem *p = (Mem*)p4;
60242           sqlcipher3DbFree(db, p->zMalloc);
60243           sqlcipher3DbFree(db, p);
60244         }
60245         break;
60246       }
60247       case P4_VTAB : {
60248         if( db->pnBytesFreed==0 ) sqlcipher3VtabUnlock((VTable *)p4);
60249         break;
60250       }
60251     }
60252   }
60253 }
60254
60255 /*
60256 ** Free the space allocated for aOp and any p4 values allocated for the
60257 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
60258 ** nOp entries. 
60259 */
60260 static void vdbeFreeOpArray(sqlcipher3 *db, Op *aOp, int nOp){
60261   if( aOp ){
60262     Op *pOp;
60263     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60264       freeP4(db, pOp->p4type, pOp->p4.p);
60265 #ifdef SQLCIPHER_DEBUG
60266       sqlcipher3DbFree(db, pOp->zComment);
60267 #endif     
60268     }
60269   }
60270   sqlcipher3DbFree(db, aOp);
60271 }
60272
60273 /*
60274 ** Link the SubProgram object passed as the second argument into the linked
60275 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60276 ** objects when the VM is no longer required.
60277 */
60278 SQLCIPHER_PRIVATE void sqlcipher3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60279   p->pNext = pVdbe->pProgram;
60280   pVdbe->pProgram = p;
60281 }
60282
60283 /*
60284 ** Change the opcode at addr into OP_Noop
60285 */
60286 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeToNoop(Vdbe *p, int addr){
60287   if( p->aOp ){
60288     VdbeOp *pOp = &p->aOp[addr];
60289     sqlcipher3 *db = p->db;
60290     freeP4(db, pOp->p4type, pOp->p4.p);
60291     memset(pOp, 0, sizeof(pOp[0]));
60292     pOp->opcode = OP_Noop;
60293   }
60294 }
60295
60296 /*
60297 ** Change the value of the P4 operand for a specific instruction.
60298 ** This routine is useful when a large program is loaded from a
60299 ** static array using sqlcipher3VdbeAddOpList but we want to make a
60300 ** few minor changes to the program.
60301 **
60302 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60303 ** the string is made into memory obtained from sqlcipher3_malloc().
60304 ** A value of n==0 means copy bytes of zP4 up to and including the
60305 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
60306 **
60307 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60308 ** A copy is made of the KeyInfo structure into memory obtained from
60309 ** sqlcipher3_malloc, to be freed when the Vdbe is finalized.
60310 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60311 ** stored in memory that the caller has obtained from sqlcipher3_malloc. The 
60312 ** caller should not free the allocation, it will be freed when the Vdbe is
60313 ** finalized.
60314 ** 
60315 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60316 ** to a string or structure that is guaranteed to exist for the lifetime of
60317 ** the Vdbe. In these cases we can just copy the pointer.
60318 **
60319 ** If addr<0 then change P4 on the most recently inserted instruction.
60320 */
60321 SQLCIPHER_PRIVATE void sqlcipher3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60322   Op *pOp;
60323   sqlcipher3 *db;
60324   assert( p!=0 );
60325   db = p->db;
60326   assert( p->magic==VDBE_MAGIC_INIT );
60327   if( p->aOp==0 || db->mallocFailed ){
60328     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60329       freeP4(db, n, (void*)*(char**)&zP4);
60330     }
60331     return;
60332   }
60333   assert( p->nOp>0 );
60334   assert( addr<p->nOp );
60335   if( addr<0 ){
60336     addr = p->nOp - 1;
60337   }
60338   pOp = &p->aOp[addr];
60339   freeP4(db, pOp->p4type, pOp->p4.p);
60340   pOp->p4.p = 0;
60341   if( n==P4_INT32 ){
60342     /* Note: this cast is safe, because the origin data point was an int
60343     ** that was cast to a (const char *). */
60344     pOp->p4.i = SQLCIPHER_PTR_TO_INT(zP4);
60345     pOp->p4type = P4_INT32;
60346   }else if( zP4==0 ){
60347     pOp->p4.p = 0;
60348     pOp->p4type = P4_NOTUSED;
60349   }else if( n==P4_KEYINFO ){
60350     KeyInfo *pKeyInfo;
60351     int nField, nByte;
60352
60353     nField = ((KeyInfo*)zP4)->nField;
60354     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60355     pKeyInfo = sqlcipher3DbMallocRaw(0, nByte);
60356     pOp->p4.pKeyInfo = pKeyInfo;
60357     if( pKeyInfo ){
60358       u8 *aSortOrder;
60359       memcpy((char*)pKeyInfo, zP4, nByte - nField);
60360       aSortOrder = pKeyInfo->aSortOrder;
60361       if( aSortOrder ){
60362         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60363         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60364       }
60365       pOp->p4type = P4_KEYINFO;
60366     }else{
60367       p->db->mallocFailed = 1;
60368       pOp->p4type = P4_NOTUSED;
60369     }
60370   }else if( n==P4_KEYINFO_HANDOFF ){
60371     pOp->p4.p = (void*)zP4;
60372     pOp->p4type = P4_KEYINFO;
60373   }else if( n==P4_VTAB ){
60374     pOp->p4.p = (void*)zP4;
60375     pOp->p4type = P4_VTAB;
60376     sqlcipher3VtabLock((VTable *)zP4);
60377     assert( ((VTable *)zP4)->db==p->db );
60378   }else if( n<0 ){
60379     pOp->p4.p = (void*)zP4;
60380     pOp->p4type = (signed char)n;
60381   }else{
60382     if( n==0 ) n = sqlcipher3Strlen30(zP4);
60383     pOp->p4.z = sqlcipher3DbStrNDup(p->db, zP4, n);
60384     pOp->p4type = P4_DYNAMIC;
60385   }
60386 }
60387
60388 #ifndef NDEBUG
60389 /*
60390 ** Change the comment on the the most recently coded instruction.  Or
60391 ** insert a No-op and add the comment to that new instruction.  This
60392 ** makes the code easier to read during debugging.  None of this happens
60393 ** in a production build.
60394 */
60395 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60396   assert( p->nOp>0 || p->aOp==0 );
60397   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60398   if( p->nOp ){
60399     assert( p->aOp );
60400     sqlcipher3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60401     p->aOp[p->nOp-1].zComment = sqlcipher3VMPrintf(p->db, zFormat, ap);
60402   }
60403 }
60404 SQLCIPHER_PRIVATE void sqlcipher3VdbeComment(Vdbe *p, const char *zFormat, ...){
60405   va_list ap;
60406   if( p ){
60407     va_start(ap, zFormat);
60408     vdbeVComment(p, zFormat, ap);
60409     va_end(ap);
60410   }
60411 }
60412 SQLCIPHER_PRIVATE void sqlcipher3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60413   va_list ap;
60414   if( p ){
60415     sqlcipher3VdbeAddOp0(p, OP_Noop);
60416     va_start(ap, zFormat);
60417     vdbeVComment(p, zFormat, ap);
60418     va_end(ap);
60419   }
60420 }
60421 #endif  /* NDEBUG */
60422
60423 /*
60424 ** Return the opcode for a given address.  If the address is -1, then
60425 ** return the most recently inserted opcode.
60426 **
60427 ** If a memory allocation error has occurred prior to the calling of this
60428 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
60429 ** is readable but not writable, though it is cast to a writable value.
60430 ** The return of a dummy opcode allows the call to continue functioning
60431 ** after a OOM fault without having to check to see if the return from 
60432 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
60433 ** dummy will never be written to.  This is verified by code inspection and
60434 ** by running with Valgrind.
60435 **
60436 ** About the #ifdef SQLCIPHER_OMIT_TRACE:  Normally, this routine is never called
60437 ** unless p->nOp>0.  This is because in the absense of SQLCIPHER_OMIT_TRACE,
60438 ** an OP_Trace instruction is always inserted by sqlcipher3VdbeGet() as soon as
60439 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
60440 ** having to double-check to make sure that the result is non-negative. But
60441 ** if SQLCIPHER_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60442 ** check the value of p->nOp-1 before continuing.
60443 */
60444 SQLCIPHER_PRIVATE VdbeOp *sqlcipher3VdbeGetOp(Vdbe *p, int addr){
60445   /* C89 specifies that the constant "dummy" will be initialized to all
60446   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
60447   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
60448   assert( p->magic==VDBE_MAGIC_INIT );
60449   if( addr<0 ){
60450 #ifdef SQLCIPHER_OMIT_TRACE
60451     if( p->nOp==0 ) return (VdbeOp*)&dummy;
60452 #endif
60453     addr = p->nOp - 1;
60454   }
60455   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60456   if( p->db->mallocFailed ){
60457     return (VdbeOp*)&dummy;
60458   }else{
60459     return &p->aOp[addr];
60460   }
60461 }
60462
60463 #if !defined(SQLCIPHER_OMIT_EXPLAIN) || !defined(NDEBUG) \
60464      || defined(VDBE_PROFILE) || defined(SQLCIPHER_DEBUG)
60465 /*
60466 ** Compute a string that describes the P4 parameter for an opcode.
60467 ** Use zTemp for any required temporary buffer space.
60468 */
60469 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60470   char *zP4 = zTemp;
60471   assert( nTemp>=20 );
60472   switch( pOp->p4type ){
60473     case P4_KEYINFO_STATIC:
60474     case P4_KEYINFO: {
60475       int i, j;
60476       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60477       sqlcipher3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60478       i = sqlcipher3Strlen30(zTemp);
60479       for(j=0; j<pKeyInfo->nField; j++){
60480         CollSeq *pColl = pKeyInfo->aColl[j];
60481         if( pColl ){
60482           int n = sqlcipher3Strlen30(pColl->zName);
60483           if( i+n>nTemp-6 ){
60484             memcpy(&zTemp[i],",...",4);
60485             break;
60486           }
60487           zTemp[i++] = ',';
60488           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
60489             zTemp[i++] = '-';
60490           }
60491           memcpy(&zTemp[i], pColl->zName,n+1);
60492           i += n;
60493         }else if( i+4<nTemp-6 ){
60494           memcpy(&zTemp[i],",nil",4);
60495           i += 4;
60496         }
60497       }
60498       zTemp[i++] = ')';
60499       zTemp[i] = 0;
60500       assert( i<nTemp );
60501       break;
60502     }
60503     case P4_COLLSEQ: {
60504       CollSeq *pColl = pOp->p4.pColl;
60505       sqlcipher3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60506       break;
60507     }
60508     case P4_FUNCDEF: {
60509       FuncDef *pDef = pOp->p4.pFunc;
60510       sqlcipher3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60511       break;
60512     }
60513     case P4_INT64: {
60514       sqlcipher3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60515       break;
60516     }
60517     case P4_INT32: {
60518       sqlcipher3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60519       break;
60520     }
60521     case P4_REAL: {
60522       sqlcipher3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60523       break;
60524     }
60525     case P4_MEM: {
60526       Mem *pMem = pOp->p4.pMem;
60527       assert( (pMem->flags & MEM_Null)==0 );
60528       if( pMem->flags & MEM_Str ){
60529         zP4 = pMem->z;
60530       }else if( pMem->flags & MEM_Int ){
60531         sqlcipher3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60532       }else if( pMem->flags & MEM_Real ){
60533         sqlcipher3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60534       }else{
60535         assert( pMem->flags & MEM_Blob );
60536         zP4 = "(blob)";
60537       }
60538       break;
60539     }
60540 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
60541     case P4_VTAB: {
60542       sqlcipher3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60543       sqlcipher3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60544       break;
60545     }
60546 #endif
60547     case P4_INTARRAY: {
60548       sqlcipher3_snprintf(nTemp, zTemp, "intarray");
60549       break;
60550     }
60551     case P4_SUBPROGRAM: {
60552       sqlcipher3_snprintf(nTemp, zTemp, "program");
60553       break;
60554     }
60555     case P4_ADVANCE: {
60556       zTemp[0] = 0;
60557       break;
60558     }
60559     default: {
60560       zP4 = pOp->p4.z;
60561       if( zP4==0 ){
60562         zP4 = zTemp;
60563         zTemp[0] = 0;
60564       }
60565     }
60566   }
60567   assert( zP4!=0 );
60568   return zP4;
60569 }
60570 #endif
60571
60572 /*
60573 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60574 **
60575 ** The prepared statements need to know in advance the complete set of
60576 ** attached databases that they will be using.  A mask of these databases
60577 ** is maintained in p->btreeMask and is used for locking and other purposes.
60578 */
60579 SQLCIPHER_PRIVATE void sqlcipher3VdbeUsesBtree(Vdbe *p, int i){
60580   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60581   assert( i<(int)sizeof(p->btreeMask)*8 );
60582   p->btreeMask |= ((yDbMask)1)<<i;
60583   if( i!=1 && sqlcipher3BtreeSharable(p->db->aDb[i].pBt) ){
60584     p->lockMask |= ((yDbMask)1)<<i;
60585   }
60586 }
60587
60588 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE>0
60589 /*
60590 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60591 ** this routine obtains the mutex associated with each BtShared structure
60592 ** that may be accessed by the VM passed as an argument. In doing so it also
60593 ** sets the BtShared.db member of each of the BtShared structures, ensuring
60594 ** that the correct busy-handler callback is invoked if required.
60595 **
60596 ** If SQLite is not threadsafe but does support shared-cache mode, then
60597 ** sqlcipher3BtreeEnter() is invoked to set the BtShared.db variables
60598 ** of all of BtShared structures accessible via the database handle 
60599 ** associated with the VM.
60600 **
60601 ** If SQLite is not threadsafe and does not support shared-cache mode, this
60602 ** function is a no-op.
60603 **
60604 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
60605 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
60606 ** corresponding to btrees that use shared cache.  Then the runtime of
60607 ** this routine is N*N.  But as N is rarely more than 1, this should not
60608 ** be a problem.
60609 */
60610 SQLCIPHER_PRIVATE void sqlcipher3VdbeEnter(Vdbe *p){
60611   int i;
60612   yDbMask mask;
60613   sqlcipher3 *db;
60614   Db *aDb;
60615   int nDb;
60616   if( p->lockMask==0 ) return;  /* The common case */
60617   db = p->db;
60618   aDb = db->aDb;
60619   nDb = db->nDb;
60620   for(i=0, mask=1; i<nDb; i++, mask += mask){
60621     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60622       sqlcipher3BtreeEnter(aDb[i].pBt);
60623     }
60624   }
60625 }
60626 #endif
60627
60628 #if !defined(SQLCIPHER_OMIT_SHARED_CACHE) && SQLCIPHER_THREADSAFE>0
60629 /*
60630 ** Unlock all of the btrees previously locked by a call to sqlcipher3VdbeEnter().
60631 */
60632 SQLCIPHER_PRIVATE void sqlcipher3VdbeLeave(Vdbe *p){
60633   int i;
60634   yDbMask mask;
60635   sqlcipher3 *db;
60636   Db *aDb;
60637   int nDb;
60638   if( p->lockMask==0 ) return;  /* The common case */
60639   db = p->db;
60640   aDb = db->aDb;
60641   nDb = db->nDb;
60642   for(i=0, mask=1; i<nDb; i++, mask += mask){
60643     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60644       sqlcipher3BtreeLeave(aDb[i].pBt);
60645     }
60646   }
60647 }
60648 #endif
60649
60650 #if defined(VDBE_PROFILE) || defined(SQLCIPHER_DEBUG)
60651 /*
60652 ** Print a single opcode.  This routine is used for debugging only.
60653 */
60654 SQLCIPHER_PRIVATE void sqlcipher3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
60655   char *zP4;
60656   char zPtr[50];
60657   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
60658   if( pOut==0 ) pOut = stdout;
60659   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
60660   fprintf(pOut, zFormat1, pc, 
60661       sqlcipher3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
60662 #ifdef SQLCIPHER_DEBUG
60663       pOp->zComment ? pOp->zComment : ""
60664 #else
60665       ""
60666 #endif
60667   );
60668   fflush(pOut);
60669 }
60670 #endif
60671
60672 /*
60673 ** Release an array of N Mem elements
60674 */
60675 static void releaseMemArray(Mem *p, int N){
60676   if( p && N ){
60677     Mem *pEnd;
60678     sqlcipher3 *db = p->db;
60679     u8 malloc_failed = db->mallocFailed;
60680     if( db->pnBytesFreed ){
60681       for(pEnd=&p[N]; p<pEnd; p++){
60682         sqlcipher3DbFree(db, p->zMalloc);
60683       }
60684       return;
60685     }
60686     for(pEnd=&p[N]; p<pEnd; p++){
60687       assert( (&p[1])==pEnd || p[0].db==p[1].db );
60688
60689       /* This block is really an inlined version of sqlcipher3VdbeMemRelease()
60690       ** that takes advantage of the fact that the memory cell value is 
60691       ** being set to NULL after releasing any dynamic resources.
60692       **
60693       ** The justification for duplicating code is that according to 
60694       ** callgrind, this causes a certain test case to hit the CPU 4.7 
60695       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
60696       ** sqlcipher3MemRelease() were called from here. With -O2, this jumps
60697       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
60698       ** with no indexes using a single prepared INSERT statement, bind() 
60699       ** and reset(). Inserts are grouped into a transaction.
60700       */
60701       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
60702         sqlcipher3VdbeMemRelease(p);
60703       }else if( p->zMalloc ){
60704         sqlcipher3DbFree(db, p->zMalloc);
60705         p->zMalloc = 0;
60706       }
60707
60708       p->flags = MEM_Null;
60709     }
60710     db->mallocFailed = malloc_failed;
60711   }
60712 }
60713
60714 /*
60715 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
60716 ** allocated by the OP_Program opcode in sqlcipher3VdbeExec().
60717 */
60718 SQLCIPHER_PRIVATE void sqlcipher3VdbeFrameDelete(VdbeFrame *p){
60719   int i;
60720   Mem *aMem = VdbeFrameMem(p);
60721   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
60722   for(i=0; i<p->nChildCsr; i++){
60723     sqlcipher3VdbeFreeCursor(p->v, apCsr[i]);
60724   }
60725   releaseMemArray(aMem, p->nChildMem);
60726   sqlcipher3DbFree(p->v->db, p);
60727 }
60728
60729 #ifndef SQLCIPHER_OMIT_EXPLAIN
60730 /*
60731 ** Give a listing of the program in the virtual machine.
60732 **
60733 ** The interface is the same as sqlcipher3VdbeExec().  But instead of
60734 ** running the code, it invokes the callback once for each instruction.
60735 ** This feature is used to implement "EXPLAIN".
60736 **
60737 ** When p->explain==1, each instruction is listed.  When
60738 ** p->explain==2, only OP_Explain instructions are listed and these
60739 ** are shown in a different format.  p->explain==2 is used to implement
60740 ** EXPLAIN QUERY PLAN.
60741 **
60742 ** When p->explain==1, first the main program is listed, then each of
60743 ** the trigger subprograms are listed one by one.
60744 */
60745 SQLCIPHER_PRIVATE int sqlcipher3VdbeList(
60746   Vdbe *p                   /* The VDBE */
60747 ){
60748   int nRow;                            /* Stop when row count reaches this */
60749   int nSub = 0;                        /* Number of sub-vdbes seen so far */
60750   SubProgram **apSub = 0;              /* Array of sub-vdbes */
60751   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
60752   sqlcipher3 *db = p->db;                 /* The database connection */
60753   int i;                               /* Loop counter */
60754   int rc = SQLCIPHER_OK;                  /* Return code */
60755   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
60756
60757   assert( p->explain );
60758   assert( p->magic==VDBE_MAGIC_RUN );
60759   assert( p->rc==SQLCIPHER_OK || p->rc==SQLCIPHER_BUSY || p->rc==SQLCIPHER_NOMEM );
60760
60761   /* Even though this opcode does not use dynamic strings for
60762   ** the result, result columns may become dynamic if the user calls
60763   ** sqlcipher3_column_text16(), causing a translation to UTF-16 encoding.
60764   */
60765   releaseMemArray(pMem, 8);
60766   p->pResultSet = 0;
60767
60768   if( p->rc==SQLCIPHER_NOMEM ){
60769     /* This happens if a malloc() inside a call to sqlcipher3_column_text() or
60770     ** sqlcipher3_column_text16() failed.  */
60771     db->mallocFailed = 1;
60772     return SQLCIPHER_ERROR;
60773   }
60774
60775   /* When the number of output rows reaches nRow, that means the
60776   ** listing has finished and sqlcipher3_step() should return SQLCIPHER_DONE.
60777   ** nRow is the sum of the number of rows in the main program, plus
60778   ** the sum of the number of rows in all trigger subprograms encountered
60779   ** so far.  The nRow value will increase as new trigger subprograms are
60780   ** encountered, but p->pc will eventually catch up to nRow.
60781   */
60782   nRow = p->nOp;
60783   if( p->explain==1 ){
60784     /* The first 8 memory cells are used for the result set.  So we will
60785     ** commandeer the 9th cell to use as storage for an array of pointers
60786     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
60787     ** cells.  */
60788     assert( p->nMem>9 );
60789     pSub = &p->aMem[9];
60790     if( pSub->flags&MEM_Blob ){
60791       /* On the first call to sqlcipher3_step(), pSub will hold a NULL.  It is
60792       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
60793       nSub = pSub->n/sizeof(Vdbe*);
60794       apSub = (SubProgram **)pSub->z;
60795     }
60796     for(i=0; i<nSub; i++){
60797       nRow += apSub[i]->nOp;
60798     }
60799   }
60800
60801   do{
60802     i = p->pc++;
60803   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
60804   if( i>=nRow ){
60805     p->rc = SQLCIPHER_OK;
60806     rc = SQLCIPHER_DONE;
60807   }else if( db->u1.isInterrupted ){
60808     p->rc = SQLCIPHER_INTERRUPT;
60809     rc = SQLCIPHER_ERROR;
60810     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3ErrStr(p->rc));
60811   }else{
60812     char *z;
60813     Op *pOp;
60814     if( i<p->nOp ){
60815       /* The output line number is small enough that we are still in the
60816       ** main program. */
60817       pOp = &p->aOp[i];
60818     }else{
60819       /* We are currently listing subprograms.  Figure out which one and
60820       ** pick up the appropriate opcode. */
60821       int j;
60822       i -= p->nOp;
60823       for(j=0; i>=apSub[j]->nOp; j++){
60824         i -= apSub[j]->nOp;
60825       }
60826       pOp = &apSub[j]->aOp[i];
60827     }
60828     if( p->explain==1 ){
60829       pMem->flags = MEM_Int;
60830       pMem->type = SQLCIPHER_INTEGER;
60831       pMem->u.i = i;                                /* Program counter */
60832       pMem++;
60833   
60834       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
60835       pMem->z = (char*)sqlcipher3OpcodeName(pOp->opcode);  /* Opcode */
60836       assert( pMem->z!=0 );
60837       pMem->n = sqlcipher3Strlen30(pMem->z);
60838       pMem->type = SQLCIPHER_TEXT;
60839       pMem->enc = SQLCIPHER_UTF8;
60840       pMem++;
60841
60842       /* When an OP_Program opcode is encounter (the only opcode that has
60843       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
60844       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
60845       ** has not already been seen.
60846       */
60847       if( pOp->p4type==P4_SUBPROGRAM ){
60848         int nByte = (nSub+1)*sizeof(SubProgram*);
60849         int j;
60850         for(j=0; j<nSub; j++){
60851           if( apSub[j]==pOp->p4.pProgram ) break;
60852         }
60853         if( j==nSub && SQLCIPHER_OK==sqlcipher3VdbeMemGrow(pSub, nByte, 1) ){
60854           apSub = (SubProgram **)pSub->z;
60855           apSub[nSub++] = pOp->p4.pProgram;
60856           pSub->flags |= MEM_Blob;
60857           pSub->n = nSub*sizeof(SubProgram*);
60858         }
60859       }
60860     }
60861
60862     pMem->flags = MEM_Int;
60863     pMem->u.i = pOp->p1;                          /* P1 */
60864     pMem->type = SQLCIPHER_INTEGER;
60865     pMem++;
60866
60867     pMem->flags = MEM_Int;
60868     pMem->u.i = pOp->p2;                          /* P2 */
60869     pMem->type = SQLCIPHER_INTEGER;
60870     pMem++;
60871
60872     pMem->flags = MEM_Int;
60873     pMem->u.i = pOp->p3;                          /* P3 */
60874     pMem->type = SQLCIPHER_INTEGER;
60875     pMem++;
60876
60877     if( sqlcipher3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
60878       assert( p->db->mallocFailed );
60879       return SQLCIPHER_ERROR;
60880     }
60881     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60882     z = displayP4(pOp, pMem->z, 32);
60883     if( z!=pMem->z ){
60884       sqlcipher3VdbeMemSetStr(pMem, z, -1, SQLCIPHER_UTF8, 0);
60885     }else{
60886       assert( pMem->z!=0 );
60887       pMem->n = sqlcipher3Strlen30(pMem->z);
60888       pMem->enc = SQLCIPHER_UTF8;
60889     }
60890     pMem->type = SQLCIPHER_TEXT;
60891     pMem++;
60892
60893     if( p->explain==1 ){
60894       if( sqlcipher3VdbeMemGrow(pMem, 4, 0) ){
60895         assert( p->db->mallocFailed );
60896         return SQLCIPHER_ERROR;
60897       }
60898       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60899       pMem->n = 2;
60900       sqlcipher3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
60901       pMem->type = SQLCIPHER_TEXT;
60902       pMem->enc = SQLCIPHER_UTF8;
60903       pMem++;
60904   
60905 #ifdef SQLCIPHER_DEBUG
60906       if( pOp->zComment ){
60907         pMem->flags = MEM_Str|MEM_Term;
60908         pMem->z = pOp->zComment;
60909         pMem->n = sqlcipher3Strlen30(pMem->z);
60910         pMem->enc = SQLCIPHER_UTF8;
60911         pMem->type = SQLCIPHER_TEXT;
60912       }else
60913 #endif
60914       {
60915         pMem->flags = MEM_Null;                       /* Comment */
60916         pMem->type = SQLCIPHER_NULL;
60917       }
60918     }
60919
60920     p->nResColumn = 8 - 4*(p->explain-1);
60921     p->pResultSet = &p->aMem[1];
60922     p->rc = SQLCIPHER_OK;
60923     rc = SQLCIPHER_ROW;
60924   }
60925   return rc;
60926 }
60927 #endif /* SQLCIPHER_OMIT_EXPLAIN */
60928
60929 #ifdef SQLCIPHER_DEBUG
60930 /*
60931 ** Print the SQL that was used to generate a VDBE program.
60932 */
60933 SQLCIPHER_PRIVATE void sqlcipher3VdbePrintSql(Vdbe *p){
60934   int nOp = p->nOp;
60935   VdbeOp *pOp;
60936   if( nOp<1 ) return;
60937   pOp = &p->aOp[0];
60938   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60939     const char *z = pOp->p4.z;
60940     while( sqlcipher3Isspace(*z) ) z++;
60941     printf("SQL: [%s]\n", z);
60942   }
60943 }
60944 #endif
60945
60946 #if !defined(SQLCIPHER_OMIT_TRACE) && defined(SQLCIPHER_ENABLE_IOTRACE)
60947 /*
60948 ** Print an IOTRACE message showing SQL content.
60949 */
60950 SQLCIPHER_PRIVATE void sqlcipher3VdbeIOTraceSql(Vdbe *p){
60951   int nOp = p->nOp;
60952   VdbeOp *pOp;
60953   if( sqlcipher3IoTrace==0 ) return;
60954   if( nOp<1 ) return;
60955   pOp = &p->aOp[0];
60956   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60957     int i, j;
60958     char z[1000];
60959     sqlcipher3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
60960     for(i=0; sqlcipher3Isspace(z[i]); i++){}
60961     for(j=0; z[i]; i++){
60962       if( sqlcipher3Isspace(z[i]) ){
60963         if( z[i-1]!=' ' ){
60964           z[j++] = ' ';
60965         }
60966       }else{
60967         z[j++] = z[i];
60968       }
60969     }
60970     z[j] = 0;
60971     sqlcipher3IoTrace("SQL %s\n", z);
60972   }
60973 }
60974 #endif /* !SQLCIPHER_OMIT_TRACE && SQLCIPHER_ENABLE_IOTRACE */
60975
60976 /*
60977 ** Allocate space from a fixed size buffer and return a pointer to
60978 ** that space.  If insufficient space is available, return NULL.
60979 **
60980 ** The pBuf parameter is the initial value of a pointer which will
60981 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
60982 ** NULL, it means that memory space has already been allocated and that
60983 ** this routine should not allocate any new memory.  When pBuf is not
60984 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
60985 ** is NULL.
60986 **
60987 ** nByte is the number of bytes of space needed.
60988 **
60989 ** *ppFrom points to available space and pEnd points to the end of the
60990 ** available space.  When space is allocated, *ppFrom is advanced past
60991 ** the end of the allocated space.
60992 **
60993 ** *pnByte is a counter of the number of bytes of space that have failed
60994 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
60995 ** request, then increment *pnByte by the amount of the request.
60996 */
60997 static void *allocSpace(
60998   void *pBuf,          /* Where return pointer will be stored */
60999   int nByte,           /* Number of bytes to allocate */
61000   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
61001   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
61002   int *pnByte          /* If allocation cannot be made, increment *pnByte */
61003 ){
61004   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
61005   if( pBuf ) return pBuf;
61006   nByte = ROUND8(nByte);
61007   if( &(*ppFrom)[nByte] <= pEnd ){
61008     pBuf = (void*)*ppFrom;
61009     *ppFrom += nByte;
61010   }else{
61011     *pnByte += nByte;
61012   }
61013   return pBuf;
61014 }
61015
61016 /*
61017 ** Rewind the VDBE back to the beginning in preparation for
61018 ** running it.
61019 */
61020 SQLCIPHER_PRIVATE void sqlcipher3VdbeRewind(Vdbe *p){
61021 #if defined(SQLCIPHER_DEBUG) || defined(VDBE_PROFILE)
61022   int i;
61023 #endif
61024   assert( p!=0 );
61025   assert( p->magic==VDBE_MAGIC_INIT );
61026
61027   /* There should be at least one opcode.
61028   */
61029   assert( p->nOp>0 );
61030
61031   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61032   p->magic = VDBE_MAGIC_RUN;
61033
61034 #ifdef SQLCIPHER_DEBUG
61035   for(i=1; i<p->nMem; i++){
61036     assert( p->aMem[i].db==p->db );
61037   }
61038 #endif
61039   p->pc = -1;
61040   p->rc = SQLCIPHER_OK;
61041   p->errorAction = OE_Abort;
61042   p->magic = VDBE_MAGIC_RUN;
61043   p->nChange = 0;
61044   p->cacheCtr = 1;
61045   p->minWriteFileFormat = 255;
61046   p->iStatement = 0;
61047   p->nFkConstraint = 0;
61048 #ifdef VDBE_PROFILE
61049   for(i=0; i<p->nOp; i++){
61050     p->aOp[i].cnt = 0;
61051     p->aOp[i].cycles = 0;
61052   }
61053 #endif
61054 }
61055
61056 /*
61057 ** Prepare a virtual machine for execution for the first time after
61058 ** creating the virtual machine.  This involves things such
61059 ** as allocating stack space and initializing the program counter.
61060 ** After the VDBE has be prepped, it can be executed by one or more
61061 ** calls to sqlcipher3VdbeExec().  
61062 **
61063 ** This function may be called exact once on a each virtual machine.
61064 ** After this routine is called the VM has been "packaged" and is ready
61065 ** to run.  After this routine is called, futher calls to 
61066 ** sqlcipher3VdbeAddOp() functions are prohibited.  This routine disconnects
61067 ** the Vdbe from the Parse object that helped generate it so that the
61068 ** the Vdbe becomes an independent entity and the Parse object can be
61069 ** destroyed.
61070 **
61071 ** Use the sqlcipher3VdbeRewind() procedure to restore a virtual machine back
61072 ** to its initial state after it has been run.
61073 */
61074 SQLCIPHER_PRIVATE void sqlcipher3VdbeMakeReady(
61075   Vdbe *p,                       /* The VDBE */
61076   Parse *pParse                  /* Parsing context */
61077 ){
61078   sqlcipher3 *db;                   /* The database connection */
61079   int nVar;                      /* Number of parameters */
61080   int nMem;                      /* Number of VM memory registers */
61081   int nCursor;                   /* Number of cursors required */
61082   int nArg;                      /* Number of arguments in subprograms */
61083   int n;                         /* Loop counter */
61084   u8 *zCsr;                      /* Memory available for allocation */
61085   u8 *zEnd;                      /* First byte past allocated memory */
61086   int nByte;                     /* How much extra memory is needed */
61087
61088   assert( p!=0 );
61089   assert( p->nOp>0 );
61090   assert( pParse!=0 );
61091   assert( p->magic==VDBE_MAGIC_INIT );
61092   db = p->db;
61093   assert( db->mallocFailed==0 );
61094   nVar = pParse->nVar;
61095   nMem = pParse->nMem;
61096   nCursor = pParse->nTab;
61097   nArg = pParse->nMaxArg;
61098   
61099   /* For each cursor required, also allocate a memory cell. Memory
61100   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61101   ** the vdbe program. Instead they are used to allocate space for
61102   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
61103   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61104   ** stores the blob of memory associated with cursor 1, etc.
61105   **
61106   ** See also: allocateCursor().
61107   */
61108   nMem += nCursor;
61109
61110   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
61111   ** an array to marshal SQL function arguments in.
61112   */
61113   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61114   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61115
61116   resolveP2Values(p, &nArg);
61117   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61118   if( pParse->explain && nMem<10 ){
61119     nMem = 10;
61120   }
61121   memset(zCsr, 0, zEnd-zCsr);
61122   zCsr += (zCsr - (u8*)0)&7;
61123   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61124   p->expired = 0;
61125
61126   /* Memory for registers, parameters, cursor, etc, is allocated in two
61127   ** passes.  On the first pass, we try to reuse unused space at the 
61128   ** end of the opcode array.  If we are unable to satisfy all memory
61129   ** requirements by reusing the opcode array tail, then the second
61130   ** pass will fill in the rest using a fresh allocation.  
61131   **
61132   ** This two-pass approach that reuses as much memory as possible from
61133   ** the leftover space at the end of the opcode array can significantly
61134   ** reduce the amount of memory held by a prepared statement.
61135   */
61136   do {
61137     nByte = 0;
61138     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61139     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61140     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61141     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61142     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61143                           &zCsr, zEnd, &nByte);
61144     if( nByte ){
61145       p->pFree = sqlcipher3DbMallocZero(db, nByte);
61146     }
61147     zCsr = p->pFree;
61148     zEnd = &zCsr[nByte];
61149   }while( nByte && !db->mallocFailed );
61150
61151   p->nCursor = (u16)nCursor;
61152   if( p->aVar ){
61153     p->nVar = (ynVar)nVar;
61154     for(n=0; n<nVar; n++){
61155       p->aVar[n].flags = MEM_Null;
61156       p->aVar[n].db = db;
61157     }
61158   }
61159   if( p->azVar ){
61160     p->nzVar = pParse->nzVar;
61161     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61162     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61163   }
61164   if( p->aMem ){
61165     p->aMem--;                      /* aMem[] goes from 1..nMem */
61166     p->nMem = nMem;                 /*       not from 0..nMem-1 */
61167     for(n=1; n<=nMem; n++){
61168       p->aMem[n].flags = MEM_Null;
61169       p->aMem[n].db = db;
61170     }
61171   }
61172   p->explain = pParse->explain;
61173   sqlcipher3VdbeRewind(p);
61174 }
61175
61176 /*
61177 ** Close a VDBE cursor and release all the resources that cursor 
61178 ** happens to hold.
61179 */
61180 SQLCIPHER_PRIVATE void sqlcipher3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61181   if( pCx==0 ){
61182     return;
61183   }
61184   sqlcipher3VdbeSorterClose(p->db, pCx);
61185   if( pCx->pBt ){
61186     sqlcipher3BtreeClose(pCx->pBt);
61187     /* The pCx->pCursor will be close automatically, if it exists, by
61188     ** the call above. */
61189   }else if( pCx->pCursor ){
61190     sqlcipher3BtreeCloseCursor(pCx->pCursor);
61191   }
61192 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
61193   if( pCx->pVtabCursor ){
61194     sqlcipher3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61195     const sqlcipher3_module *pModule = pCx->pModule;
61196     p->inVtabMethod = 1;
61197     pModule->xClose(pVtabCursor);
61198     p->inVtabMethod = 0;
61199   }
61200 #endif
61201 }
61202
61203 /*
61204 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61205 ** is used, for example, when a trigger sub-program is halted to restore
61206 ** control to the main program.
61207 */
61208 SQLCIPHER_PRIVATE int sqlcipher3VdbeFrameRestore(VdbeFrame *pFrame){
61209   Vdbe *v = pFrame->v;
61210   v->aOp = pFrame->aOp;
61211   v->nOp = pFrame->nOp;
61212   v->aMem = pFrame->aMem;
61213   v->nMem = pFrame->nMem;
61214   v->apCsr = pFrame->apCsr;
61215   v->nCursor = pFrame->nCursor;
61216   v->db->lastRowid = pFrame->lastRowid;
61217   v->nChange = pFrame->nChange;
61218   return pFrame->pc;
61219 }
61220
61221 /*
61222 ** Close all cursors.
61223 **
61224 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
61225 ** cell array. This is necessary as the memory cell array may contain
61226 ** pointers to VdbeFrame objects, which may in turn contain pointers to
61227 ** open cursors.
61228 */
61229 static void closeAllCursors(Vdbe *p){
61230   if( p->pFrame ){
61231     VdbeFrame *pFrame;
61232     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61233     sqlcipher3VdbeFrameRestore(pFrame);
61234   }
61235   p->pFrame = 0;
61236   p->nFrame = 0;
61237
61238   if( p->apCsr ){
61239     int i;
61240     for(i=0; i<p->nCursor; i++){
61241       VdbeCursor *pC = p->apCsr[i];
61242       if( pC ){
61243         sqlcipher3VdbeFreeCursor(p, pC);
61244         p->apCsr[i] = 0;
61245       }
61246     }
61247   }
61248   if( p->aMem ){
61249     releaseMemArray(&p->aMem[1], p->nMem);
61250   }
61251   while( p->pDelFrame ){
61252     VdbeFrame *pDel = p->pDelFrame;
61253     p->pDelFrame = pDel->pParent;
61254     sqlcipher3VdbeFrameDelete(pDel);
61255   }
61256 }
61257
61258 /*
61259 ** Clean up the VM after execution.
61260 **
61261 ** This routine will automatically close any cursors, lists, and/or
61262 ** sorters that were left open.  It also deletes the values of
61263 ** variables in the aVar[] array.
61264 */
61265 static void Cleanup(Vdbe *p){
61266   sqlcipher3 *db = p->db;
61267
61268 #ifdef SQLCIPHER_DEBUG
61269   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
61270   ** Vdbe.aMem[] arrays have already been cleaned up.  */
61271   int i;
61272   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
61273   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
61274 #endif
61275
61276   sqlcipher3DbFree(db, p->zErrMsg);
61277   p->zErrMsg = 0;
61278   p->pResultSet = 0;
61279 }
61280
61281 /*
61282 ** Set the number of result columns that will be returned by this SQL
61283 ** statement. This is now set at compile time, rather than during
61284 ** execution of the vdbe program so that sqlcipher3_column_count() can
61285 ** be called on an SQL statement before sqlcipher3_step().
61286 */
61287 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetNumCols(Vdbe *p, int nResColumn){
61288   Mem *pColName;
61289   int n;
61290   sqlcipher3 *db = p->db;
61291
61292   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61293   sqlcipher3DbFree(db, p->aColName);
61294   n = nResColumn*COLNAME_N;
61295   p->nResColumn = (u16)nResColumn;
61296   p->aColName = pColName = (Mem*)sqlcipher3DbMallocZero(db, sizeof(Mem)*n );
61297   if( p->aColName==0 ) return;
61298   while( n-- > 0 ){
61299     pColName->flags = MEM_Null;
61300     pColName->db = p->db;
61301     pColName++;
61302   }
61303 }
61304
61305 /*
61306 ** Set the name of the idx'th column to be returned by the SQL statement.
61307 ** zName must be a pointer to a nul terminated string.
61308 **
61309 ** This call must be made after a call to sqlcipher3VdbeSetNumCols().
61310 **
61311 ** The final parameter, xDel, must be one of SQLCIPHER_DYNAMIC, SQLCIPHER_STATIC
61312 ** or SQLCIPHER_TRANSIENT. If it is SQLCIPHER_DYNAMIC, then the buffer pointed
61313 ** to by zName will be freed by sqlcipher3DbFree() when the vdbe is destroyed.
61314 */
61315 SQLCIPHER_PRIVATE int sqlcipher3VdbeSetColName(
61316   Vdbe *p,                         /* Vdbe being configured */
61317   int idx,                         /* Index of column zName applies to */
61318   int var,                         /* One of the COLNAME_* constants */
61319   const char *zName,               /* Pointer to buffer containing name */
61320   void (*xDel)(void*)              /* Memory management strategy for zName */
61321 ){
61322   int rc;
61323   Mem *pColName;
61324   assert( idx<p->nResColumn );
61325   assert( var<COLNAME_N );
61326   if( p->db->mallocFailed ){
61327     assert( !zName || xDel!=SQLCIPHER_DYNAMIC );
61328     return SQLCIPHER_NOMEM;
61329   }
61330   assert( p->aColName!=0 );
61331   pColName = &(p->aColName[idx+var*p->nResColumn]);
61332   rc = sqlcipher3VdbeMemSetStr(pColName, zName, -1, SQLCIPHER_UTF8, xDel);
61333   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61334   return rc;
61335 }
61336
61337 /*
61338 ** A read or write transaction may or may not be active on database handle
61339 ** db. If a transaction is active, commit it. If there is a
61340 ** write-transaction spanning more than one database file, this routine
61341 ** takes care of the master journal trickery.
61342 */
61343 static int vdbeCommit(sqlcipher3 *db, Vdbe *p){
61344   int i;
61345   int nTrans = 0;  /* Number of databases with an active write-transaction */
61346   int rc = SQLCIPHER_OK;
61347   int needXcommit = 0;
61348
61349 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
61350   /* With this option, sqlcipher3VtabSync() is defined to be simply 
61351   ** SQLCIPHER_OK so p is not used. 
61352   */
61353   UNUSED_PARAMETER(p);
61354 #endif
61355
61356   /* Before doing anything else, call the xSync() callback for any
61357   ** virtual module tables written in this transaction. This has to
61358   ** be done before determining whether a master journal file is 
61359   ** required, as an xSync() callback may add an attached database
61360   ** to the transaction.
61361   */
61362   rc = sqlcipher3VtabSync(db, &p->zErrMsg);
61363
61364   /* This loop determines (a) if the commit hook should be invoked and
61365   ** (b) how many database files have open write transactions, not 
61366   ** including the temp database. (b) is important because if more than 
61367   ** one database file has an open write transaction, a master journal
61368   ** file is required for an atomic commit.
61369   */ 
61370   for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){ 
61371     Btree *pBt = db->aDb[i].pBt;
61372     if( sqlcipher3BtreeIsInTrans(pBt) ){
61373       needXcommit = 1;
61374       if( i!=1 ) nTrans++;
61375       rc = sqlcipher3PagerExclusiveLock(sqlcipher3BtreePager(pBt));
61376     }
61377   }
61378   if( rc!=SQLCIPHER_OK ){
61379     return rc;
61380   }
61381
61382   /* If there are any write-transactions at all, invoke the commit hook */
61383   if( needXcommit && db->xCommitCallback ){
61384     rc = db->xCommitCallback(db->pCommitArg);
61385     if( rc ){
61386       return SQLCIPHER_CONSTRAINT;
61387     }
61388   }
61389
61390   /* The simple case - no more than one database file (not counting the
61391   ** TEMP database) has a transaction active.   There is no need for the
61392   ** master-journal.
61393   **
61394   ** If the return value of sqlcipher3BtreeGetFilename() is a zero length
61395   ** string, it means the main database is :memory: or a temp file.  In 
61396   ** that case we do not support atomic multi-file commits, so use the 
61397   ** simple case then too.
61398   */
61399   if( 0==sqlcipher3Strlen30(sqlcipher3BtreeGetFilename(db->aDb[0].pBt))
61400    || nTrans<=1
61401   ){
61402     for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){
61403       Btree *pBt = db->aDb[i].pBt;
61404       if( pBt ){
61405         rc = sqlcipher3BtreeCommitPhaseOne(pBt, 0);
61406       }
61407     }
61408
61409     /* Do the commit only if all databases successfully complete phase 1. 
61410     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61411     ** IO error while deleting or truncating a journal file. It is unlikely,
61412     ** but could happen. In this case abandon processing and return the error.
61413     */
61414     for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){
61415       Btree *pBt = db->aDb[i].pBt;
61416       if( pBt ){
61417         rc = sqlcipher3BtreeCommitPhaseTwo(pBt, 0);
61418       }
61419     }
61420     if( rc==SQLCIPHER_OK ){
61421       sqlcipher3VtabCommit(db);
61422     }
61423   }
61424
61425   /* The complex case - There is a multi-file write-transaction active.
61426   ** This requires a master journal file to ensure the transaction is
61427   ** committed atomicly.
61428   */
61429 #ifndef SQLCIPHER_OMIT_DISKIO
61430   else{
61431     sqlcipher3_vfs *pVfs = db->pVfs;
61432     int needSync = 0;
61433     char *zMaster = 0;   /* File-name for the master journal */
61434     char const *zMainFile = sqlcipher3BtreeGetFilename(db->aDb[0].pBt);
61435     sqlcipher3_file *pMaster = 0;
61436     i64 offset = 0;
61437     int res;
61438
61439     /* Select a master journal file name */
61440     do {
61441       u32 iRandom;
61442       sqlcipher3DbFree(db, zMaster);
61443       sqlcipher3_randomness(sizeof(iRandom), &iRandom);
61444       zMaster = sqlcipher3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
61445       if( !zMaster ){
61446         return SQLCIPHER_NOMEM;
61447       }
61448       sqlcipher3FileSuffix3(zMainFile, zMaster);
61449       rc = sqlcipher3OsAccess(pVfs, zMaster, SQLCIPHER_ACCESS_EXISTS, &res);
61450     }while( rc==SQLCIPHER_OK && res );
61451     if( rc==SQLCIPHER_OK ){
61452       /* Open the master journal. */
61453       rc = sqlcipher3OsOpenMalloc(pVfs, zMaster, &pMaster, 
61454           SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE|
61455           SQLCIPHER_OPEN_EXCLUSIVE|SQLCIPHER_OPEN_MASTER_JOURNAL, 0
61456       );
61457     }
61458     if( rc!=SQLCIPHER_OK ){
61459       sqlcipher3DbFree(db, zMaster);
61460       return rc;
61461     }
61462  
61463     /* Write the name of each database file in the transaction into the new
61464     ** master journal file. If an error occurs at this point close
61465     ** and delete the master journal file. All the individual journal files
61466     ** still have 'null' as the master journal pointer, so they will roll
61467     ** back independently if a failure occurs.
61468     */
61469     for(i=0; i<db->nDb; i++){
61470       Btree *pBt = db->aDb[i].pBt;
61471       if( sqlcipher3BtreeIsInTrans(pBt) ){
61472         char const *zFile = sqlcipher3BtreeGetJournalname(pBt);
61473         if( zFile==0 ){
61474           continue;  /* Ignore TEMP and :memory: databases */
61475         }
61476         assert( zFile[0]!=0 );
61477         if( !needSync && !sqlcipher3BtreeSyncDisabled(pBt) ){
61478           needSync = 1;
61479         }
61480         rc = sqlcipher3OsWrite(pMaster, zFile, sqlcipher3Strlen30(zFile)+1, offset);
61481         offset += sqlcipher3Strlen30(zFile)+1;
61482         if( rc!=SQLCIPHER_OK ){
61483           sqlcipher3OsCloseFree(pMaster);
61484           sqlcipher3OsDelete(pVfs, zMaster, 0);
61485           sqlcipher3DbFree(db, zMaster);
61486           return rc;
61487         }
61488       }
61489     }
61490
61491     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61492     ** flag is set this is not required.
61493     */
61494     if( needSync 
61495      && 0==(sqlcipher3OsDeviceCharacteristics(pMaster)&SQLCIPHER_IOCAP_SEQUENTIAL)
61496      && SQLCIPHER_OK!=(rc = sqlcipher3OsSync(pMaster, SQLCIPHER_SYNC_NORMAL))
61497     ){
61498       sqlcipher3OsCloseFree(pMaster);
61499       sqlcipher3OsDelete(pVfs, zMaster, 0);
61500       sqlcipher3DbFree(db, zMaster);
61501       return rc;
61502     }
61503
61504     /* Sync all the db files involved in the transaction. The same call
61505     ** sets the master journal pointer in each individual journal. If
61506     ** an error occurs here, do not delete the master journal file.
61507     **
61508     ** If the error occurs during the first call to
61509     ** sqlcipher3BtreeCommitPhaseOne(), then there is a chance that the
61510     ** master journal file will be orphaned. But we cannot delete it,
61511     ** in case the master journal file name was written into the journal
61512     ** file before the failure occurred.
61513     */
61514     for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){ 
61515       Btree *pBt = db->aDb[i].pBt;
61516       if( pBt ){
61517         rc = sqlcipher3BtreeCommitPhaseOne(pBt, zMaster);
61518       }
61519     }
61520     sqlcipher3OsCloseFree(pMaster);
61521     assert( rc!=SQLCIPHER_BUSY );
61522     if( rc!=SQLCIPHER_OK ){
61523       sqlcipher3DbFree(db, zMaster);
61524       return rc;
61525     }
61526
61527     /* Delete the master journal file. This commits the transaction. After
61528     ** doing this the directory is synced again before any individual
61529     ** transaction files are deleted.
61530     */
61531     rc = sqlcipher3OsDelete(pVfs, zMaster, 1);
61532     sqlcipher3DbFree(db, zMaster);
61533     zMaster = 0;
61534     if( rc ){
61535       return rc;
61536     }
61537
61538     /* All files and directories have already been synced, so the following
61539     ** calls to sqlcipher3BtreeCommitPhaseTwo() are only closing files and
61540     ** deleting or truncating journals. If something goes wrong while
61541     ** this is happening we don't really care. The integrity of the
61542     ** transaction is already guaranteed, but some stray 'cold' journals
61543     ** may be lying around. Returning an error code won't help matters.
61544     */
61545     disable_simulated_io_errors();
61546     sqlcipher3BeginBenignMalloc();
61547     for(i=0; i<db->nDb; i++){ 
61548       Btree *pBt = db->aDb[i].pBt;
61549       if( pBt ){
61550         sqlcipher3BtreeCommitPhaseTwo(pBt, 1);
61551       }
61552     }
61553     sqlcipher3EndBenignMalloc();
61554     enable_simulated_io_errors();
61555
61556     sqlcipher3VtabCommit(db);
61557   }
61558 #endif
61559
61560   return rc;
61561 }
61562
61563 /* 
61564 ** This routine checks that the sqlcipher3.activeVdbeCnt count variable
61565 ** matches the number of vdbe's in the list sqlcipher3.pVdbe that are
61566 ** currently active. An assertion fails if the two counts do not match.
61567 ** This is an internal self-check only - it is not an essential processing
61568 ** step.
61569 **
61570 ** This is a no-op if NDEBUG is defined.
61571 */
61572 #ifndef NDEBUG
61573 static void checkActiveVdbeCnt(sqlcipher3 *db){
61574   Vdbe *p;
61575   int cnt = 0;
61576   int nWrite = 0;
61577   p = db->pVdbe;
61578   while( p ){
61579     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
61580       cnt++;
61581       if( p->readOnly==0 ) nWrite++;
61582     }
61583     p = p->pNext;
61584   }
61585   assert( cnt==db->activeVdbeCnt );
61586   assert( nWrite==db->writeVdbeCnt );
61587 }
61588 #else
61589 #define checkActiveVdbeCnt(x)
61590 #endif
61591
61592 /*
61593 ** For every Btree that in database connection db which 
61594 ** has been modified, "trip" or invalidate each cursor in
61595 ** that Btree might have been modified so that the cursor
61596 ** can never be used again.  This happens when a rollback
61597 *** occurs.  We have to trip all the other cursors, even
61598 ** cursor from other VMs in different database connections,
61599 ** so that none of them try to use the data at which they
61600 ** were pointing and which now may have been changed due
61601 ** to the rollback.
61602 **
61603 ** Remember that a rollback can delete tables complete and
61604 ** reorder rootpages.  So it is not sufficient just to save
61605 ** the state of the cursor.  We have to invalidate the cursor
61606 ** so that it is never used again.
61607 */
61608 static void invalidateCursorsOnModifiedBtrees(sqlcipher3 *db){
61609   int i;
61610   for(i=0; i<db->nDb; i++){
61611     Btree *p = db->aDb[i].pBt;
61612     if( p && sqlcipher3BtreeIsInTrans(p) ){
61613       sqlcipher3BtreeTripAllCursors(p, SQLCIPHER_ABORT);
61614     }
61615   }
61616 }
61617
61618 /*
61619 ** If the Vdbe passed as the first argument opened a statement-transaction,
61620 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61621 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61622 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
61623 ** statement transaction is commtted.
61624 **
61625 ** If an IO error occurs, an SQLCIPHER_IOERR_XXX error code is returned. 
61626 ** Otherwise SQLCIPHER_OK.
61627 */
61628 SQLCIPHER_PRIVATE int sqlcipher3VdbeCloseStatement(Vdbe *p, int eOp){
61629   sqlcipher3 *const db = p->db;
61630   int rc = SQLCIPHER_OK;
61631
61632   /* If p->iStatement is greater than zero, then this Vdbe opened a 
61633   ** statement transaction that should be closed here. The only exception
61634   ** is that an IO error may have occured, causing an emergency rollback.
61635   ** In this case (db->nStatement==0), and there is nothing to do.
61636   */
61637   if( db->nStatement && p->iStatement ){
61638     int i;
61639     const int iSavepoint = p->iStatement-1;
61640
61641     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
61642     assert( db->nStatement>0 );
61643     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
61644
61645     for(i=0; i<db->nDb; i++){ 
61646       int rc2 = SQLCIPHER_OK;
61647       Btree *pBt = db->aDb[i].pBt;
61648       if( pBt ){
61649         if( eOp==SAVEPOINT_ROLLBACK ){
61650           rc2 = sqlcipher3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
61651         }
61652         if( rc2==SQLCIPHER_OK ){
61653           rc2 = sqlcipher3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
61654         }
61655         if( rc==SQLCIPHER_OK ){
61656           rc = rc2;
61657         }
61658       }
61659     }
61660     db->nStatement--;
61661     p->iStatement = 0;
61662
61663     if( rc==SQLCIPHER_OK ){
61664       if( eOp==SAVEPOINT_ROLLBACK ){
61665         rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
61666       }
61667       if( rc==SQLCIPHER_OK ){
61668         rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
61669       }
61670     }
61671
61672     /* If the statement transaction is being rolled back, also restore the 
61673     ** database handles deferred constraint counter to the value it had when 
61674     ** the statement transaction was opened.  */
61675     if( eOp==SAVEPOINT_ROLLBACK ){
61676       db->nDeferredCons = p->nStmtDefCons;
61677     }
61678   }
61679   return rc;
61680 }
61681
61682 /*
61683 ** This function is called when a transaction opened by the database 
61684 ** handle associated with the VM passed as an argument is about to be 
61685 ** committed. If there are outstanding deferred foreign key constraint
61686 ** violations, return SQLCIPHER_ERROR. Otherwise, SQLCIPHER_OK.
61687 **
61688 ** If there are outstanding FK violations and this function returns 
61689 ** SQLCIPHER_ERROR, set the result of the VM to SQLCIPHER_CONSTRAINT and write
61690 ** an error message to it. Then return SQLCIPHER_ERROR.
61691 */
61692 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
61693 SQLCIPHER_PRIVATE int sqlcipher3VdbeCheckFk(Vdbe *p, int deferred){
61694   sqlcipher3 *db = p->db;
61695   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
61696     p->rc = SQLCIPHER_CONSTRAINT;
61697     p->errorAction = OE_Abort;
61698     sqlcipher3SetString(&p->zErrMsg, db, "foreign key constraint failed");
61699     return SQLCIPHER_ERROR;
61700   }
61701   return SQLCIPHER_OK;
61702 }
61703 #endif
61704
61705 /*
61706 ** This routine is called the when a VDBE tries to halt.  If the VDBE
61707 ** has made changes and is in autocommit mode, then commit those
61708 ** changes.  If a rollback is needed, then do the rollback.
61709 **
61710 ** This routine is the only way to move the state of a VM from
61711 ** SQLCIPHER_MAGIC_RUN to SQLCIPHER_MAGIC_HALT.  It is harmless to
61712 ** call this on a VM that is in the SQLCIPHER_MAGIC_HALT state.
61713 **
61714 ** Return an error code.  If the commit could not complete because of
61715 ** lock contention, return SQLCIPHER_BUSY.  If SQLCIPHER_BUSY is returned, it
61716 ** means the close did not happen and needs to be repeated.
61717 */
61718 SQLCIPHER_PRIVATE int sqlcipher3VdbeHalt(Vdbe *p){
61719   int rc;                         /* Used to store transient return codes */
61720   sqlcipher3 *db = p->db;
61721
61722   /* This function contains the logic that determines if a statement or
61723   ** transaction will be committed or rolled back as a result of the
61724   ** execution of this virtual machine. 
61725   **
61726   ** If any of the following errors occur:
61727   **
61728   **     SQLCIPHER_NOMEM
61729   **     SQLCIPHER_IOERR
61730   **     SQLCIPHER_FULL
61731   **     SQLCIPHER_INTERRUPT
61732   **
61733   ** Then the internal cache might have been left in an inconsistent
61734   ** state.  We need to rollback the statement transaction, if there is
61735   ** one, or the complete transaction if there is no statement transaction.
61736   */
61737
61738   if( p->db->mallocFailed ){
61739     p->rc = SQLCIPHER_NOMEM;
61740   }
61741   closeAllCursors(p);
61742   if( p->magic!=VDBE_MAGIC_RUN ){
61743     return SQLCIPHER_OK;
61744   }
61745   checkActiveVdbeCnt(db);
61746
61747   /* No commit or rollback needed if the program never started */
61748   if( p->pc>=0 ){
61749     int mrc;   /* Primary error code from p->rc */
61750     int eStatementOp = 0;
61751     int isSpecialError;            /* Set to true if a 'special' error */
61752
61753     /* Lock all btrees used by the statement */
61754     sqlcipher3VdbeEnter(p);
61755
61756     /* Check for one of the special errors */
61757     mrc = p->rc & 0xff;
61758     assert( p->rc!=SQLCIPHER_IOERR_BLOCKED );  /* This error no longer exists */
61759     isSpecialError = mrc==SQLCIPHER_NOMEM || mrc==SQLCIPHER_IOERR
61760                      || mrc==SQLCIPHER_INTERRUPT || mrc==SQLCIPHER_FULL;
61761     if( isSpecialError ){
61762       /* If the query was read-only and the error code is SQLCIPHER_INTERRUPT, 
61763       ** no rollback is necessary. Otherwise, at least a savepoint 
61764       ** transaction must be rolled back to restore the database to a 
61765       ** consistent state.
61766       **
61767       ** Even if the statement is read-only, it is important to perform
61768       ** a statement or transaction rollback operation. If the error 
61769       ** occured while writing to the journal, sub-journal or database
61770       ** file as part of an effort to free up cache space (see function
61771       ** pagerStress() in pager.c), the rollback is required to restore 
61772       ** the pager to a consistent state.
61773       */
61774       if( !p->readOnly || mrc!=SQLCIPHER_INTERRUPT ){
61775         if( (mrc==SQLCIPHER_NOMEM || mrc==SQLCIPHER_FULL) && p->usesStmtJournal ){
61776           eStatementOp = SAVEPOINT_ROLLBACK;
61777         }else{
61778           /* We are forced to roll back the active transaction. Before doing
61779           ** so, abort any other statements this handle currently has active.
61780           */
61781           invalidateCursorsOnModifiedBtrees(db);
61782           sqlcipher3RollbackAll(db);
61783           sqlcipher3CloseSavepoints(db);
61784           db->autoCommit = 1;
61785         }
61786       }
61787     }
61788
61789     /* Check for immediate foreign key violations. */
61790     if( p->rc==SQLCIPHER_OK ){
61791       sqlcipher3VdbeCheckFk(p, 0);
61792     }
61793   
61794     /* If the auto-commit flag is set and this is the only active writer 
61795     ** VM, then we do either a commit or rollback of the current transaction. 
61796     **
61797     ** Note: This block also runs if one of the special errors handled 
61798     ** above has occurred. 
61799     */
61800     if( !sqlcipher3VtabInSync(db) 
61801      && db->autoCommit 
61802      && db->writeVdbeCnt==(p->readOnly==0) 
61803     ){
61804       if( p->rc==SQLCIPHER_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
61805         rc = sqlcipher3VdbeCheckFk(p, 1);
61806         if( rc!=SQLCIPHER_OK ){
61807           if( NEVER(p->readOnly) ){
61808             sqlcipher3VdbeLeave(p);
61809             return SQLCIPHER_ERROR;
61810           }
61811           rc = SQLCIPHER_CONSTRAINT;
61812         }else{ 
61813           /* The auto-commit flag is true, the vdbe program was successful 
61814           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
61815           ** key constraints to hold up the transaction. This means a commit 
61816           ** is required. */
61817           rc = vdbeCommit(db, p);
61818         }
61819         if( rc==SQLCIPHER_BUSY && p->readOnly ){
61820           sqlcipher3VdbeLeave(p);
61821           return SQLCIPHER_BUSY;
61822         }else if( rc!=SQLCIPHER_OK ){
61823           p->rc = rc;
61824           sqlcipher3RollbackAll(db);
61825         }else{
61826           db->nDeferredCons = 0;
61827           sqlcipher3CommitInternalChanges(db);
61828         }
61829       }else{
61830         sqlcipher3RollbackAll(db);
61831       }
61832       db->nStatement = 0;
61833     }else if( eStatementOp==0 ){
61834       if( p->rc==SQLCIPHER_OK || p->errorAction==OE_Fail ){
61835         eStatementOp = SAVEPOINT_RELEASE;
61836       }else if( p->errorAction==OE_Abort ){
61837         eStatementOp = SAVEPOINT_ROLLBACK;
61838       }else{
61839         invalidateCursorsOnModifiedBtrees(db);
61840         sqlcipher3RollbackAll(db);
61841         sqlcipher3CloseSavepoints(db);
61842         db->autoCommit = 1;
61843       }
61844     }
61845   
61846     /* If eStatementOp is non-zero, then a statement transaction needs to
61847     ** be committed or rolled back. Call sqlcipher3VdbeCloseStatement() to
61848     ** do so. If this operation returns an error, and the current statement
61849     ** error code is SQLCIPHER_OK or SQLCIPHER_CONSTRAINT, then promote the
61850     ** current statement error code.
61851     */
61852     if( eStatementOp ){
61853       rc = sqlcipher3VdbeCloseStatement(p, eStatementOp);
61854       if( rc ){
61855         if( p->rc==SQLCIPHER_OK || p->rc==SQLCIPHER_CONSTRAINT ){
61856           p->rc = rc;
61857           sqlcipher3DbFree(db, p->zErrMsg);
61858           p->zErrMsg = 0;
61859         }
61860         invalidateCursorsOnModifiedBtrees(db);
61861         sqlcipher3RollbackAll(db);
61862         sqlcipher3CloseSavepoints(db);
61863         db->autoCommit = 1;
61864       }
61865     }
61866   
61867     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
61868     ** has been rolled back, update the database connection change-counter. 
61869     */
61870     if( p->changeCntOn ){
61871       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
61872         sqlcipher3VdbeSetChanges(db, p->nChange);
61873       }else{
61874         sqlcipher3VdbeSetChanges(db, 0);
61875       }
61876       p->nChange = 0;
61877     }
61878   
61879     /* Rollback or commit any schema changes that occurred. */
61880     if( p->rc!=SQLCIPHER_OK && db->flags&SQLCIPHER_InternChanges ){
61881       sqlcipher3ResetInternalSchema(db, -1);
61882       db->flags = (db->flags | SQLCIPHER_InternChanges);
61883     }
61884
61885     /* Release the locks */
61886     sqlcipher3VdbeLeave(p);
61887   }
61888
61889   /* We have successfully halted and closed the VM.  Record this fact. */
61890   if( p->pc>=0 ){
61891     db->activeVdbeCnt--;
61892     if( !p->readOnly ){
61893       db->writeVdbeCnt--;
61894     }
61895     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
61896   }
61897   p->magic = VDBE_MAGIC_HALT;
61898   checkActiveVdbeCnt(db);
61899   if( p->db->mallocFailed ){
61900     p->rc = SQLCIPHER_NOMEM;
61901   }
61902
61903   /* If the auto-commit flag is set to true, then any locks that were held
61904   ** by connection db have now been released. Call sqlcipher3ConnectionUnlocked() 
61905   ** to invoke any required unlock-notify callbacks.
61906   */
61907   if( db->autoCommit ){
61908     sqlcipher3ConnectionUnlocked(db);
61909   }
61910
61911   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
61912   return (p->rc==SQLCIPHER_BUSY ? SQLCIPHER_BUSY : SQLCIPHER_OK);
61913 }
61914
61915
61916 /*
61917 ** Each VDBE holds the result of the most recent sqlcipher3_step() call
61918 ** in p->rc.  This routine sets that result back to SQLCIPHER_OK.
61919 */
61920 SQLCIPHER_PRIVATE void sqlcipher3VdbeResetStepResult(Vdbe *p){
61921   p->rc = SQLCIPHER_OK;
61922 }
61923
61924 /*
61925 ** Copy the error code and error message belonging to the VDBE passed
61926 ** as the first argument to its database handle (so that they will be 
61927 ** returned by calls to sqlcipher3_errcode() and sqlcipher3_errmsg()).
61928 **
61929 ** This function does not clear the VDBE error code or message, just
61930 ** copies them to the database handle.
61931 */
61932 SQLCIPHER_PRIVATE int sqlcipher3VdbeTransferError(Vdbe *p){
61933   sqlcipher3 *db = p->db;
61934   int rc = p->rc;
61935   if( p->zErrMsg ){
61936     u8 mallocFailed = db->mallocFailed;
61937     sqlcipher3BeginBenignMalloc();
61938     sqlcipher3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLCIPHER_UTF8, SQLCIPHER_TRANSIENT);
61939     sqlcipher3EndBenignMalloc();
61940     db->mallocFailed = mallocFailed;
61941     db->errCode = rc;
61942   }else{
61943     sqlcipher3Error(db, rc, 0);
61944   }
61945   return rc;
61946 }
61947
61948 /*
61949 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
61950 ** Write any error messages into *pzErrMsg.  Return the result code.
61951 **
61952 ** After this routine is run, the VDBE should be ready to be executed
61953 ** again.
61954 **
61955 ** To look at it another way, this routine resets the state of the
61956 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
61957 ** VDBE_MAGIC_INIT.
61958 */
61959 SQLCIPHER_PRIVATE int sqlcipher3VdbeReset(Vdbe *p){
61960   sqlcipher3 *db;
61961   db = p->db;
61962
61963   /* If the VM did not run to completion or if it encountered an
61964   ** error, then it might not have been halted properly.  So halt
61965   ** it now.
61966   */
61967   sqlcipher3VdbeHalt(p);
61968
61969   /* If the VDBE has be run even partially, then transfer the error code
61970   ** and error message from the VDBE into the main database structure.  But
61971   ** if the VDBE has just been set to run but has not actually executed any
61972   ** instructions yet, leave the main database error information unchanged.
61973   */
61974   if( p->pc>=0 ){
61975     sqlcipher3VdbeTransferError(p);
61976     sqlcipher3DbFree(db, p->zErrMsg);
61977     p->zErrMsg = 0;
61978     if( p->runOnlyOnce ) p->expired = 1;
61979   }else if( p->rc && p->expired ){
61980     /* The expired flag was set on the VDBE before the first call
61981     ** to sqlcipher3_step(). For consistency (since sqlcipher3_step() was
61982     ** called), set the database error in this case as well.
61983     */
61984     sqlcipher3Error(db, p->rc, 0);
61985     sqlcipher3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLCIPHER_UTF8, SQLCIPHER_TRANSIENT);
61986     sqlcipher3DbFree(db, p->zErrMsg);
61987     p->zErrMsg = 0;
61988   }
61989
61990   /* Reclaim all memory used by the VDBE
61991   */
61992   Cleanup(p);
61993
61994   /* Save profiling information from this VDBE run.
61995   */
61996 #ifdef VDBE_PROFILE
61997   {
61998     FILE *out = fopen("vdbe_profile.out", "a");
61999     if( out ){
62000       int i;
62001       fprintf(out, "---- ");
62002       for(i=0; i<p->nOp; i++){
62003         fprintf(out, "%02x", p->aOp[i].opcode);
62004       }
62005       fprintf(out, "\n");
62006       for(i=0; i<p->nOp; i++){
62007         fprintf(out, "%6d %10lld %8lld ",
62008            p->aOp[i].cnt,
62009            p->aOp[i].cycles,
62010            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
62011         );
62012         sqlcipher3VdbePrintOp(out, i, &p->aOp[i]);
62013       }
62014       fclose(out);
62015     }
62016   }
62017 #endif
62018   p->magic = VDBE_MAGIC_INIT;
62019   return p->rc & db->errMask;
62020 }
62021  
62022 /*
62023 ** Clean up and delete a VDBE after execution.  Return an integer which is
62024 ** the result code.  Write any error message text into *pzErrMsg.
62025 */
62026 SQLCIPHER_PRIVATE int sqlcipher3VdbeFinalize(Vdbe *p){
62027   int rc = SQLCIPHER_OK;
62028   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
62029     rc = sqlcipher3VdbeReset(p);
62030     assert( (rc & p->db->errMask)==rc );
62031   }
62032   sqlcipher3VdbeDelete(p);
62033   return rc;
62034 }
62035
62036 /*
62037 ** Call the destructor for each auxdata entry in pVdbeFunc for which
62038 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
62039 ** are always destroyed.  To destroy all auxdata entries, call this
62040 ** routine with mask==0.
62041 */
62042 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
62043   int i;
62044   for(i=0; i<pVdbeFunc->nAux; i++){
62045     struct AuxData *pAux = &pVdbeFunc->apAux[i];
62046     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
62047       if( pAux->xDelete ){
62048         pAux->xDelete(pAux->pAux);
62049       }
62050       pAux->pAux = 0;
62051     }
62052   }
62053 }
62054
62055 /*
62056 ** Free all memory associated with the Vdbe passed as the second argument.
62057 ** The difference between this function and sqlcipher3VdbeDelete() is that
62058 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62059 ** the database connection.
62060 */
62061 SQLCIPHER_PRIVATE void sqlcipher3VdbeDeleteObject(sqlcipher3 *db, Vdbe *p){
62062   SubProgram *pSub, *pNext;
62063   int i;
62064   assert( p->db==0 || p->db==db );
62065   releaseMemArray(p->aVar, p->nVar);
62066   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62067   for(pSub=p->pProgram; pSub; pSub=pNext){
62068     pNext = pSub->pNext;
62069     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62070     sqlcipher3DbFree(db, pSub);
62071   }
62072   for(i=p->nzVar-1; i>=0; i--) sqlcipher3DbFree(db, p->azVar[i]);
62073   vdbeFreeOpArray(db, p->aOp, p->nOp);
62074   sqlcipher3DbFree(db, p->aLabel);
62075   sqlcipher3DbFree(db, p->aColName);
62076   sqlcipher3DbFree(db, p->zSql);
62077   sqlcipher3DbFree(db, p->pFree);
62078   sqlcipher3DbFree(db, p);
62079 }
62080
62081 /*
62082 ** Delete an entire VDBE.
62083 */
62084 SQLCIPHER_PRIVATE void sqlcipher3VdbeDelete(Vdbe *p){
62085   sqlcipher3 *db;
62086
62087   if( NEVER(p==0) ) return;
62088   db = p->db;
62089   if( p->pPrev ){
62090     p->pPrev->pNext = p->pNext;
62091   }else{
62092     assert( db->pVdbe==p );
62093     db->pVdbe = p->pNext;
62094   }
62095   if( p->pNext ){
62096     p->pNext->pPrev = p->pPrev;
62097   }
62098   p->magic = VDBE_MAGIC_DEAD;
62099   p->db = 0;
62100   sqlcipher3VdbeDeleteObject(db, p);
62101 }
62102
62103 /*
62104 ** Make sure the cursor p is ready to read or write the row to which it
62105 ** was last positioned.  Return an error code if an OOM fault or I/O error
62106 ** prevents us from positioning the cursor to its correct position.
62107 **
62108 ** If a MoveTo operation is pending on the given cursor, then do that
62109 ** MoveTo now.  If no move is pending, check to see if the row has been
62110 ** deleted out from under the cursor and if it has, mark the row as
62111 ** a NULL row.
62112 **
62113 ** If the cursor is already pointing to the correct row and that row has
62114 ** not been deleted out from under the cursor, then this routine is a no-op.
62115 */
62116 SQLCIPHER_PRIVATE int sqlcipher3VdbeCursorMoveto(VdbeCursor *p){
62117   if( p->deferredMoveto ){
62118     int res, rc;
62119 #ifdef SQLCIPHER_TEST
62120     extern int sqlcipher3_search_count;
62121 #endif
62122     assert( p->isTable );
62123     rc = sqlcipher3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62124     if( rc ) return rc;
62125     p->lastRowid = p->movetoTarget;
62126     if( res!=0 ) return SQLCIPHER_CORRUPT_BKPT;
62127     p->rowidIsValid = 1;
62128 #ifdef SQLCIPHER_TEST
62129     sqlcipher3_search_count++;
62130 #endif
62131     p->deferredMoveto = 0;
62132     p->cacheStatus = CACHE_STALE;
62133   }else if( ALWAYS(p->pCursor) ){
62134     int hasMoved;
62135     int rc = sqlcipher3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62136     if( rc ) return rc;
62137     if( hasMoved ){
62138       p->cacheStatus = CACHE_STALE;
62139       p->nullRow = 1;
62140     }
62141   }
62142   return SQLCIPHER_OK;
62143 }
62144
62145 /*
62146 ** The following functions:
62147 **
62148 ** sqlcipher3VdbeSerialType()
62149 ** sqlcipher3VdbeSerialTypeLen()
62150 ** sqlcipher3VdbeSerialLen()
62151 ** sqlcipher3VdbeSerialPut()
62152 ** sqlcipher3VdbeSerialGet()
62153 **
62154 ** encapsulate the code that serializes values for storage in SQLite
62155 ** data and index records. Each serialized value consists of a
62156 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62157 ** integer, stored as a varint.
62158 **
62159 ** In an SQLite index record, the serial type is stored directly before
62160 ** the blob of data that it corresponds to. In a table record, all serial
62161 ** types are stored at the start of the record, and the blobs of data at
62162 ** the end. Hence these functions allow the caller to handle the
62163 ** serial-type and data blob seperately.
62164 **
62165 ** The following table describes the various storage classes for data:
62166 **
62167 **   serial type        bytes of data      type
62168 **   --------------     ---------------    ---------------
62169 **      0                     0            NULL
62170 **      1                     1            signed integer
62171 **      2                     2            signed integer
62172 **      3                     3            signed integer
62173 **      4                     4            signed integer
62174 **      5                     6            signed integer
62175 **      6                     8            signed integer
62176 **      7                     8            IEEE float
62177 **      8                     0            Integer constant 0
62178 **      9                     0            Integer constant 1
62179 **     10,11                               reserved for expansion
62180 **    N>=12 and even       (N-12)/2        BLOB
62181 **    N>=13 and odd        (N-13)/2        text
62182 **
62183 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62184 ** of SQLite will not understand those serial types.
62185 */
62186
62187 /*
62188 ** Return the serial-type for the value stored in pMem.
62189 */
62190 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialType(Mem *pMem, int file_format){
62191   int flags = pMem->flags;
62192   int n;
62193
62194   if( flags&MEM_Null ){
62195     return 0;
62196   }
62197   if( flags&MEM_Int ){
62198     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62199 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62200     i64 i = pMem->u.i;
62201     u64 u;
62202     if( file_format>=4 && (i&1)==i ){
62203       return 8+(u32)i;
62204     }
62205     if( i<0 ){
62206       if( i<(-MAX_6BYTE) ) return 6;
62207       /* Previous test prevents:  u = -(-9223372036854775808) */
62208       u = -i;
62209     }else{
62210       u = i;
62211     }
62212     if( u<=127 ) return 1;
62213     if( u<=32767 ) return 2;
62214     if( u<=8388607 ) return 3;
62215     if( u<=2147483647 ) return 4;
62216     if( u<=MAX_6BYTE ) return 5;
62217     return 6;
62218   }
62219   if( flags&MEM_Real ){
62220     return 7;
62221   }
62222   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62223   n = pMem->n;
62224   if( flags & MEM_Zero ){
62225     n += pMem->u.nZero;
62226   }
62227   assert( n>=0 );
62228   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62229 }
62230
62231 /*
62232 ** Return the length of the data corresponding to the supplied serial-type.
62233 */
62234 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialTypeLen(u32 serial_type){
62235   if( serial_type>=12 ){
62236     return (serial_type-12)/2;
62237   }else{
62238     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62239     return aSize[serial_type];
62240   }
62241 }
62242
62243 /*
62244 ** If we are on an architecture with mixed-endian floating 
62245 ** points (ex: ARM7) then swap the lower 4 bytes with the 
62246 ** upper 4 bytes.  Return the result.
62247 **
62248 ** For most architectures, this is a no-op.
62249 **
62250 ** (later):  It is reported to me that the mixed-endian problem
62251 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62252 ** that early versions of GCC stored the two words of a 64-bit
62253 ** float in the wrong order.  And that error has been propagated
62254 ** ever since.  The blame is not necessarily with GCC, though.
62255 ** GCC might have just copying the problem from a prior compiler.
62256 ** I am also told that newer versions of GCC that follow a different
62257 ** ABI get the byte order right.
62258 **
62259 ** Developers using SQLite on an ARM7 should compile and run their
62260 ** application using -DSQLCIPHER_DEBUG=1 at least once.  With DEBUG
62261 ** enabled, some asserts below will ensure that the byte order of
62262 ** floating point values is correct.
62263 **
62264 ** (2007-08-30)  Frank van Vugt has studied this problem closely
62265 ** and has send his findings to the SQLite developers.  Frank
62266 ** writes that some Linux kernels offer floating point hardware
62267 ** emulation that uses only 32-bit mantissas instead of a full 
62268 ** 48-bits as required by the IEEE standard.  (This is the
62269 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62270 ** byte swapping becomes very complicated.  To avoid problems,
62271 ** the necessary byte swapping is carried out using a 64-bit integer
62272 ** rather than a 64-bit float.  Frank assures us that the code here
62273 ** works for him.  We, the developers, have no way to independently
62274 ** verify this, but Frank seems to know what he is talking about
62275 ** so we trust him.
62276 */
62277 #ifdef SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT
62278 static u64 floatSwap(u64 in){
62279   union {
62280     u64 r;
62281     u32 i[2];
62282   } u;
62283   u32 t;
62284
62285   u.r = in;
62286   t = u.i[0];
62287   u.i[0] = u.i[1];
62288   u.i[1] = t;
62289   return u.r;
62290 }
62291 # define swapMixedEndianFloat(X)  X = floatSwap(X)
62292 #else
62293 # define swapMixedEndianFloat(X)
62294 #endif
62295
62296 /*
62297 ** Write the serialized data blob for the value stored in pMem into 
62298 ** buf. It is assumed that the caller has allocated sufficient space.
62299 ** Return the number of bytes written.
62300 **
62301 ** nBuf is the amount of space left in buf[].  nBuf must always be
62302 ** large enough to hold the entire field.  Except, if the field is
62303 ** a blob with a zero-filled tail, then buf[] might be just the right
62304 ** size to hold everything except for the zero-filled tail.  If buf[]
62305 ** is only big enough to hold the non-zero prefix, then only write that
62306 ** prefix into buf[].  But if buf[] is large enough to hold both the
62307 ** prefix and the tail then write the prefix and set the tail to all
62308 ** zeros.
62309 **
62310 ** Return the number of bytes actually written into buf[].  The number
62311 ** of bytes in the zero-filled tail is included in the return value only
62312 ** if those bytes were zeroed in buf[].
62313 */ 
62314 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62315   u32 serial_type = sqlcipher3VdbeSerialType(pMem, file_format);
62316   u32 len;
62317
62318   /* Integer and Real */
62319   if( serial_type<=7 && serial_type>0 ){
62320     u64 v;
62321     u32 i;
62322     if( serial_type==7 ){
62323       assert( sizeof(v)==sizeof(pMem->r) );
62324       memcpy(&v, &pMem->r, sizeof(v));
62325       swapMixedEndianFloat(v);
62326     }else{
62327       v = pMem->u.i;
62328     }
62329     len = i = sqlcipher3VdbeSerialTypeLen(serial_type);
62330     assert( len<=(u32)nBuf );
62331     while( i-- ){
62332       buf[i] = (u8)(v&0xFF);
62333       v >>= 8;
62334     }
62335     return len;
62336   }
62337
62338   /* String or blob */
62339   if( serial_type>=12 ){
62340     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62341              == (int)sqlcipher3VdbeSerialTypeLen(serial_type) );
62342     assert( pMem->n<=nBuf );
62343     len = pMem->n;
62344     memcpy(buf, pMem->z, len);
62345     if( pMem->flags & MEM_Zero ){
62346       len += pMem->u.nZero;
62347       assert( nBuf>=0 );
62348       if( len > (u32)nBuf ){
62349         len = (u32)nBuf;
62350       }
62351       memset(&buf[pMem->n], 0, len-pMem->n);
62352     }
62353     return len;
62354   }
62355
62356   /* NULL or constants 0 or 1 */
62357   return 0;
62358 }
62359
62360 /*
62361 ** Deserialize the data blob pointed to by buf as serial type serial_type
62362 ** and store the result in pMem.  Return the number of bytes read.
62363 */ 
62364 SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialGet(
62365   const unsigned char *buf,     /* Buffer to deserialize from */
62366   u32 serial_type,              /* Serial type to deserialize */
62367   Mem *pMem                     /* Memory cell to write value into */
62368 ){
62369   switch( serial_type ){
62370     case 10:   /* Reserved for future use */
62371     case 11:   /* Reserved for future use */
62372     case 0: {  /* NULL */
62373       pMem->flags = MEM_Null;
62374       break;
62375     }
62376     case 1: { /* 1-byte signed integer */
62377       pMem->u.i = (signed char)buf[0];
62378       pMem->flags = MEM_Int;
62379       return 1;
62380     }
62381     case 2: { /* 2-byte signed integer */
62382       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62383       pMem->flags = MEM_Int;
62384       return 2;
62385     }
62386     case 3: { /* 3-byte signed integer */
62387       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62388       pMem->flags = MEM_Int;
62389       return 3;
62390     }
62391     case 4: { /* 4-byte signed integer */
62392       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62393       pMem->flags = MEM_Int;
62394       return 4;
62395     }
62396     case 5: { /* 6-byte signed integer */
62397       u64 x = (((signed char)buf[0])<<8) | buf[1];
62398       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62399       x = (x<<32) | y;
62400       pMem->u.i = *(i64*)&x;
62401       pMem->flags = MEM_Int;
62402       return 6;
62403     }
62404     case 6:   /* 8-byte signed integer */
62405     case 7: { /* IEEE floating point */
62406       u64 x;
62407       u32 y;
62408 #if !defined(NDEBUG) && !defined(SQLCIPHER_OMIT_FLOATING_POINT)
62409       /* Verify that integers and floating point values use the same
62410       ** byte order.  Or, that if SQLCIPHER_MIXED_ENDIAN_64BIT_FLOAT is
62411       ** defined that 64-bit floating point values really are mixed
62412       ** endian.
62413       */
62414       static const u64 t1 = ((u64)0x3ff00000)<<32;
62415       static const double r1 = 1.0;
62416       u64 t2 = t1;
62417       swapMixedEndianFloat(t2);
62418       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62419 #endif
62420
62421       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62422       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62423       x = (x<<32) | y;
62424       if( serial_type==6 ){
62425         pMem->u.i = *(i64*)&x;
62426         pMem->flags = MEM_Int;
62427       }else{
62428         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62429         swapMixedEndianFloat(x);
62430         memcpy(&pMem->r, &x, sizeof(x));
62431         pMem->flags = sqlcipher3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62432       }
62433       return 8;
62434     }
62435     case 8:    /* Integer 0 */
62436     case 9: {  /* Integer 1 */
62437       pMem->u.i = serial_type-8;
62438       pMem->flags = MEM_Int;
62439       return 0;
62440     }
62441     default: {
62442       u32 len = (serial_type-12)/2;
62443       pMem->z = (char *)buf;
62444       pMem->n = len;
62445       pMem->xDel = 0;
62446       if( serial_type&0x01 ){
62447         pMem->flags = MEM_Str | MEM_Ephem;
62448       }else{
62449         pMem->flags = MEM_Blob | MEM_Ephem;
62450       }
62451       return len;
62452     }
62453   }
62454   return 0;
62455 }
62456
62457 /*
62458 ** This routine is used to allocate sufficient space for an UnpackedRecord
62459 ** structure large enough to be used with sqlcipher3VdbeRecordUnpack() if
62460 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
62461 **
62462 ** The space is either allocated using sqlcipher3DbMallocRaw() or from within
62463 ** the unaligned buffer passed via the second and third arguments (presumably
62464 ** stack space). If the former, then *ppFree is set to a pointer that should
62465 ** be eventually freed by the caller using sqlcipher3DbFree(). Or, if the 
62466 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62467 ** before returning.
62468 **
62469 ** If an OOM error occurs, NULL is returned.
62470 */
62471 SQLCIPHER_PRIVATE UnpackedRecord *sqlcipher3VdbeAllocUnpackedRecord(
62472   KeyInfo *pKeyInfo,              /* Description of the record */
62473   char *pSpace,                   /* Unaligned space available */
62474   int szSpace,                    /* Size of pSpace[] in bytes */
62475   char **ppFree                   /* OUT: Caller should free this pointer */
62476 ){
62477   UnpackedRecord *p;              /* Unpacked record to return */
62478   int nOff;                       /* Increment pSpace by nOff to align it */
62479   int nByte;                      /* Number of bytes required for *p */
62480
62481   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62482   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
62483   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
62484   */
62485   nOff = (8 - (SQLCIPHER_PTR_TO_INT(pSpace) & 7)) & 7;
62486   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62487   if( nByte>szSpace+nOff ){
62488     p = (UnpackedRecord *)sqlcipher3DbMallocRaw(pKeyInfo->db, nByte);
62489     *ppFree = (char *)p;
62490     if( !p ) return 0;
62491   }else{
62492     p = (UnpackedRecord*)&pSpace[nOff];
62493     *ppFree = 0;
62494   }
62495
62496   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62497   p->pKeyInfo = pKeyInfo;
62498   p->nField = pKeyInfo->nField + 1;
62499   return p;
62500 }
62501
62502 /*
62503 ** Given the nKey-byte encoding of a record in pKey[], populate the 
62504 ** UnpackedRecord structure indicated by the fourth argument with the
62505 ** contents of the decoded record.
62506 */ 
62507 SQLCIPHER_PRIVATE void sqlcipher3VdbeRecordUnpack(
62508   KeyInfo *pKeyInfo,     /* Information about the record format */
62509   int nKey,              /* Size of the binary record */
62510   const void *pKey,      /* The binary record */
62511   UnpackedRecord *p      /* Populate this structure before returning. */
62512 ){
62513   const unsigned char *aKey = (const unsigned char *)pKey;
62514   int d; 
62515   u32 idx;                        /* Offset in aKey[] to read from */
62516   u16 u;                          /* Unsigned loop counter */
62517   u32 szHdr;
62518   Mem *pMem = p->aMem;
62519
62520   p->flags = 0;
62521   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62522   idx = getVarint32(aKey, szHdr);
62523   d = szHdr;
62524   u = 0;
62525   while( idx<szHdr && u<p->nField && d<=nKey ){
62526     u32 serial_type;
62527
62528     idx += getVarint32(&aKey[idx], serial_type);
62529     pMem->enc = pKeyInfo->enc;
62530     pMem->db = pKeyInfo->db;
62531     /* pMem->flags = 0; // sqlcipher3VdbeSerialGet() will set this for us */
62532     pMem->zMalloc = 0;
62533     d += sqlcipher3VdbeSerialGet(&aKey[d], serial_type, pMem);
62534     pMem++;
62535     u++;
62536   }
62537   assert( u<=pKeyInfo->nField + 1 );
62538   p->nField = u;
62539 }
62540
62541 /*
62542 ** This function compares the two table rows or index records
62543 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
62544 ** or positive integer if key1 is less than, equal to or 
62545 ** greater than key2.  The {nKey1, pKey1} key must be a blob
62546 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
62547 ** key must be a parsed key such as obtained from
62548 ** sqlcipher3VdbeParseRecord.
62549 **
62550 ** Key1 and Key2 do not have to contain the same number of fields.
62551 ** The key with fewer fields is usually compares less than the 
62552 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
62553 ** and the common prefixes are equal, then key1 is less than key2.
62554 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62555 ** equal, then the keys are considered to be equal and
62556 ** the parts beyond the common prefix are ignored.
62557 **
62558 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
62559 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
62560 ** an index key, and thus ends with a rowid value.  The last byte
62561 ** of the header will therefore be the serial type of the rowid:
62562 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
62563 ** The serial type of the final rowid will always be a single byte.
62564 ** By ignoring this last byte of the header, we force the comparison
62565 ** to ignore the rowid at the end of key1.
62566 */
62567 SQLCIPHER_PRIVATE int sqlcipher3VdbeRecordCompare(
62568   int nKey1, const void *pKey1, /* Left key */
62569   UnpackedRecord *pPKey2        /* Right key */
62570 ){
62571   int d1;            /* Offset into aKey[] of next data element */
62572   u32 idx1;          /* Offset into aKey[] of next header element */
62573   u32 szHdr1;        /* Number of bytes in header */
62574   int i = 0;
62575   int nField;
62576   int rc = 0;
62577   const unsigned char *aKey1 = (const unsigned char *)pKey1;
62578   KeyInfo *pKeyInfo;
62579   Mem mem1;
62580
62581   pKeyInfo = pPKey2->pKeyInfo;
62582   mem1.enc = pKeyInfo->enc;
62583   mem1.db = pKeyInfo->db;
62584   /* mem1.flags = 0;  // Will be initialized by sqlcipher3VdbeSerialGet() */
62585   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
62586
62587   /* Compilers may complain that mem1.u.i is potentially uninitialized.
62588   ** We could initialize it, as shown here, to silence those complaints.
62589   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
62590   ** the unnecessary initialization has a measurable negative performance
62591   ** impact, since this routine is a very high runner.  And so, we choose
62592   ** to ignore the compiler warnings and leave this variable uninitialized.
62593   */
62594   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
62595   
62596   idx1 = getVarint32(aKey1, szHdr1);
62597   d1 = szHdr1;
62598   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
62599     szHdr1--;
62600   }
62601   nField = pKeyInfo->nField;
62602   while( idx1<szHdr1 && i<pPKey2->nField ){
62603     u32 serial_type1;
62604
62605     /* Read the serial types for the next element in each key. */
62606     idx1 += getVarint32( aKey1+idx1, serial_type1 );
62607     if( d1>=nKey1 && sqlcipher3VdbeSerialTypeLen(serial_type1)>0 ) break;
62608
62609     /* Extract the values to be compared.
62610     */
62611     d1 += sqlcipher3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
62612
62613     /* Do the comparison
62614     */
62615     rc = sqlcipher3MemCompare(&mem1, &pPKey2->aMem[i],
62616                            i<nField ? pKeyInfo->aColl[i] : 0);
62617     if( rc!=0 ){
62618       assert( mem1.zMalloc==0 );  /* See comment below */
62619
62620       /* Invert the result if we are using DESC sort order. */
62621       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
62622         rc = -rc;
62623       }
62624     
62625       /* If the PREFIX_SEARCH flag is set and all fields except the final
62626       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
62627       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
62628       ** This is used by the OP_IsUnique opcode.
62629       */
62630       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
62631         assert( idx1==szHdr1 && rc );
62632         assert( mem1.flags & MEM_Int );
62633         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
62634         pPKey2->rowid = mem1.u.i;
62635       }
62636     
62637       return rc;
62638     }
62639     i++;
62640   }
62641
62642   /* No memory allocation is ever used on mem1.  Prove this using
62643   ** the following assert().  If the assert() fails, it indicates a
62644   ** memory leak and a need to call sqlcipher3VdbeMemRelease(&mem1).
62645   */
62646   assert( mem1.zMalloc==0 );
62647
62648   /* rc==0 here means that one of the keys ran out of fields and
62649   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
62650   ** flag is set, then break the tie by treating key2 as larger.
62651   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
62652   ** are considered to be equal.  Otherwise, the longer key is the 
62653   ** larger.  As it happens, the pPKey2 will always be the longer
62654   ** if there is a difference.
62655   */
62656   assert( rc==0 );
62657   if( pPKey2->flags & UNPACKED_INCRKEY ){
62658     rc = -1;
62659   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
62660     /* Leave rc==0 */
62661   }else if( idx1<szHdr1 ){
62662     rc = 1;
62663   }
62664   return rc;
62665 }
62666  
62667
62668 /*
62669 ** pCur points at an index entry created using the OP_MakeRecord opcode.
62670 ** Read the rowid (the last field in the record) and store it in *rowid.
62671 ** Return SQLCIPHER_OK if everything works, or an error code otherwise.
62672 **
62673 ** pCur might be pointing to text obtained from a corrupt database file.
62674 ** So the content cannot be trusted.  Do appropriate checks on the content.
62675 */
62676 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxRowid(sqlcipher3 *db, BtCursor *pCur, i64 *rowid){
62677   i64 nCellKey = 0;
62678   int rc;
62679   u32 szHdr;        /* Size of the header */
62680   u32 typeRowid;    /* Serial type of the rowid */
62681   u32 lenRowid;     /* Size of the rowid */
62682   Mem m, v;
62683
62684   UNUSED_PARAMETER(db);
62685
62686   /* Get the size of the index entry.  Only indices entries of less
62687   ** than 2GiB are support - anything large must be database corruption.
62688   ** Any corruption is detected in sqlcipher3BtreeParseCellPtr(), though, so
62689   ** this code can safely assume that nCellKey is 32-bits  
62690   */
62691   assert( sqlcipher3BtreeCursorIsValid(pCur) );
62692   VVA_ONLY(rc =) sqlcipher3BtreeKeySize(pCur, &nCellKey);
62693   assert( rc==SQLCIPHER_OK );     /* pCur is always valid so KeySize cannot fail */
62694   assert( (nCellKey & SQLCIPHER_MAX_U32)==(u64)nCellKey );
62695
62696   /* Read in the complete content of the index entry */
62697   memset(&m, 0, sizeof(m));
62698   rc = sqlcipher3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
62699   if( rc ){
62700     return rc;
62701   }
62702
62703   /* The index entry must begin with a header size */
62704   (void)getVarint32((u8*)m.z, szHdr);
62705   testcase( szHdr==3 );
62706   testcase( szHdr==m.n );
62707   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
62708     goto idx_rowid_corruption;
62709   }
62710
62711   /* The last field of the index should be an integer - the ROWID.
62712   ** Verify that the last entry really is an integer. */
62713   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
62714   testcase( typeRowid==1 );
62715   testcase( typeRowid==2 );
62716   testcase( typeRowid==3 );
62717   testcase( typeRowid==4 );
62718   testcase( typeRowid==5 );
62719   testcase( typeRowid==6 );
62720   testcase( typeRowid==8 );
62721   testcase( typeRowid==9 );
62722   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
62723     goto idx_rowid_corruption;
62724   }
62725   lenRowid = sqlcipher3VdbeSerialTypeLen(typeRowid);
62726   testcase( (u32)m.n==szHdr+lenRowid );
62727   if( unlikely((u32)m.n<szHdr+lenRowid) ){
62728     goto idx_rowid_corruption;
62729   }
62730
62731   /* Fetch the integer off the end of the index record */
62732   sqlcipher3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
62733   *rowid = v.u.i;
62734   sqlcipher3VdbeMemRelease(&m);
62735   return SQLCIPHER_OK;
62736
62737   /* Jump here if database corruption is detected after m has been
62738   ** allocated.  Free the m object and return SQLCIPHER_CORRUPT. */
62739 idx_rowid_corruption:
62740   testcase( m.zMalloc!=0 );
62741   sqlcipher3VdbeMemRelease(&m);
62742   return SQLCIPHER_CORRUPT_BKPT;
62743 }
62744
62745 /*
62746 ** Compare the key of the index entry that cursor pC is pointing to against
62747 ** the key string in pUnpacked.  Write into *pRes a number
62748 ** that is negative, zero, or positive if pC is less than, equal to,
62749 ** or greater than pUnpacked.  Return SQLCIPHER_OK on success.
62750 **
62751 ** pUnpacked is either created without a rowid or is truncated so that it
62752 ** omits the rowid at the end.  The rowid at the end of the index entry
62753 ** is ignored as well.  Hence, this routine only compares the prefixes 
62754 ** of the keys prior to the final rowid, not the entire key.
62755 */
62756 SQLCIPHER_PRIVATE int sqlcipher3VdbeIdxKeyCompare(
62757   VdbeCursor *pC,             /* The cursor to compare against */
62758   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
62759   int *res                    /* Write the comparison result here */
62760 ){
62761   i64 nCellKey = 0;
62762   int rc;
62763   BtCursor *pCur = pC->pCursor;
62764   Mem m;
62765
62766   assert( sqlcipher3BtreeCursorIsValid(pCur) );
62767   VVA_ONLY(rc =) sqlcipher3BtreeKeySize(pCur, &nCellKey);
62768   assert( rc==SQLCIPHER_OK );    /* pCur is always valid so KeySize cannot fail */
62769   /* nCellKey will always be between 0 and 0xffffffff because of the say
62770   ** that btreeParseCellPtr() and sqlcipher3GetVarint32() are implemented */
62771   if( nCellKey<=0 || nCellKey>0x7fffffff ){
62772     *res = 0;
62773     return SQLCIPHER_CORRUPT_BKPT;
62774   }
62775   memset(&m, 0, sizeof(m));
62776   rc = sqlcipher3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
62777   if( rc ){
62778     return rc;
62779   }
62780   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
62781   *res = sqlcipher3VdbeRecordCompare(m.n, m.z, pUnpacked);
62782   sqlcipher3VdbeMemRelease(&m);
62783   return SQLCIPHER_OK;
62784 }
62785
62786 /*
62787 ** This routine sets the value to be returned by subsequent calls to
62788 ** sqlcipher3_changes() on the database handle 'db'. 
62789 */
62790 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetChanges(sqlcipher3 *db, int nChange){
62791   assert( sqlcipher3_mutex_held(db->mutex) );
62792   db->nChange = nChange;
62793   db->nTotalChange += nChange;
62794 }
62795
62796 /*
62797 ** Set a flag in the vdbe to update the change counter when it is finalised
62798 ** or reset.
62799 */
62800 SQLCIPHER_PRIVATE void sqlcipher3VdbeCountChanges(Vdbe *v){
62801   v->changeCntOn = 1;
62802 }
62803
62804 /*
62805 ** Mark every prepared statement associated with a database connection
62806 ** as expired.
62807 **
62808 ** An expired statement means that recompilation of the statement is
62809 ** recommend.  Statements expire when things happen that make their
62810 ** programs obsolete.  Removing user-defined functions or collating
62811 ** sequences, or changing an authorization function are the types of
62812 ** things that make prepared statements obsolete.
62813 */
62814 SQLCIPHER_PRIVATE void sqlcipher3ExpirePreparedStatements(sqlcipher3 *db){
62815   Vdbe *p;
62816   for(p = db->pVdbe; p; p=p->pNext){
62817     p->expired = 1;
62818   }
62819 }
62820
62821 /*
62822 ** Return the database associated with the Vdbe.
62823 */
62824 SQLCIPHER_PRIVATE sqlcipher3 *sqlcipher3VdbeDb(Vdbe *v){
62825   return v->db;
62826 }
62827
62828 /*
62829 ** Return a pointer to an sqlcipher3_value structure containing the value bound
62830 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
62831 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLCIPHER_AFF_*
62832 ** constants) to the value before returning it.
62833 **
62834 ** The returned value must be freed by the caller using sqlcipher3ValueFree().
62835 */
62836 SQLCIPHER_PRIVATE sqlcipher3_value *sqlcipher3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
62837   assert( iVar>0 );
62838   if( v ){
62839     Mem *pMem = &v->aVar[iVar-1];
62840     if( 0==(pMem->flags & MEM_Null) ){
62841       sqlcipher3_value *pRet = sqlcipher3ValueNew(v->db);
62842       if( pRet ){
62843         sqlcipher3VdbeMemCopy((Mem *)pRet, pMem);
62844         sqlcipher3ValueApplyAffinity(pRet, aff, SQLCIPHER_UTF8);
62845         sqlcipher3VdbeMemStoreType((Mem *)pRet);
62846       }
62847       return pRet;
62848     }
62849   }
62850   return 0;
62851 }
62852
62853 /*
62854 ** Configure SQL variable iVar so that binding a new value to it signals
62855 ** to sqlcipher3_reoptimize() that re-preparing the statement may result
62856 ** in a better query plan.
62857 */
62858 SQLCIPHER_PRIVATE void sqlcipher3VdbeSetVarmask(Vdbe *v, int iVar){
62859   assert( iVar>0 );
62860   if( iVar>32 ){
62861     v->expmask = 0xffffffff;
62862   }else{
62863     v->expmask |= ((u32)1 << (iVar-1));
62864   }
62865 }
62866
62867 /************** End of vdbeaux.c *********************************************/
62868 /************** Begin file vdbeapi.c *****************************************/
62869 /*
62870 ** 2004 May 26
62871 **
62872 ** The author disclaims copyright to this source code.  In place of
62873 ** a legal notice, here is a blessing:
62874 **
62875 **    May you do good and not evil.
62876 **    May you find forgiveness for yourself and forgive others.
62877 **    May you share freely, never taking more than you give.
62878 **
62879 *************************************************************************
62880 **
62881 ** This file contains code use to implement APIs that are part of the
62882 ** VDBE.
62883 */
62884
62885 #ifndef SQLCIPHER_OMIT_DEPRECATED
62886 /*
62887 ** Return TRUE (non-zero) of the statement supplied as an argument needs
62888 ** to be recompiled.  A statement needs to be recompiled whenever the
62889 ** execution environment changes in a way that would alter the program
62890 ** that sqlcipher3_prepare() generates.  For example, if new functions or
62891 ** collating sequences are registered or if an authorizer function is
62892 ** added or changed.
62893 */
62894 SQLCIPHER_API int sqlcipher3_expired(sqlcipher3_stmt *pStmt){
62895   Vdbe *p = (Vdbe*)pStmt;
62896   return p==0 || p->expired;
62897 }
62898 #endif
62899
62900 /*
62901 ** Check on a Vdbe to make sure it has not been finalized.  Log
62902 ** an error and return true if it has been finalized (or is otherwise
62903 ** invalid).  Return false if it is ok.
62904 */
62905 static int vdbeSafety(Vdbe *p){
62906   if( p->db==0 ){
62907     sqlcipher3_log(SQLCIPHER_MISUSE, "API called with finalized prepared statement");
62908     return 1;
62909   }else{
62910     return 0;
62911   }
62912 }
62913 static int vdbeSafetyNotNull(Vdbe *p){
62914   if( p==0 ){
62915     sqlcipher3_log(SQLCIPHER_MISUSE, "API called with NULL prepared statement");
62916     return 1;
62917   }else{
62918     return vdbeSafety(p);
62919   }
62920 }
62921
62922 /*
62923 ** The following routine destroys a virtual machine that is created by
62924 ** the sqlcipher3_compile() routine. The integer returned is an SQLCIPHER_
62925 ** success/failure code that describes the result of executing the virtual
62926 ** machine.
62927 **
62928 ** This routine sets the error code and string returned by
62929 ** sqlcipher3_errcode(), sqlcipher3_errmsg() and sqlcipher3_errmsg16().
62930 */
62931 SQLCIPHER_API int sqlcipher3_finalize(sqlcipher3_stmt *pStmt){
62932   int rc;
62933   if( pStmt==0 ){
62934     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlcipher3_finalize() on a NULL
62935     ** pointer is a harmless no-op. */
62936     rc = SQLCIPHER_OK;
62937   }else{
62938     Vdbe *v = (Vdbe*)pStmt;
62939     sqlcipher3 *db = v->db;
62940 #if SQLCIPHER_THREADSAFE
62941     sqlcipher3_mutex *mutex;
62942 #endif
62943     if( vdbeSafety(v) ) return SQLCIPHER_MISUSE_BKPT;
62944 #if SQLCIPHER_THREADSAFE
62945     mutex = v->db->mutex;
62946 #endif
62947     sqlcipher3_mutex_enter(mutex);
62948     rc = sqlcipher3VdbeFinalize(v);
62949     rc = sqlcipher3ApiExit(db, rc);
62950     sqlcipher3_mutex_leave(mutex);
62951   }
62952   return rc;
62953 }
62954
62955 /*
62956 ** Terminate the current execution of an SQL statement and reset it
62957 ** back to its starting state so that it can be reused. A success code from
62958 ** the prior execution is returned.
62959 **
62960 ** This routine sets the error code and string returned by
62961 ** sqlcipher3_errcode(), sqlcipher3_errmsg() and sqlcipher3_errmsg16().
62962 */
62963 SQLCIPHER_API int sqlcipher3_reset(sqlcipher3_stmt *pStmt){
62964   int rc;
62965   if( pStmt==0 ){
62966     rc = SQLCIPHER_OK;
62967   }else{
62968     Vdbe *v = (Vdbe*)pStmt;
62969     sqlcipher3_mutex_enter(v->db->mutex);
62970     rc = sqlcipher3VdbeReset(v);
62971     sqlcipher3VdbeRewind(v);
62972     assert( (rc & (v->db->errMask))==rc );
62973     rc = sqlcipher3ApiExit(v->db, rc);
62974     sqlcipher3_mutex_leave(v->db->mutex);
62975   }
62976   return rc;
62977 }
62978
62979 /*
62980 ** Set all the parameters in the compiled SQL statement to NULL.
62981 */
62982 SQLCIPHER_API int sqlcipher3_clear_bindings(sqlcipher3_stmt *pStmt){
62983   int i;
62984   int rc = SQLCIPHER_OK;
62985   Vdbe *p = (Vdbe*)pStmt;
62986 #if SQLCIPHER_THREADSAFE
62987   sqlcipher3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
62988 #endif
62989   sqlcipher3_mutex_enter(mutex);
62990   for(i=0; i<p->nVar; i++){
62991     sqlcipher3VdbeMemRelease(&p->aVar[i]);
62992     p->aVar[i].flags = MEM_Null;
62993   }
62994   if( p->isPrepareV2 && p->expmask ){
62995     p->expired = 1;
62996   }
62997   sqlcipher3_mutex_leave(mutex);
62998   return rc;
62999 }
63000
63001
63002 /**************************** sqlcipher3_value_  *******************************
63003 ** The following routines extract information from a Mem or sqlcipher3_value
63004 ** structure.
63005 */
63006 SQLCIPHER_API const void *sqlcipher3_value_blob(sqlcipher3_value *pVal){
63007   Mem *p = (Mem*)pVal;
63008   if( p->flags & (MEM_Blob|MEM_Str) ){
63009     sqlcipher3VdbeMemExpandBlob(p);
63010     p->flags &= ~MEM_Str;
63011     p->flags |= MEM_Blob;
63012     return p->n ? p->z : 0;
63013   }else{
63014     return sqlcipher3_value_text(pVal);
63015   }
63016 }
63017 SQLCIPHER_API int sqlcipher3_value_bytes(sqlcipher3_value *pVal){
63018   return sqlcipher3ValueBytes(pVal, SQLCIPHER_UTF8);
63019 }
63020 SQLCIPHER_API int sqlcipher3_value_bytes16(sqlcipher3_value *pVal){
63021   return sqlcipher3ValueBytes(pVal, SQLCIPHER_UTF16NATIVE);
63022 }
63023 SQLCIPHER_API double sqlcipher3_value_double(sqlcipher3_value *pVal){
63024   return sqlcipher3VdbeRealValue((Mem*)pVal);
63025 }
63026 SQLCIPHER_API int sqlcipher3_value_int(sqlcipher3_value *pVal){
63027   return (int)sqlcipher3VdbeIntValue((Mem*)pVal);
63028 }
63029 SQLCIPHER_API sqlcipher_int64 sqlcipher3_value_int64(sqlcipher3_value *pVal){
63030   return sqlcipher3VdbeIntValue((Mem*)pVal);
63031 }
63032 SQLCIPHER_API const unsigned char *sqlcipher3_value_text(sqlcipher3_value *pVal){
63033   return (const unsigned char *)sqlcipher3ValueText(pVal, SQLCIPHER_UTF8);
63034 }
63035 #ifndef SQLCIPHER_OMIT_UTF16
63036 SQLCIPHER_API const void *sqlcipher3_value_text16(sqlcipher3_value* pVal){
63037   return sqlcipher3ValueText(pVal, SQLCIPHER_UTF16NATIVE);
63038 }
63039 SQLCIPHER_API const void *sqlcipher3_value_text16be(sqlcipher3_value *pVal){
63040   return sqlcipher3ValueText(pVal, SQLCIPHER_UTF16BE);
63041 }
63042 SQLCIPHER_API const void *sqlcipher3_value_text16le(sqlcipher3_value *pVal){
63043   return sqlcipher3ValueText(pVal, SQLCIPHER_UTF16LE);
63044 }
63045 #endif /* SQLCIPHER_OMIT_UTF16 */
63046 SQLCIPHER_API int sqlcipher3_value_type(sqlcipher3_value* pVal){
63047   return pVal->type;
63048 }
63049
63050 /**************************** sqlcipher3_result_  *******************************
63051 ** The following routines are used by user-defined functions to specify
63052 ** the function result.
63053 **
63054 ** The setStrOrError() funtion calls sqlcipher3VdbeMemSetStr() to store the
63055 ** result as a string or blob but if the string or blob is too large, it
63056 ** then sets the error code to SQLCIPHER_TOOBIG
63057 */
63058 static void setResultStrOrError(
63059   sqlcipher3_context *pCtx,  /* Function context */
63060   const char *z,          /* String pointer */
63061   int n,                  /* Bytes in string, or negative */
63062   u8 enc,                 /* Encoding of z.  0 for BLOBs */
63063   void (*xDel)(void*)     /* Destructor function */
63064 ){
63065   if( sqlcipher3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLCIPHER_TOOBIG ){
63066     sqlcipher3_result_error_toobig(pCtx);
63067   }
63068 }
63069 SQLCIPHER_API void sqlcipher3_result_blob(
63070   sqlcipher3_context *pCtx, 
63071   const void *z, 
63072   int n, 
63073   void (*xDel)(void *)
63074 ){
63075   assert( n>=0 );
63076   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63077   setResultStrOrError(pCtx, z, n, 0, xDel);
63078 }
63079 SQLCIPHER_API void sqlcipher3_result_double(sqlcipher3_context *pCtx, double rVal){
63080   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63081   sqlcipher3VdbeMemSetDouble(&pCtx->s, rVal);
63082 }
63083 SQLCIPHER_API void sqlcipher3_result_error(sqlcipher3_context *pCtx, const char *z, int n){
63084   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63085   pCtx->isError = SQLCIPHER_ERROR;
63086   sqlcipher3VdbeMemSetStr(&pCtx->s, z, n, SQLCIPHER_UTF8, SQLCIPHER_TRANSIENT);
63087 }
63088 #ifndef SQLCIPHER_OMIT_UTF16
63089 SQLCIPHER_API void sqlcipher3_result_error16(sqlcipher3_context *pCtx, const void *z, int n){
63090   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63091   pCtx->isError = SQLCIPHER_ERROR;
63092   sqlcipher3VdbeMemSetStr(&pCtx->s, z, n, SQLCIPHER_UTF16NATIVE, SQLCIPHER_TRANSIENT);
63093 }
63094 #endif
63095 SQLCIPHER_API void sqlcipher3_result_int(sqlcipher3_context *pCtx, int iVal){
63096   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63097   sqlcipher3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63098 }
63099 SQLCIPHER_API void sqlcipher3_result_int64(sqlcipher3_context *pCtx, i64 iVal){
63100   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63101   sqlcipher3VdbeMemSetInt64(&pCtx->s, iVal);
63102 }
63103 SQLCIPHER_API void sqlcipher3_result_null(sqlcipher3_context *pCtx){
63104   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63105   sqlcipher3VdbeMemSetNull(&pCtx->s);
63106 }
63107 SQLCIPHER_API void sqlcipher3_result_text(
63108   sqlcipher3_context *pCtx, 
63109   const char *z, 
63110   int n,
63111   void (*xDel)(void *)
63112 ){
63113   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63114   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF8, xDel);
63115 }
63116 #ifndef SQLCIPHER_OMIT_UTF16
63117 SQLCIPHER_API void sqlcipher3_result_text16(
63118   sqlcipher3_context *pCtx, 
63119   const void *z, 
63120   int n, 
63121   void (*xDel)(void *)
63122 ){
63123   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63124   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF16NATIVE, xDel);
63125 }
63126 SQLCIPHER_API void sqlcipher3_result_text16be(
63127   sqlcipher3_context *pCtx, 
63128   const void *z, 
63129   int n, 
63130   void (*xDel)(void *)
63131 ){
63132   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63133   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF16BE, xDel);
63134 }
63135 SQLCIPHER_API void sqlcipher3_result_text16le(
63136   sqlcipher3_context *pCtx, 
63137   const void *z, 
63138   int n, 
63139   void (*xDel)(void *)
63140 ){
63141   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63142   setResultStrOrError(pCtx, z, n, SQLCIPHER_UTF16LE, xDel);
63143 }
63144 #endif /* SQLCIPHER_OMIT_UTF16 */
63145 SQLCIPHER_API void sqlcipher3_result_value(sqlcipher3_context *pCtx, sqlcipher3_value *pValue){
63146   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63147   sqlcipher3VdbeMemCopy(&pCtx->s, pValue);
63148 }
63149 SQLCIPHER_API void sqlcipher3_result_zeroblob(sqlcipher3_context *pCtx, int n){
63150   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63151   sqlcipher3VdbeMemSetZeroBlob(&pCtx->s, n);
63152 }
63153 SQLCIPHER_API void sqlcipher3_result_error_code(sqlcipher3_context *pCtx, int errCode){
63154   pCtx->isError = errCode;
63155   if( pCtx->s.flags & MEM_Null ){
63156     sqlcipher3VdbeMemSetStr(&pCtx->s, sqlcipher3ErrStr(errCode), -1, 
63157                          SQLCIPHER_UTF8, SQLCIPHER_STATIC);
63158   }
63159 }
63160
63161 /* Force an SQLCIPHER_TOOBIG error. */
63162 SQLCIPHER_API void sqlcipher3_result_error_toobig(sqlcipher3_context *pCtx){
63163   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63164   pCtx->isError = SQLCIPHER_TOOBIG;
63165   sqlcipher3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
63166                        SQLCIPHER_UTF8, SQLCIPHER_STATIC);
63167 }
63168
63169 /* An SQLCIPHER_NOMEM error. */
63170 SQLCIPHER_API void sqlcipher3_result_error_nomem(sqlcipher3_context *pCtx){
63171   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63172   sqlcipher3VdbeMemSetNull(&pCtx->s);
63173   pCtx->isError = SQLCIPHER_NOMEM;
63174   pCtx->s.db->mallocFailed = 1;
63175 }
63176
63177 /*
63178 ** This function is called after a transaction has been committed. It 
63179 ** invokes callbacks registered with sqlcipher3_wal_hook() as required.
63180 */
63181 static int doWalCallbacks(sqlcipher3 *db){
63182   int rc = SQLCIPHER_OK;
63183 #ifndef SQLCIPHER_OMIT_WAL
63184   int i;
63185   for(i=0; i<db->nDb; i++){
63186     Btree *pBt = db->aDb[i].pBt;
63187     if( pBt ){
63188       int nEntry = sqlcipher3PagerWalCallback(sqlcipher3BtreePager(pBt));
63189       if( db->xWalCallback && nEntry>0 && rc==SQLCIPHER_OK ){
63190         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63191       }
63192     }
63193   }
63194 #endif
63195   return rc;
63196 }
63197
63198 /*
63199 ** Execute the statement pStmt, either until a row of data is ready, the
63200 ** statement is completely executed or an error occurs.
63201 **
63202 ** This routine implements the bulk of the logic behind the sqlcipher_step()
63203 ** API.  The only thing omitted is the automatic recompile if a 
63204 ** schema change has occurred.  That detail is handled by the
63205 ** outer sqlcipher3_step() wrapper procedure.
63206 */
63207 static int sqlcipher3Step(Vdbe *p){
63208   sqlcipher3 *db;
63209   int rc;
63210
63211   assert(p);
63212   if( p->magic!=VDBE_MAGIC_RUN ){
63213     /* We used to require that sqlcipher3_reset() be called before retrying
63214     ** sqlcipher3_step() after any error or after SQLCIPHER_DONE.  But beginning
63215     ** with version 3.7.0, we changed this so that sqlcipher3_reset() would
63216     ** be called automatically instead of throwing the SQLCIPHER_MISUSE error.
63217     ** This "automatic-reset" change is not technically an incompatibility, 
63218     ** since any application that receives an SQLCIPHER_MISUSE is broken by
63219     ** definition.
63220     **
63221     ** Nevertheless, some published applications that were originally written
63222     ** for version 3.6.23 or earlier do in fact depend on SQLCIPHER_MISUSE 
63223     ** returns, and the so were broken by the automatic-reset change.  As a
63224     ** a work-around, the SQLCIPHER_OMIT_AUTORESET compile-time restores the
63225     ** legacy behavior of returning SQLCIPHER_MISUSE for cases where the 
63226     ** previous sqlcipher3_step() returned something other than a SQLCIPHER_LOCKED
63227     ** or SQLCIPHER_BUSY error.
63228     */
63229 #ifdef SQLCIPHER_OMIT_AUTORESET
63230     if( p->rc==SQLCIPHER_BUSY || p->rc==SQLCIPHER_LOCKED ){
63231       sqlcipher3_reset((sqlcipher3_stmt*)p);
63232     }else{
63233       return SQLCIPHER_MISUSE_BKPT;
63234     }
63235 #else
63236     sqlcipher3_reset((sqlcipher3_stmt*)p);
63237 #endif
63238   }
63239
63240   /* Check that malloc() has not failed. If it has, return early. */
63241   db = p->db;
63242   if( db->mallocFailed ){
63243     p->rc = SQLCIPHER_NOMEM;
63244     return SQLCIPHER_NOMEM;
63245   }
63246
63247   if( p->pc<=0 && p->expired ){
63248     p->rc = SQLCIPHER_SCHEMA;
63249     rc = SQLCIPHER_ERROR;
63250     goto end_of_step;
63251   }
63252   if( p->pc<0 ){
63253     /* If there are no other statements currently running, then
63254     ** reset the interrupt flag.  This prevents a call to sqlcipher3_interrupt
63255     ** from interrupting a statement that has not yet started.
63256     */
63257     if( db->activeVdbeCnt==0 ){
63258       db->u1.isInterrupted = 0;
63259     }
63260
63261     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63262
63263 #ifndef SQLCIPHER_OMIT_TRACE
63264     if( db->xProfile && !db->init.busy ){
63265       sqlcipher3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63266     }
63267 #endif
63268
63269     db->activeVdbeCnt++;
63270     if( p->readOnly==0 ) db->writeVdbeCnt++;
63271     p->pc = 0;
63272   }
63273 #ifndef SQLCIPHER_OMIT_EXPLAIN
63274   if( p->explain ){
63275     rc = sqlcipher3VdbeList(p);
63276   }else
63277 #endif /* SQLCIPHER_OMIT_EXPLAIN */
63278   {
63279     db->vdbeExecCnt++;
63280     rc = sqlcipher3VdbeExec(p);
63281     db->vdbeExecCnt--;
63282   }
63283
63284 #ifndef SQLCIPHER_OMIT_TRACE
63285   /* Invoke the profile callback if there is one
63286   */
63287   if( rc!=SQLCIPHER_ROW && db->xProfile && !db->init.busy && p->zSql ){
63288     sqlcipher3_int64 iNow;
63289     sqlcipher3OsCurrentTimeInt64(db->pVfs, &iNow);
63290     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63291   }
63292 #endif
63293
63294   if( rc==SQLCIPHER_DONE ){
63295     assert( p->rc==SQLCIPHER_OK );
63296     p->rc = doWalCallbacks(db);
63297     if( p->rc!=SQLCIPHER_OK ){
63298       rc = SQLCIPHER_ERROR;
63299     }
63300   }
63301
63302   db->errCode = rc;
63303   if( SQLCIPHER_NOMEM==sqlcipher3ApiExit(p->db, p->rc) ){
63304     p->rc = SQLCIPHER_NOMEM;
63305   }
63306 end_of_step:
63307   /* At this point local variable rc holds the value that should be 
63308   ** returned if this statement was compiled using the legacy 
63309   ** sqlcipher3_prepare() interface. According to the docs, this can only
63310   ** be one of the values in the first assert() below. Variable p->rc 
63311   ** contains the value that would be returned if sqlcipher3_finalize() 
63312   ** were called on statement p.
63313   */
63314   assert( rc==SQLCIPHER_ROW  || rc==SQLCIPHER_DONE   || rc==SQLCIPHER_ERROR 
63315        || rc==SQLCIPHER_BUSY || rc==SQLCIPHER_MISUSE
63316   );
63317   assert( p->rc!=SQLCIPHER_ROW && p->rc!=SQLCIPHER_DONE );
63318   if( p->isPrepareV2 && rc!=SQLCIPHER_ROW && rc!=SQLCIPHER_DONE ){
63319     /* If this statement was prepared using sqlcipher3_prepare_v2(), and an
63320     ** error has occured, then return the error code in p->rc to the
63321     ** caller. Set the error code in the database handle to the same value.
63322     */ 
63323     rc = sqlcipher3VdbeTransferError(p);
63324   }
63325   return (rc&db->errMask);
63326 }
63327
63328 /*
63329 ** The maximum number of times that a statement will try to reparse
63330 ** itself before giving up and returning SQLCIPHER_SCHEMA.
63331 */
63332 #ifndef SQLCIPHER_MAX_SCHEMA_RETRY
63333 # define SQLCIPHER_MAX_SCHEMA_RETRY 5
63334 #endif
63335
63336 /*
63337 ** This is the top-level implementation of sqlcipher3_step().  Call
63338 ** sqlcipher3Step() to do most of the work.  If a schema error occurs,
63339 ** call sqlcipher3Reprepare() and try again.
63340 */
63341 SQLCIPHER_API int sqlcipher3_step(sqlcipher3_stmt *pStmt){
63342   int rc = SQLCIPHER_OK;      /* Result from sqlcipher3Step() */
63343   int rc2 = SQLCIPHER_OK;     /* Result from sqlcipher3Reprepare() */
63344   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63345   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63346   sqlcipher3 *db;             /* The database connection */
63347
63348   if( vdbeSafetyNotNull(v) ){
63349     return SQLCIPHER_MISUSE_BKPT;
63350   }
63351   db = v->db;
63352   sqlcipher3_mutex_enter(db->mutex);
63353   while( (rc = sqlcipher3Step(v))==SQLCIPHER_SCHEMA
63354          && cnt++ < SQLCIPHER_MAX_SCHEMA_RETRY
63355          && (rc2 = rc = sqlcipher3Reprepare(v))==SQLCIPHER_OK ){
63356     sqlcipher3_reset(pStmt);
63357     assert( v->expired==0 );
63358   }
63359   if( rc2!=SQLCIPHER_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63360     /* This case occurs after failing to recompile an sql statement. 
63361     ** The error message from the SQL compiler has already been loaded 
63362     ** into the database handle. This block copies the error message 
63363     ** from the database handle into the statement and sets the statement
63364     ** program counter to 0 to ensure that when the statement is 
63365     ** finalized or reset the parser error message is available via
63366     ** sqlcipher3_errmsg() and sqlcipher3_errcode().
63367     */
63368     const char *zErr = (const char *)sqlcipher3_value_text(db->pErr); 
63369     sqlcipher3DbFree(db, v->zErrMsg);
63370     if( !db->mallocFailed ){
63371       v->zErrMsg = sqlcipher3DbStrDup(db, zErr);
63372       v->rc = rc2;
63373     } else {
63374       v->zErrMsg = 0;
63375       v->rc = rc = SQLCIPHER_NOMEM;
63376     }
63377   }
63378   rc = sqlcipher3ApiExit(db, rc);
63379   sqlcipher3_mutex_leave(db->mutex);
63380   return rc;
63381 }
63382
63383 /*
63384 ** Extract the user data from a sqlcipher3_context structure and return a
63385 ** pointer to it.
63386 */
63387 SQLCIPHER_API void *sqlcipher3_user_data(sqlcipher3_context *p){
63388   assert( p && p->pFunc );
63389   return p->pFunc->pUserData;
63390 }
63391
63392 /*
63393 ** Extract the user data from a sqlcipher3_context structure and return a
63394 ** pointer to it.
63395 **
63396 ** IMPLEMENTATION-OF: R-46798-50301 The sqlcipher3_context_db_handle() interface
63397 ** returns a copy of the pointer to the database connection (the 1st
63398 ** parameter) of the sqlcipher3_create_function() and
63399 ** sqlcipher3_create_function16() routines that originally registered the
63400 ** application defined function.
63401 */
63402 SQLCIPHER_API sqlcipher3 *sqlcipher3_context_db_handle(sqlcipher3_context *p){
63403   assert( p && p->pFunc );
63404   return p->s.db;
63405 }
63406
63407 /*
63408 ** The following is the implementation of an SQL function that always
63409 ** fails with an error message stating that the function is used in the
63410 ** wrong context.  The sqlcipher3_overload_function() API might construct
63411 ** SQL function that use this routine so that the functions will exist
63412 ** for name resolution but are actually overloaded by the xFindFunction
63413 ** method of virtual tables.
63414 */
63415 SQLCIPHER_PRIVATE void sqlcipher3InvalidFunction(
63416   sqlcipher3_context *context,  /* The function calling context */
63417   int NotUsed,               /* Number of arguments to the function */
63418   sqlcipher3_value **NotUsed2   /* Value of each argument */
63419 ){
63420   const char *zName = context->pFunc->zName;
63421   char *zErr;
63422   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63423   zErr = sqlcipher3_mprintf(
63424       "unable to use function %s in the requested context", zName);
63425   sqlcipher3_result_error(context, zErr, -1);
63426   sqlcipher3_free(zErr);
63427 }
63428
63429 /*
63430 ** Allocate or return the aggregate context for a user function.  A new
63431 ** context is allocated on the first call.  Subsequent calls return the
63432 ** same context that was returned on prior calls.
63433 */
63434 SQLCIPHER_API void *sqlcipher3_aggregate_context(sqlcipher3_context *p, int nByte){
63435   Mem *pMem;
63436   assert( p && p->pFunc && p->pFunc->xStep );
63437   assert( sqlcipher3_mutex_held(p->s.db->mutex) );
63438   pMem = p->pMem;
63439   testcase( nByte<0 );
63440   if( (pMem->flags & MEM_Agg)==0 ){
63441     if( nByte<=0 ){
63442       sqlcipher3VdbeMemReleaseExternal(pMem);
63443       pMem->flags = MEM_Null;
63444       pMem->z = 0;
63445     }else{
63446       sqlcipher3VdbeMemGrow(pMem, nByte, 0);
63447       pMem->flags = MEM_Agg;
63448       pMem->u.pDef = p->pFunc;
63449       if( pMem->z ){
63450         memset(pMem->z, 0, nByte);
63451       }
63452     }
63453   }
63454   return (void*)pMem->z;
63455 }
63456
63457 /*
63458 ** Return the auxilary data pointer, if any, for the iArg'th argument to
63459 ** the user-function defined by pCtx.
63460 */
63461 SQLCIPHER_API void *sqlcipher3_get_auxdata(sqlcipher3_context *pCtx, int iArg){
63462   VdbeFunc *pVdbeFunc;
63463
63464   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63465   pVdbeFunc = pCtx->pVdbeFunc;
63466   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
63467     return 0;
63468   }
63469   return pVdbeFunc->apAux[iArg].pAux;
63470 }
63471
63472 /*
63473 ** Set the auxilary data pointer and delete function, for the iArg'th
63474 ** argument to the user-function defined by pCtx. Any previous value is
63475 ** deleted by calling the delete function specified when it was set.
63476 */
63477 SQLCIPHER_API void sqlcipher3_set_auxdata(
63478   sqlcipher3_context *pCtx, 
63479   int iArg, 
63480   void *pAux, 
63481   void (*xDelete)(void*)
63482 ){
63483   struct AuxData *pAuxData;
63484   VdbeFunc *pVdbeFunc;
63485   if( iArg<0 ) goto failed;
63486
63487   assert( sqlcipher3_mutex_held(pCtx->s.db->mutex) );
63488   pVdbeFunc = pCtx->pVdbeFunc;
63489   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
63490     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
63491     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
63492     pVdbeFunc = sqlcipher3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
63493     if( !pVdbeFunc ){
63494       goto failed;
63495     }
63496     pCtx->pVdbeFunc = pVdbeFunc;
63497     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
63498     pVdbeFunc->nAux = iArg+1;
63499     pVdbeFunc->pFunc = pCtx->pFunc;
63500   }
63501
63502   pAuxData = &pVdbeFunc->apAux[iArg];
63503   if( pAuxData->pAux && pAuxData->xDelete ){
63504     pAuxData->xDelete(pAuxData->pAux);
63505   }
63506   pAuxData->pAux = pAux;
63507   pAuxData->xDelete = xDelete;
63508   return;
63509
63510 failed:
63511   if( xDelete ){
63512     xDelete(pAux);
63513   }
63514 }
63515
63516 #ifndef SQLCIPHER_OMIT_DEPRECATED
63517 /*
63518 ** Return the number of times the Step function of a aggregate has been 
63519 ** called.
63520 **
63521 ** This function is deprecated.  Do not use it for new code.  It is
63522 ** provide only to avoid breaking legacy code.  New aggregate function
63523 ** implementations should keep their own counts within their aggregate
63524 ** context.
63525 */
63526 SQLCIPHER_API int sqlcipher3_aggregate_count(sqlcipher3_context *p){
63527   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63528   return p->pMem->n;
63529 }
63530 #endif
63531
63532 /*
63533 ** Return the number of columns in the result set for the statement pStmt.
63534 */
63535 SQLCIPHER_API int sqlcipher3_column_count(sqlcipher3_stmt *pStmt){
63536   Vdbe *pVm = (Vdbe *)pStmt;
63537   return pVm ? pVm->nResColumn : 0;
63538 }
63539
63540 /*
63541 ** Return the number of values available from the current row of the
63542 ** currently executing statement pStmt.
63543 */
63544 SQLCIPHER_API int sqlcipher3_data_count(sqlcipher3_stmt *pStmt){
63545   Vdbe *pVm = (Vdbe *)pStmt;
63546   if( pVm==0 || pVm->pResultSet==0 ) return 0;
63547   return pVm->nResColumn;
63548 }
63549
63550
63551 /*
63552 ** Check to see if column iCol of the given statement is valid.  If
63553 ** it is, return a pointer to the Mem for the value of that column.
63554 ** If iCol is not valid, return a pointer to a Mem which has a value
63555 ** of NULL.
63556 */
63557 static Mem *columnMem(sqlcipher3_stmt *pStmt, int i){
63558   Vdbe *pVm;
63559   Mem *pOut;
63560
63561   pVm = (Vdbe *)pStmt;
63562   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
63563     sqlcipher3_mutex_enter(pVm->db->mutex);
63564     pOut = &pVm->pResultSet[i];
63565   }else{
63566     /* If the value passed as the second argument is out of range, return
63567     ** a pointer to the following static Mem object which contains the
63568     ** value SQL NULL. Even though the Mem structure contains an element
63569     ** of type i64, on certain architecture (x86) with certain compiler
63570     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
63571     ** instead of an 8-byte one. This all works fine, except that when
63572     ** running with SQLCIPHER_DEBUG defined the SQLite code sometimes assert()s
63573     ** that a Mem structure is located on an 8-byte boundary. To prevent
63574     ** this assert() from failing, when building with SQLCIPHER_DEBUG defined
63575     ** using gcc, force nullMem to be 8-byte aligned using the magical
63576     ** __attribute__((aligned(8))) macro.  */
63577     static const Mem nullMem 
63578 #if defined(SQLCIPHER_DEBUG) && defined(__GNUC__)
63579       __attribute__((aligned(8))) 
63580 #endif
63581       = {0, "", (double)0, {0}, 0, MEM_Null, SQLCIPHER_NULL, 0,
63582 #ifdef SQLCIPHER_DEBUG
63583          0, 0,  /* pScopyFrom, pFiller */
63584 #endif
63585          0, 0 };
63586
63587     if( pVm && ALWAYS(pVm->db) ){
63588       sqlcipher3_mutex_enter(pVm->db->mutex);
63589       sqlcipher3Error(pVm->db, SQLCIPHER_RANGE, 0);
63590     }
63591     pOut = (Mem*)&nullMem;
63592   }
63593   return pOut;
63594 }
63595
63596 /*
63597 ** This function is called after invoking an sqlcipher3_value_XXX function on a 
63598 ** column value (i.e. a value returned by evaluating an SQL expression in the
63599 ** select list of a SELECT statement) that may cause a malloc() failure. If 
63600 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
63601 ** code of statement pStmt set to SQLCIPHER_NOMEM.
63602 **
63603 ** Specifically, this is called from within:
63604 **
63605 **     sqlcipher3_column_int()
63606 **     sqlcipher3_column_int64()
63607 **     sqlcipher3_column_text()
63608 **     sqlcipher3_column_text16()
63609 **     sqlcipher3_column_real()
63610 **     sqlcipher3_column_bytes()
63611 **     sqlcipher3_column_bytes16()
63612 **     sqiite3_column_blob()
63613 */
63614 static void columnMallocFailure(sqlcipher3_stmt *pStmt)
63615 {
63616   /* If malloc() failed during an encoding conversion within an
63617   ** sqlcipher3_column_XXX API, then set the return code of the statement to
63618   ** SQLCIPHER_NOMEM. The next call to _step() (if any) will return SQLCIPHER_ERROR
63619   ** and _finalize() will return NOMEM.
63620   */
63621   Vdbe *p = (Vdbe *)pStmt;
63622   if( p ){
63623     p->rc = sqlcipher3ApiExit(p->db, p->rc);
63624     sqlcipher3_mutex_leave(p->db->mutex);
63625   }
63626 }
63627
63628 /**************************** sqlcipher3_column_  *******************************
63629 ** The following routines are used to access elements of the current row
63630 ** in the result set.
63631 */
63632 SQLCIPHER_API const void *sqlcipher3_column_blob(sqlcipher3_stmt *pStmt, int i){
63633   const void *val;
63634   val = sqlcipher3_value_blob( columnMem(pStmt,i) );
63635   /* Even though there is no encoding conversion, value_blob() might
63636   ** need to call malloc() to expand the result of a zeroblob() 
63637   ** expression. 
63638   */
63639   columnMallocFailure(pStmt);
63640   return val;
63641 }
63642 SQLCIPHER_API int sqlcipher3_column_bytes(sqlcipher3_stmt *pStmt, int i){
63643   int val = sqlcipher3_value_bytes( columnMem(pStmt,i) );
63644   columnMallocFailure(pStmt);
63645   return val;
63646 }
63647 SQLCIPHER_API int sqlcipher3_column_bytes16(sqlcipher3_stmt *pStmt, int i){
63648   int val = sqlcipher3_value_bytes16( columnMem(pStmt,i) );
63649   columnMallocFailure(pStmt);
63650   return val;
63651 }
63652 SQLCIPHER_API double sqlcipher3_column_double(sqlcipher3_stmt *pStmt, int i){
63653   double val = sqlcipher3_value_double( columnMem(pStmt,i) );
63654   columnMallocFailure(pStmt);
63655   return val;
63656 }
63657 SQLCIPHER_API int sqlcipher3_column_int(sqlcipher3_stmt *pStmt, int i){
63658   int val = sqlcipher3_value_int( columnMem(pStmt,i) );
63659   columnMallocFailure(pStmt);
63660   return val;
63661 }
63662 SQLCIPHER_API sqlcipher_int64 sqlcipher3_column_int64(sqlcipher3_stmt *pStmt, int i){
63663   sqlcipher_int64 val = sqlcipher3_value_int64( columnMem(pStmt,i) );
63664   columnMallocFailure(pStmt);
63665   return val;
63666 }
63667 SQLCIPHER_API const unsigned char *sqlcipher3_column_text(sqlcipher3_stmt *pStmt, int i){
63668   const unsigned char *val = sqlcipher3_value_text( columnMem(pStmt,i) );
63669   columnMallocFailure(pStmt);
63670   return val;
63671 }
63672 SQLCIPHER_API sqlcipher3_value *sqlcipher3_column_value(sqlcipher3_stmt *pStmt, int i){
63673   Mem *pOut = columnMem(pStmt, i);
63674   if( pOut->flags&MEM_Static ){
63675     pOut->flags &= ~MEM_Static;
63676     pOut->flags |= MEM_Ephem;
63677   }
63678   columnMallocFailure(pStmt);
63679   return (sqlcipher3_value *)pOut;
63680 }
63681 #ifndef SQLCIPHER_OMIT_UTF16
63682 SQLCIPHER_API const void *sqlcipher3_column_text16(sqlcipher3_stmt *pStmt, int i){
63683   const void *val = sqlcipher3_value_text16( columnMem(pStmt,i) );
63684   columnMallocFailure(pStmt);
63685   return val;
63686 }
63687 #endif /* SQLCIPHER_OMIT_UTF16 */
63688 SQLCIPHER_API int sqlcipher3_column_type(sqlcipher3_stmt *pStmt, int i){
63689   int iType = sqlcipher3_value_type( columnMem(pStmt,i) );
63690   columnMallocFailure(pStmt);
63691   return iType;
63692 }
63693
63694 /* The following function is experimental and subject to change or
63695 ** removal */
63696 /*int sqlcipher3_column_numeric_type(sqlcipher3_stmt *pStmt, int i){
63697 **  return sqlcipher3_value_numeric_type( columnMem(pStmt,i) );
63698 **}
63699 */
63700
63701 /*
63702 ** Convert the N-th element of pStmt->pColName[] into a string using
63703 ** xFunc() then return that string.  If N is out of range, return 0.
63704 **
63705 ** There are up to 5 names for each column.  useType determines which
63706 ** name is returned.  Here are the names:
63707 **
63708 **    0      The column name as it should be displayed for output
63709 **    1      The datatype name for the column
63710 **    2      The name of the database that the column derives from
63711 **    3      The name of the table that the column derives from
63712 **    4      The name of the table column that the result column derives from
63713 **
63714 ** If the result is not a simple column reference (if it is an expression
63715 ** or a constant) then useTypes 2, 3, and 4 return NULL.
63716 */
63717 static const void *columnName(
63718   sqlcipher3_stmt *pStmt,
63719   int N,
63720   const void *(*xFunc)(Mem*),
63721   int useType
63722 ){
63723   const void *ret = 0;
63724   Vdbe *p = (Vdbe *)pStmt;
63725   int n;
63726   sqlcipher3 *db = p->db;
63727   
63728   assert( db!=0 );
63729   n = sqlcipher3_column_count(pStmt);
63730   if( N<n && N>=0 ){
63731     N += useType*n;
63732     sqlcipher3_mutex_enter(db->mutex);
63733     assert( db->mallocFailed==0 );
63734     ret = xFunc(&p->aColName[N]);
63735      /* A malloc may have failed inside of the xFunc() call. If this
63736     ** is the case, clear the mallocFailed flag and return NULL.
63737     */
63738     if( db->mallocFailed ){
63739       db->mallocFailed = 0;
63740       ret = 0;
63741     }
63742     sqlcipher3_mutex_leave(db->mutex);
63743   }
63744   return ret;
63745 }
63746
63747 /*
63748 ** Return the name of the Nth column of the result set returned by SQL
63749 ** statement pStmt.
63750 */
63751 SQLCIPHER_API const char *sqlcipher3_column_name(sqlcipher3_stmt *pStmt, int N){
63752   return columnName(
63753       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_NAME);
63754 }
63755 #ifndef SQLCIPHER_OMIT_UTF16
63756 SQLCIPHER_API const void *sqlcipher3_column_name16(sqlcipher3_stmt *pStmt, int N){
63757   return columnName(
63758       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_NAME);
63759 }
63760 #endif
63761
63762 /*
63763 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
63764 ** not define OMIT_DECLTYPE.
63765 */
63766 #if defined(SQLCIPHER_OMIT_DECLTYPE) && defined(SQLCIPHER_ENABLE_COLUMN_METADATA)
63767 # error "Must not define both SQLCIPHER_OMIT_DECLTYPE \
63768          and SQLCIPHER_ENABLE_COLUMN_METADATA"
63769 #endif
63770
63771 #ifndef SQLCIPHER_OMIT_DECLTYPE
63772 /*
63773 ** Return the column declaration type (if applicable) of the 'i'th column
63774 ** of the result set of SQL statement pStmt.
63775 */
63776 SQLCIPHER_API const char *sqlcipher3_column_decltype(sqlcipher3_stmt *pStmt, int N){
63777   return columnName(
63778       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_DECLTYPE);
63779 }
63780 #ifndef SQLCIPHER_OMIT_UTF16
63781 SQLCIPHER_API const void *sqlcipher3_column_decltype16(sqlcipher3_stmt *pStmt, int N){
63782   return columnName(
63783       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_DECLTYPE);
63784 }
63785 #endif /* SQLCIPHER_OMIT_UTF16 */
63786 #endif /* SQLCIPHER_OMIT_DECLTYPE */
63787
63788 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
63789 /*
63790 ** Return the name of the database from which a result column derives.
63791 ** NULL is returned if the result column is an expression or constant or
63792 ** anything else which is not an unabiguous reference to a database column.
63793 */
63794 SQLCIPHER_API const char *sqlcipher3_column_database_name(sqlcipher3_stmt *pStmt, int N){
63795   return columnName(
63796       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_DATABASE);
63797 }
63798 #ifndef SQLCIPHER_OMIT_UTF16
63799 SQLCIPHER_API const void *sqlcipher3_column_database_name16(sqlcipher3_stmt *pStmt, int N){
63800   return columnName(
63801       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_DATABASE);
63802 }
63803 #endif /* SQLCIPHER_OMIT_UTF16 */
63804
63805 /*
63806 ** Return the name of the table from which a result column derives.
63807 ** NULL is returned if the result column is an expression or constant or
63808 ** anything else which is not an unabiguous reference to a database column.
63809 */
63810 SQLCIPHER_API const char *sqlcipher3_column_table_name(sqlcipher3_stmt *pStmt, int N){
63811   return columnName(
63812       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_TABLE);
63813 }
63814 #ifndef SQLCIPHER_OMIT_UTF16
63815 SQLCIPHER_API const void *sqlcipher3_column_table_name16(sqlcipher3_stmt *pStmt, int N){
63816   return columnName(
63817       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_TABLE);
63818 }
63819 #endif /* SQLCIPHER_OMIT_UTF16 */
63820
63821 /*
63822 ** Return the name of the table column from which a result column derives.
63823 ** NULL is returned if the result column is an expression or constant or
63824 ** anything else which is not an unabiguous reference to a database column.
63825 */
63826 SQLCIPHER_API const char *sqlcipher3_column_origin_name(sqlcipher3_stmt *pStmt, int N){
63827   return columnName(
63828       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text, COLNAME_COLUMN);
63829 }
63830 #ifndef SQLCIPHER_OMIT_UTF16
63831 SQLCIPHER_API const void *sqlcipher3_column_origin_name16(sqlcipher3_stmt *pStmt, int N){
63832   return columnName(
63833       pStmt, N, (const void*(*)(Mem*))sqlcipher3_value_text16, COLNAME_COLUMN);
63834 }
63835 #endif /* SQLCIPHER_OMIT_UTF16 */
63836 #endif /* SQLCIPHER_ENABLE_COLUMN_METADATA */
63837
63838
63839 /******************************* sqlcipher3_bind_  ***************************
63840 ** 
63841 ** Routines used to attach values to wildcards in a compiled SQL statement.
63842 */
63843 /*
63844 ** Unbind the value bound to variable i in virtual machine p. This is the 
63845 ** the same as binding a NULL value to the column. If the "i" parameter is
63846 ** out of range, then SQLCIPHER_RANGE is returned. Othewise SQLCIPHER_OK.
63847 **
63848 ** A successful evaluation of this routine acquires the mutex on p.
63849 ** the mutex is released if any kind of error occurs.
63850 **
63851 ** The error code stored in database p->db is overwritten with the return
63852 ** value in any case.
63853 */
63854 static int vdbeUnbind(Vdbe *p, int i){
63855   Mem *pVar;
63856   if( vdbeSafetyNotNull(p) ){
63857     return SQLCIPHER_MISUSE_BKPT;
63858   }
63859   sqlcipher3_mutex_enter(p->db->mutex);
63860   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
63861     sqlcipher3Error(p->db, SQLCIPHER_MISUSE, 0);
63862     sqlcipher3_mutex_leave(p->db->mutex);
63863     sqlcipher3_log(SQLCIPHER_MISUSE, 
63864         "bind on a busy prepared statement: [%s]", p->zSql);
63865     return SQLCIPHER_MISUSE_BKPT;
63866   }
63867   if( i<1 || i>p->nVar ){
63868     sqlcipher3Error(p->db, SQLCIPHER_RANGE, 0);
63869     sqlcipher3_mutex_leave(p->db->mutex);
63870     return SQLCIPHER_RANGE;
63871   }
63872   i--;
63873   pVar = &p->aVar[i];
63874   sqlcipher3VdbeMemRelease(pVar);
63875   pVar->flags = MEM_Null;
63876   sqlcipher3Error(p->db, SQLCIPHER_OK, 0);
63877
63878   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
63879   ** binding a new value to this variable invalidates the current query plan.
63880   **
63881   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
63882   ** parameter in the WHERE clause might influence the choice of query plan
63883   ** for a statement, then the statement will be automatically recompiled,
63884   ** as if there had been a schema change, on the first sqlcipher3_step() call
63885   ** following any change to the bindings of that parameter.
63886   */
63887   if( p->isPrepareV2 &&
63888      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
63889   ){
63890     p->expired = 1;
63891   }
63892   return SQLCIPHER_OK;
63893 }
63894
63895 /*
63896 ** Bind a text or BLOB value.
63897 */
63898 static int bindText(
63899   sqlcipher3_stmt *pStmt,   /* The statement to bind against */
63900   int i,                 /* Index of the parameter to bind */
63901   const void *zData,     /* Pointer to the data to be bound */
63902   int nData,             /* Number of bytes of data to be bound */
63903   void (*xDel)(void*),   /* Destructor for the data */
63904   u8 encoding            /* Encoding for the data */
63905 ){
63906   Vdbe *p = (Vdbe *)pStmt;
63907   Mem *pVar;
63908   int rc;
63909
63910   rc = vdbeUnbind(p, i);
63911   if( rc==SQLCIPHER_OK ){
63912     if( zData!=0 ){
63913       pVar = &p->aVar[i-1];
63914       rc = sqlcipher3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
63915       if( rc==SQLCIPHER_OK && encoding!=0 ){
63916         rc = sqlcipher3VdbeChangeEncoding(pVar, ENC(p->db));
63917       }
63918       sqlcipher3Error(p->db, rc, 0);
63919       rc = sqlcipher3ApiExit(p->db, rc);
63920     }
63921     sqlcipher3_mutex_leave(p->db->mutex);
63922   }else if( xDel!=SQLCIPHER_STATIC && xDel!=SQLCIPHER_TRANSIENT ){
63923     xDel((void*)zData);
63924   }
63925   return rc;
63926 }
63927
63928
63929 /*
63930 ** Bind a blob value to an SQL statement variable.
63931 */
63932 SQLCIPHER_API int sqlcipher3_bind_blob(
63933   sqlcipher3_stmt *pStmt, 
63934   int i, 
63935   const void *zData, 
63936   int nData, 
63937   void (*xDel)(void*)
63938 ){
63939   return bindText(pStmt, i, zData, nData, xDel, 0);
63940 }
63941 SQLCIPHER_API int sqlcipher3_bind_double(sqlcipher3_stmt *pStmt, int i, double rValue){
63942   int rc;
63943   Vdbe *p = (Vdbe *)pStmt;
63944   rc = vdbeUnbind(p, i);
63945   if( rc==SQLCIPHER_OK ){
63946     sqlcipher3VdbeMemSetDouble(&p->aVar[i-1], rValue);
63947     sqlcipher3_mutex_leave(p->db->mutex);
63948   }
63949   return rc;
63950 }
63951 SQLCIPHER_API int sqlcipher3_bind_int(sqlcipher3_stmt *p, int i, int iValue){
63952   return sqlcipher3_bind_int64(p, i, (i64)iValue);
63953 }
63954 SQLCIPHER_API int sqlcipher3_bind_int64(sqlcipher3_stmt *pStmt, int i, sqlcipher_int64 iValue){
63955   int rc;
63956   Vdbe *p = (Vdbe *)pStmt;
63957   rc = vdbeUnbind(p, i);
63958   if( rc==SQLCIPHER_OK ){
63959     sqlcipher3VdbeMemSetInt64(&p->aVar[i-1], iValue);
63960     sqlcipher3_mutex_leave(p->db->mutex);
63961   }
63962   return rc;
63963 }
63964 SQLCIPHER_API int sqlcipher3_bind_null(sqlcipher3_stmt *pStmt, int i){
63965   int rc;
63966   Vdbe *p = (Vdbe*)pStmt;
63967   rc = vdbeUnbind(p, i);
63968   if( rc==SQLCIPHER_OK ){
63969     sqlcipher3_mutex_leave(p->db->mutex);
63970   }
63971   return rc;
63972 }
63973 SQLCIPHER_API int sqlcipher3_bind_text( 
63974   sqlcipher3_stmt *pStmt, 
63975   int i, 
63976   const char *zData, 
63977   int nData, 
63978   void (*xDel)(void*)
63979 ){
63980   return bindText(pStmt, i, zData, nData, xDel, SQLCIPHER_UTF8);
63981 }
63982 #ifndef SQLCIPHER_OMIT_UTF16
63983 SQLCIPHER_API int sqlcipher3_bind_text16(
63984   sqlcipher3_stmt *pStmt, 
63985   int i, 
63986   const void *zData, 
63987   int nData, 
63988   void (*xDel)(void*)
63989 ){
63990   return bindText(pStmt, i, zData, nData, xDel, SQLCIPHER_UTF16NATIVE);
63991 }
63992 #endif /* SQLCIPHER_OMIT_UTF16 */
63993 SQLCIPHER_API int sqlcipher3_bind_value(sqlcipher3_stmt *pStmt, int i, const sqlcipher3_value *pValue){
63994   int rc;
63995   switch( pValue->type ){
63996     case SQLCIPHER_INTEGER: {
63997       rc = sqlcipher3_bind_int64(pStmt, i, pValue->u.i);
63998       break;
63999     }
64000     case SQLCIPHER_FLOAT: {
64001       rc = sqlcipher3_bind_double(pStmt, i, pValue->r);
64002       break;
64003     }
64004     case SQLCIPHER_BLOB: {
64005       if( pValue->flags & MEM_Zero ){
64006         rc = sqlcipher3_bind_zeroblob(pStmt, i, pValue->u.nZero);
64007       }else{
64008         rc = sqlcipher3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLCIPHER_TRANSIENT);
64009       }
64010       break;
64011     }
64012     case SQLCIPHER_TEXT: {
64013       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLCIPHER_TRANSIENT,
64014                               pValue->enc);
64015       break;
64016     }
64017     default: {
64018       rc = sqlcipher3_bind_null(pStmt, i);
64019       break;
64020     }
64021   }
64022   return rc;
64023 }
64024 SQLCIPHER_API int sqlcipher3_bind_zeroblob(sqlcipher3_stmt *pStmt, int i, int n){
64025   int rc;
64026   Vdbe *p = (Vdbe *)pStmt;
64027   rc = vdbeUnbind(p, i);
64028   if( rc==SQLCIPHER_OK ){
64029     sqlcipher3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64030     sqlcipher3_mutex_leave(p->db->mutex);
64031   }
64032   return rc;
64033 }
64034
64035 /*
64036 ** Return the number of wildcards that can be potentially bound to.
64037 ** This routine is added to support DBD::SQLite.  
64038 */
64039 SQLCIPHER_API int sqlcipher3_bind_parameter_count(sqlcipher3_stmt *pStmt){
64040   Vdbe *p = (Vdbe*)pStmt;
64041   return p ? p->nVar : 0;
64042 }
64043
64044 /*
64045 ** Return the name of a wildcard parameter.  Return NULL if the index
64046 ** is out of range or if the wildcard is unnamed.
64047 **
64048 ** The result is always UTF-8.
64049 */
64050 SQLCIPHER_API const char *sqlcipher3_bind_parameter_name(sqlcipher3_stmt *pStmt, int i){
64051   Vdbe *p = (Vdbe*)pStmt;
64052   if( p==0 || i<1 || i>p->nzVar ){
64053     return 0;
64054   }
64055   return p->azVar[i-1];
64056 }
64057
64058 /*
64059 ** Given a wildcard parameter name, return the index of the variable
64060 ** with that name.  If there is no variable with the given name,
64061 ** return 0.
64062 */
64063 SQLCIPHER_PRIVATE int sqlcipher3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64064   int i;
64065   if( p==0 ){
64066     return 0;
64067   }
64068   if( zName ){
64069     for(i=0; i<p->nzVar; i++){
64070       const char *z = p->azVar[i];
64071       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
64072         return i+1;
64073       }
64074     }
64075   }
64076   return 0;
64077 }
64078 SQLCIPHER_API int sqlcipher3_bind_parameter_index(sqlcipher3_stmt *pStmt, const char *zName){
64079   return sqlcipher3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlcipher3Strlen30(zName));
64080 }
64081
64082 /*
64083 ** Transfer all bindings from the first statement over to the second.
64084 */
64085 SQLCIPHER_PRIVATE int sqlcipher3TransferBindings(sqlcipher3_stmt *pFromStmt, sqlcipher3_stmt *pToStmt){
64086   Vdbe *pFrom = (Vdbe*)pFromStmt;
64087   Vdbe *pTo = (Vdbe*)pToStmt;
64088   int i;
64089   assert( pTo->db==pFrom->db );
64090   assert( pTo->nVar==pFrom->nVar );
64091   sqlcipher3_mutex_enter(pTo->db->mutex);
64092   for(i=0; i<pFrom->nVar; i++){
64093     sqlcipher3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64094   }
64095   sqlcipher3_mutex_leave(pTo->db->mutex);
64096   return SQLCIPHER_OK;
64097 }
64098
64099 #ifndef SQLCIPHER_OMIT_DEPRECATED
64100 /*
64101 ** Deprecated external interface.  Internal/core SQLite code
64102 ** should call sqlcipher3TransferBindings.
64103 **
64104 ** Is is misuse to call this routine with statements from different
64105 ** database connections.  But as this is a deprecated interface, we
64106 ** will not bother to check for that condition.
64107 **
64108 ** If the two statements contain a different number of bindings, then
64109 ** an SQLCIPHER_ERROR is returned.  Nothing else can go wrong, so otherwise
64110 ** SQLCIPHER_OK is returned.
64111 */
64112 SQLCIPHER_API int sqlcipher3_transfer_bindings(sqlcipher3_stmt *pFromStmt, sqlcipher3_stmt *pToStmt){
64113   Vdbe *pFrom = (Vdbe*)pFromStmt;
64114   Vdbe *pTo = (Vdbe*)pToStmt;
64115   if( pFrom->nVar!=pTo->nVar ){
64116     return SQLCIPHER_ERROR;
64117   }
64118   if( pTo->isPrepareV2 && pTo->expmask ){
64119     pTo->expired = 1;
64120   }
64121   if( pFrom->isPrepareV2 && pFrom->expmask ){
64122     pFrom->expired = 1;
64123   }
64124   return sqlcipher3TransferBindings(pFromStmt, pToStmt);
64125 }
64126 #endif
64127
64128 /*
64129 ** Return the sqlcipher3* database handle to which the prepared statement given
64130 ** in the argument belongs.  This is the same database handle that was
64131 ** the first argument to the sqlcipher3_prepare() that was used to create
64132 ** the statement in the first place.
64133 */
64134 SQLCIPHER_API sqlcipher3 *sqlcipher3_db_handle(sqlcipher3_stmt *pStmt){
64135   return pStmt ? ((Vdbe*)pStmt)->db : 0;
64136 }
64137
64138 /*
64139 ** Return true if the prepared statement is guaranteed to not modify the
64140 ** database.
64141 */
64142 SQLCIPHER_API int sqlcipher3_stmt_readonly(sqlcipher3_stmt *pStmt){
64143   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64144 }
64145
64146 /*
64147 ** Return a pointer to the next prepared statement after pStmt associated
64148 ** with database connection pDb.  If pStmt is NULL, return the first
64149 ** prepared statement for the database connection.  Return NULL if there
64150 ** are no more.
64151 */
64152 SQLCIPHER_API sqlcipher3_stmt *sqlcipher3_next_stmt(sqlcipher3 *pDb, sqlcipher3_stmt *pStmt){
64153   sqlcipher3_stmt *pNext;
64154   sqlcipher3_mutex_enter(pDb->mutex);
64155   if( pStmt==0 ){
64156     pNext = (sqlcipher3_stmt*)pDb->pVdbe;
64157   }else{
64158     pNext = (sqlcipher3_stmt*)((Vdbe*)pStmt)->pNext;
64159   }
64160   sqlcipher3_mutex_leave(pDb->mutex);
64161   return pNext;
64162 }
64163
64164 /*
64165 ** Return the value of a status counter for a prepared statement
64166 */
64167 SQLCIPHER_API int sqlcipher3_stmt_status(sqlcipher3_stmt *pStmt, int op, int resetFlag){
64168   Vdbe *pVdbe = (Vdbe*)pStmt;
64169   int v = pVdbe->aCounter[op-1];
64170   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64171   return v;
64172 }
64173
64174 /************** End of vdbeapi.c *********************************************/
64175 /************** Begin file vdbetrace.c ***************************************/
64176 /*
64177 ** 2009 November 25
64178 **
64179 ** The author disclaims copyright to this source code.  In place of
64180 ** a legal notice, here is a blessing:
64181 **
64182 **    May you do good and not evil.
64183 **    May you find forgiveness for yourself and forgive others.
64184 **    May you share freely, never taking more than you give.
64185 **
64186 *************************************************************************
64187 **
64188 ** This file contains code used to insert the values of host parameters
64189 ** (aka "wildcards") into the SQL text output by sqlcipher3_trace().
64190 */
64191
64192 #ifndef SQLCIPHER_OMIT_TRACE
64193
64194 /*
64195 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64196 ** bytes in this text up to but excluding the first character in
64197 ** a host parameter.  If the text contains no host parameters, return
64198 ** the total number of bytes in the text.
64199 */
64200 static int findNextHostParameter(const char *zSql, int *pnToken){
64201   int tokenType;
64202   int nTotal = 0;
64203   int n;
64204
64205   *pnToken = 0;
64206   while( zSql[0] ){
64207     n = sqlcipher3GetToken((u8*)zSql, &tokenType);
64208     assert( n>0 && tokenType!=TK_ILLEGAL );
64209     if( tokenType==TK_VARIABLE ){
64210       *pnToken = n;
64211       break;
64212     }
64213     nTotal += n;
64214     zSql += n;
64215   }
64216   return nTotal;
64217 }
64218
64219 /*
64220 ** This function returns a pointer to a nul-terminated string in memory
64221 ** obtained from sqlcipher3DbMalloc(). If sqlcipher3.vdbeExecCnt is 1, then the
64222 ** string contains a copy of zRawSql but with host parameters expanded to 
64223 ** their current bindings. Or, if sqlcipher3.vdbeExecCnt is greater than 1, 
64224 ** then the returned string holds a copy of zRawSql with "-- " prepended
64225 ** to each line of text.
64226 **
64227 ** The calling function is responsible for making sure the memory returned
64228 ** is eventually freed.
64229 **
64230 ** ALGORITHM:  Scan the input string looking for host parameters in any of
64231 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64232 ** string literals, quoted identifier names, and comments.  For text forms,
64233 ** the host parameter index is found by scanning the perpared
64234 ** statement for the corresponding OP_Variable opcode.  Once the host
64235 ** parameter index is known, locate the value in p->aVar[].  Then render
64236 ** the value as a literal in place of the host parameter name.
64237 */
64238 SQLCIPHER_PRIVATE char *sqlcipher3VdbeExpandSql(
64239   Vdbe *p,                 /* The prepared statement being evaluated */
64240   const char *zRawSql      /* Raw text of the SQL statement */
64241 ){
64242   sqlcipher3 *db;             /* The database connection */
64243   int idx = 0;             /* Index of a host parameter */
64244   int nextIndex = 1;       /* Index of next ? host parameter */
64245   int n;                   /* Length of a token prefix */
64246   int nToken;              /* Length of the parameter token */
64247   int i;                   /* Loop counter */
64248   Mem *pVar;               /* Value of a host parameter */
64249   StrAccum out;            /* Accumulate the output here */
64250   char zBase[100];         /* Initial working space */
64251
64252   db = p->db;
64253   sqlcipher3StrAccumInit(&out, zBase, sizeof(zBase), 
64254                       db->aLimit[SQLCIPHER_LIMIT_LENGTH]);
64255   out.db = db;
64256   if( db->vdbeExecCnt>1 ){
64257     while( *zRawSql ){
64258       const char *zStart = zRawSql;
64259       while( *(zRawSql++)!='\n' && *zRawSql );
64260       sqlcipher3StrAccumAppend(&out, "-- ", 3);
64261       sqlcipher3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64262     }
64263   }else{
64264     while( zRawSql[0] ){
64265       n = findNextHostParameter(zRawSql, &nToken);
64266       assert( n>0 );
64267       sqlcipher3StrAccumAppend(&out, zRawSql, n);
64268       zRawSql += n;
64269       assert( zRawSql[0] || nToken==0 );
64270       if( nToken==0 ) break;
64271       if( zRawSql[0]=='?' ){
64272         if( nToken>1 ){
64273           assert( sqlcipher3Isdigit(zRawSql[1]) );
64274           sqlcipher3GetInt32(&zRawSql[1], &idx);
64275         }else{
64276           idx = nextIndex;
64277         }
64278       }else{
64279         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64280         testcase( zRawSql[0]==':' );
64281         testcase( zRawSql[0]=='$' );
64282         testcase( zRawSql[0]=='@' );
64283         idx = sqlcipher3VdbeParameterIndex(p, zRawSql, nToken);
64284         assert( idx>0 );
64285       }
64286       zRawSql += nToken;
64287       nextIndex = idx + 1;
64288       assert( idx>0 && idx<=p->nVar );
64289       pVar = &p->aVar[idx-1];
64290       if( pVar->flags & MEM_Null ){
64291         sqlcipher3StrAccumAppend(&out, "NULL", 4);
64292       }else if( pVar->flags & MEM_Int ){
64293         sqlcipher3XPrintf(&out, "%lld", pVar->u.i);
64294       }else if( pVar->flags & MEM_Real ){
64295         sqlcipher3XPrintf(&out, "%!.15g", pVar->r);
64296       }else if( pVar->flags & MEM_Str ){
64297 #ifndef SQLCIPHER_OMIT_UTF16
64298         u8 enc = ENC(db);
64299         if( enc!=SQLCIPHER_UTF8 ){
64300           Mem utf8;
64301           memset(&utf8, 0, sizeof(utf8));
64302           utf8.db = db;
64303           sqlcipher3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLCIPHER_STATIC);
64304           sqlcipher3VdbeChangeEncoding(&utf8, SQLCIPHER_UTF8);
64305           sqlcipher3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
64306           sqlcipher3VdbeMemRelease(&utf8);
64307         }else
64308 #endif
64309         {
64310           sqlcipher3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
64311         }
64312       }else if( pVar->flags & MEM_Zero ){
64313         sqlcipher3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64314       }else{
64315         assert( pVar->flags & MEM_Blob );
64316         sqlcipher3StrAccumAppend(&out, "x'", 2);
64317         for(i=0; i<pVar->n; i++){
64318           sqlcipher3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64319         }
64320         sqlcipher3StrAccumAppend(&out, "'", 1);
64321       }
64322     }
64323   }
64324   return sqlcipher3StrAccumFinish(&out);
64325 }
64326
64327 #endif /* #ifndef SQLCIPHER_OMIT_TRACE */
64328
64329 /************** End of vdbetrace.c *******************************************/
64330 /************** Begin file vdbe.c ********************************************/
64331 /*
64332 ** 2001 September 15
64333 **
64334 ** The author disclaims copyright to this source code.  In place of
64335 ** a legal notice, here is a blessing:
64336 **
64337 **    May you do good and not evil.
64338 **    May you find forgiveness for yourself and forgive others.
64339 **    May you share freely, never taking more than you give.
64340 **
64341 *************************************************************************
64342 ** The code in this file implements execution method of the 
64343 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
64344 ** handles housekeeping details such as creating and deleting
64345 ** VDBE instances.  This file is solely interested in executing
64346 ** the VDBE program.
64347 **
64348 ** In the external interface, an "sqlcipher3_stmt*" is an opaque pointer
64349 ** to a VDBE.
64350 **
64351 ** The SQL parser generates a program which is then executed by
64352 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
64353 ** similar in form to assembly language.  The program consists of
64354 ** a linear sequence of operations.  Each operation has an opcode 
64355 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
64356 ** is a null-terminated string.  Operand P5 is an unsigned character.
64357 ** Few opcodes use all 5 operands.
64358 **
64359 ** Computation results are stored on a set of registers numbered beginning
64360 ** with 1 and going up to Vdbe.nMem.  Each register can store
64361 ** either an integer, a null-terminated string, a floating point
64362 ** number, or the SQL "NULL" value.  An implicit conversion from one
64363 ** type to the other occurs as necessary.
64364 ** 
64365 ** Most of the code in this file is taken up by the sqlcipher3VdbeExec()
64366 ** function which does the work of interpreting a VDBE program.
64367 ** But other routines are also provided to help in building up
64368 ** a program instruction by instruction.
64369 **
64370 ** Various scripts scan this source file in order to generate HTML
64371 ** documentation, headers files, or other derived files.  The formatting
64372 ** of the code in this file is, therefore, important.  See other comments
64373 ** in this file for details.  If in doubt, do not deviate from existing
64374 ** commenting and indentation practices when changing or adding code.
64375 */
64376
64377 /*
64378 ** Invoke this macro on memory cells just prior to changing the
64379 ** value of the cell.  This macro verifies that shallow copies are
64380 ** not misused.
64381 */
64382 #ifdef SQLCIPHER_DEBUG
64383 # define memAboutToChange(P,M) sqlcipher3VdbeMemPrepareToChange(P,M)
64384 #else
64385 # define memAboutToChange(P,M)
64386 #endif
64387
64388 /*
64389 ** The following global variable is incremented every time a cursor
64390 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
64391 ** procedures use this information to make sure that indices are
64392 ** working correctly.  This variable has no function other than to
64393 ** help verify the correct operation of the library.
64394 */
64395 #ifdef SQLCIPHER_TEST
64396 SQLCIPHER_API int sqlcipher3_search_count = 0;
64397 #endif
64398
64399 /*
64400 ** When this global variable is positive, it gets decremented once before
64401 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
64402 ** field of the sqlcipher3 structure is set in order to simulate and interrupt.
64403 **
64404 ** This facility is used for testing purposes only.  It does not function
64405 ** in an ordinary build.
64406 */
64407 #ifdef SQLCIPHER_TEST
64408 SQLCIPHER_API int sqlcipher3_interrupt_count = 0;
64409 #endif
64410
64411 /*
64412 ** The next global variable is incremented each type the OP_Sort opcode
64413 ** is executed.  The test procedures use this information to make sure that
64414 ** sorting is occurring or not occurring at appropriate times.   This variable
64415 ** has no function other than to help verify the correct operation of the
64416 ** library.
64417 */
64418 #ifdef SQLCIPHER_TEST
64419 SQLCIPHER_API int sqlcipher3_sort_count = 0;
64420 #endif
64421
64422 /*
64423 ** The next global variable records the size of the largest MEM_Blob
64424 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
64425 ** use this information to make sure that the zero-blob functionality
64426 ** is working correctly.   This variable has no function other than to
64427 ** help verify the correct operation of the library.
64428 */
64429 #ifdef SQLCIPHER_TEST
64430 SQLCIPHER_API int sqlcipher3_max_blobsize = 0;
64431 static void updateMaxBlobsize(Mem *p){
64432   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlcipher3_max_blobsize ){
64433     sqlcipher3_max_blobsize = p->n;
64434   }
64435 }
64436 #endif
64437
64438 /*
64439 ** The next global variable is incremented each type the OP_Found opcode
64440 ** is executed. This is used to test whether or not the foreign key
64441 ** operation implemented using OP_FkIsZero is working. This variable
64442 ** has no function other than to help verify the correct operation of the
64443 ** library.
64444 */
64445 #ifdef SQLCIPHER_TEST
64446 SQLCIPHER_API int sqlcipher3_found_count = 0;
64447 #endif
64448
64449 /*
64450 ** Test a register to see if it exceeds the current maximum blob size.
64451 ** If it does, record the new maximum blob size.
64452 */
64453 #if defined(SQLCIPHER_TEST) && !defined(SQLCIPHER_OMIT_BUILTIN_TEST)
64454 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
64455 #else
64456 # define UPDATE_MAX_BLOBSIZE(P)
64457 #endif
64458
64459 /*
64460 ** Convert the given register into a string if it isn't one
64461 ** already. Return non-zero if a malloc() fails.
64462 */
64463 #define Stringify(P, enc) \
64464    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlcipher3VdbeMemStringify(P,enc)) \
64465      { goto no_mem; }
64466
64467 /*
64468 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
64469 ** a pointer to a dynamically allocated string where some other entity
64470 ** is responsible for deallocating that string.  Because the register
64471 ** does not control the string, it might be deleted without the register
64472 ** knowing it.
64473 **
64474 ** This routine converts an ephemeral string into a dynamically allocated
64475 ** string that the register itself controls.  In other words, it
64476 ** converts an MEM_Ephem string into an MEM_Dyn string.
64477 */
64478 #define Deephemeralize(P) \
64479    if( ((P)->flags&MEM_Ephem)!=0 \
64480        && sqlcipher3VdbeMemMakeWriteable(P) ){ goto no_mem;}
64481
64482 /*
64483 ** Call sqlcipher3VdbeMemExpandBlob() on the supplied value (type Mem*)
64484 ** P if required.
64485 */
64486 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlcipher3VdbeMemExpandBlob(P):0)
64487
64488 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
64489 #ifdef SQLCIPHER_OMIT_MERGE_SORT
64490 # define isSorter(x) 0
64491 #else
64492 # define isSorter(x) ((x)->pSorter!=0)
64493 #endif
64494
64495 /*
64496 ** Argument pMem points at a register that will be passed to a
64497 ** user-defined function or returned to the user as the result of a query.
64498 ** This routine sets the pMem->type variable used by the sqlcipher3_value_*() 
64499 ** routines.
64500 */
64501 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemStoreType(Mem *pMem){
64502   int flags = pMem->flags;
64503   if( flags & MEM_Null ){
64504     pMem->type = SQLCIPHER_NULL;
64505   }
64506   else if( flags & MEM_Int ){
64507     pMem->type = SQLCIPHER_INTEGER;
64508   }
64509   else if( flags & MEM_Real ){
64510     pMem->type = SQLCIPHER_FLOAT;
64511   }
64512   else if( flags & MEM_Str ){
64513     pMem->type = SQLCIPHER_TEXT;
64514   }else{
64515     pMem->type = SQLCIPHER_BLOB;
64516   }
64517 }
64518
64519 /*
64520 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
64521 ** if we run out of memory.
64522 */
64523 static VdbeCursor *allocateCursor(
64524   Vdbe *p,              /* The virtual machine */
64525   int iCur,             /* Index of the new VdbeCursor */
64526   int nField,           /* Number of fields in the table or index */
64527   int iDb,              /* When database the cursor belongs to, or -1 */
64528   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
64529 ){
64530   /* Find the memory cell that will be used to store the blob of memory
64531   ** required for this VdbeCursor structure. It is convenient to use a 
64532   ** vdbe memory cell to manage the memory allocation required for a
64533   ** VdbeCursor structure for the following reasons:
64534   **
64535   **   * Sometimes cursor numbers are used for a couple of different
64536   **     purposes in a vdbe program. The different uses might require
64537   **     different sized allocations. Memory cells provide growable
64538   **     allocations.
64539   **
64540   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
64541   **     be freed lazily via the sqlcipher3_release_memory() API. This
64542   **     minimizes the number of malloc calls made by the system.
64543   **
64544   ** Memory cells for cursors are allocated at the top of the address
64545   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
64546   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
64547   */
64548   Mem *pMem = &p->aMem[p->nMem-iCur];
64549
64550   int nByte;
64551   VdbeCursor *pCx = 0;
64552   nByte = 
64553       ROUND8(sizeof(VdbeCursor)) + 
64554       (isBtreeCursor?sqlcipher3BtreeCursorSize():0) + 
64555       2*nField*sizeof(u32);
64556
64557   assert( iCur<p->nCursor );
64558   if( p->apCsr[iCur] ){
64559     sqlcipher3VdbeFreeCursor(p, p->apCsr[iCur]);
64560     p->apCsr[iCur] = 0;
64561   }
64562   if( SQLCIPHER_OK==sqlcipher3VdbeMemGrow(pMem, nByte, 0) ){
64563     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
64564     memset(pCx, 0, sizeof(VdbeCursor));
64565     pCx->iDb = iDb;
64566     pCx->nField = nField;
64567     if( nField ){
64568       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
64569     }
64570     if( isBtreeCursor ){
64571       pCx->pCursor = (BtCursor*)
64572           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
64573       sqlcipher3BtreeCursorZero(pCx->pCursor);
64574     }
64575   }
64576   return pCx;
64577 }
64578
64579 /*
64580 ** Try to convert a value into a numeric representation if we can
64581 ** do so without loss of information.  In other words, if the string
64582 ** looks like a number, convert it into a number.  If it does not
64583 ** look like a number, leave it alone.
64584 */
64585 static void applyNumericAffinity(Mem *pRec){
64586   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
64587     double rValue;
64588     i64 iValue;
64589     u8 enc = pRec->enc;
64590     if( (pRec->flags&MEM_Str)==0 ) return;
64591     if( sqlcipher3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
64592     if( 0==sqlcipher3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
64593       pRec->u.i = iValue;
64594       pRec->flags |= MEM_Int;
64595     }else{
64596       pRec->r = rValue;
64597       pRec->flags |= MEM_Real;
64598     }
64599   }
64600 }
64601
64602 /*
64603 ** Processing is determine by the affinity parameter:
64604 **
64605 ** SQLCIPHER_AFF_INTEGER:
64606 ** SQLCIPHER_AFF_REAL:
64607 ** SQLCIPHER_AFF_NUMERIC:
64608 **    Try to convert pRec to an integer representation or a 
64609 **    floating-point representation if an integer representation
64610 **    is not possible.  Note that the integer representation is
64611 **    always preferred, even if the affinity is REAL, because
64612 **    an integer representation is more space efficient on disk.
64613 **
64614 ** SQLCIPHER_AFF_TEXT:
64615 **    Convert pRec to a text representation.
64616 **
64617 ** SQLCIPHER_AFF_NONE:
64618 **    No-op.  pRec is unchanged.
64619 */
64620 static void applyAffinity(
64621   Mem *pRec,          /* The value to apply affinity to */
64622   char affinity,      /* The affinity to be applied */
64623   u8 enc              /* Use this text encoding */
64624 ){
64625   if( affinity==SQLCIPHER_AFF_TEXT ){
64626     /* Only attempt the conversion to TEXT if there is an integer or real
64627     ** representation (blob and NULL do not get converted) but no string
64628     ** representation.
64629     */
64630     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
64631       sqlcipher3VdbeMemStringify(pRec, enc);
64632     }
64633     pRec->flags &= ~(MEM_Real|MEM_Int);
64634   }else if( affinity!=SQLCIPHER_AFF_NONE ){
64635     assert( affinity==SQLCIPHER_AFF_INTEGER || affinity==SQLCIPHER_AFF_REAL
64636              || affinity==SQLCIPHER_AFF_NUMERIC );
64637     applyNumericAffinity(pRec);
64638     if( pRec->flags & MEM_Real ){
64639       sqlcipher3VdbeIntegerAffinity(pRec);
64640     }
64641   }
64642 }
64643
64644 /*
64645 ** Try to convert the type of a function argument or a result column
64646 ** into a numeric representation.  Use either INTEGER or REAL whichever
64647 ** is appropriate.  But only do the conversion if it is possible without
64648 ** loss of information and return the revised type of the argument.
64649 */
64650 SQLCIPHER_API int sqlcipher3_value_numeric_type(sqlcipher3_value *pVal){
64651   Mem *pMem = (Mem*)pVal;
64652   if( pMem->type==SQLCIPHER_TEXT ){
64653     applyNumericAffinity(pMem);
64654     sqlcipher3VdbeMemStoreType(pMem);
64655   }
64656   return pMem->type;
64657 }
64658
64659 /*
64660 ** Exported version of applyAffinity(). This one works on sqlcipher3_value*, 
64661 ** not the internal Mem* type.
64662 */
64663 SQLCIPHER_PRIVATE void sqlcipher3ValueApplyAffinity(
64664   sqlcipher3_value *pVal, 
64665   u8 affinity, 
64666   u8 enc
64667 ){
64668   applyAffinity((Mem *)pVal, affinity, enc);
64669 }
64670
64671 #ifdef SQLCIPHER_DEBUG
64672 /*
64673 ** Write a nice string representation of the contents of cell pMem
64674 ** into buffer zBuf, length nBuf.
64675 */
64676 SQLCIPHER_PRIVATE void sqlcipher3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
64677   char *zCsr = zBuf;
64678   int f = pMem->flags;
64679
64680   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
64681
64682   if( f&MEM_Blob ){
64683     int i;
64684     char c;
64685     if( f & MEM_Dyn ){
64686       c = 'z';
64687       assert( (f & (MEM_Static|MEM_Ephem))==0 );
64688     }else if( f & MEM_Static ){
64689       c = 't';
64690       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64691     }else if( f & MEM_Ephem ){
64692       c = 'e';
64693       assert( (f & (MEM_Static|MEM_Dyn))==0 );
64694     }else{
64695       c = 's';
64696     }
64697
64698     sqlcipher3_snprintf(100, zCsr, "%c", c);
64699     zCsr += sqlcipher3Strlen30(zCsr);
64700     sqlcipher3_snprintf(100, zCsr, "%d[", pMem->n);
64701     zCsr += sqlcipher3Strlen30(zCsr);
64702     for(i=0; i<16 && i<pMem->n; i++){
64703       sqlcipher3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
64704       zCsr += sqlcipher3Strlen30(zCsr);
64705     }
64706     for(i=0; i<16 && i<pMem->n; i++){
64707       char z = pMem->z[i];
64708       if( z<32 || z>126 ) *zCsr++ = '.';
64709       else *zCsr++ = z;
64710     }
64711
64712     sqlcipher3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
64713     zCsr += sqlcipher3Strlen30(zCsr);
64714     if( f & MEM_Zero ){
64715       sqlcipher3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
64716       zCsr += sqlcipher3Strlen30(zCsr);
64717     }
64718     *zCsr = '\0';
64719   }else if( f & MEM_Str ){
64720     int j, k;
64721     zBuf[0] = ' ';
64722     if( f & MEM_Dyn ){
64723       zBuf[1] = 'z';
64724       assert( (f & (MEM_Static|MEM_Ephem))==0 );
64725     }else if( f & MEM_Static ){
64726       zBuf[1] = 't';
64727       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64728     }else if( f & MEM_Ephem ){
64729       zBuf[1] = 'e';
64730       assert( (f & (MEM_Static|MEM_Dyn))==0 );
64731     }else{
64732       zBuf[1] = 's';
64733     }
64734     k = 2;
64735     sqlcipher3_snprintf(100, &zBuf[k], "%d", pMem->n);
64736     k += sqlcipher3Strlen30(&zBuf[k]);
64737     zBuf[k++] = '[';
64738     for(j=0; j<15 && j<pMem->n; j++){
64739       u8 c = pMem->z[j];
64740       if( c>=0x20 && c<0x7f ){
64741         zBuf[k++] = c;
64742       }else{
64743         zBuf[k++] = '.';
64744       }
64745     }
64746     zBuf[k++] = ']';
64747     sqlcipher3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
64748     k += sqlcipher3Strlen30(&zBuf[k]);
64749     zBuf[k++] = 0;
64750   }
64751 }
64752 #endif
64753
64754 #ifdef SQLCIPHER_DEBUG
64755 /*
64756 ** Print the value of a register for tracing purposes:
64757 */
64758 static void memTracePrint(FILE *out, Mem *p){
64759   if( p->flags & MEM_Null ){
64760     fprintf(out, " NULL");
64761   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
64762     fprintf(out, " si:%lld", p->u.i);
64763   }else if( p->flags & MEM_Int ){
64764     fprintf(out, " i:%lld", p->u.i);
64765 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
64766   }else if( p->flags & MEM_Real ){
64767     fprintf(out, " r:%g", p->r);
64768 #endif
64769   }else if( p->flags & MEM_RowSet ){
64770     fprintf(out, " (rowset)");
64771   }else{
64772     char zBuf[200];
64773     sqlcipher3VdbeMemPrettyPrint(p, zBuf);
64774     fprintf(out, " ");
64775     fprintf(out, "%s", zBuf);
64776   }
64777 }
64778 static void registerTrace(FILE *out, int iReg, Mem *p){
64779   fprintf(out, "REG[%d] = ", iReg);
64780   memTracePrint(out, p);
64781   fprintf(out, "\n");
64782 }
64783 #endif
64784
64785 #ifdef SQLCIPHER_DEBUG
64786 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
64787 #else
64788 #  define REGISTER_TRACE(R,M)
64789 #endif
64790
64791
64792 #ifdef VDBE_PROFILE
64793
64794 /* 
64795 ** hwtime.h contains inline assembler code for implementing 
64796 ** high-performance timing routines.
64797 */
64798 /************** Include hwtime.h in the middle of vdbe.c *********************/
64799 /************** Begin file hwtime.h ******************************************/
64800 /*
64801 ** 2008 May 27
64802 **
64803 ** The author disclaims copyright to this source code.  In place of
64804 ** a legal notice, here is a blessing:
64805 **
64806 **    May you do good and not evil.
64807 **    May you find forgiveness for yourself and forgive others.
64808 **    May you share freely, never taking more than you give.
64809 **
64810 ******************************************************************************
64811 **
64812 ** This file contains inline asm code for retrieving "high-performance"
64813 ** counters for x86 class CPUs.
64814 */
64815 #ifndef _HWTIME_H_
64816 #define _HWTIME_H_
64817
64818 /*
64819 ** The following routine only works on pentium-class (or newer) processors.
64820 ** It uses the RDTSC opcode to read the cycle count value out of the
64821 ** processor and returns that value.  This can be used for high-res
64822 ** profiling.
64823 */
64824 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
64825       (defined(i386) || defined(__i386__) || defined(_M_IX86))
64826
64827   #if defined(__GNUC__)
64828
64829   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
64830      unsigned int lo, hi;
64831      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
64832      return (sqlcipher_uint64)hi << 32 | lo;
64833   }
64834
64835   #elif defined(_MSC_VER)
64836
64837   __declspec(naked) __inline sqlcipher_uint64 __cdecl sqlcipher3Hwtime(void){
64838      __asm {
64839         rdtsc
64840         ret       ; return value at EDX:EAX
64841      }
64842   }
64843
64844   #endif
64845
64846 #elif (defined(__GNUC__) && defined(__x86_64__))
64847
64848   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
64849       unsigned long val;
64850       __asm__ __volatile__ ("rdtsc" : "=A" (val));
64851       return val;
64852   }
64853  
64854 #elif (defined(__GNUC__) && defined(__ppc__))
64855
64856   __inline__ sqlcipher_uint64 sqlcipher3Hwtime(void){
64857       unsigned long long retval;
64858       unsigned long junk;
64859       __asm__ __volatile__ ("\n\
64860           1:      mftbu   %1\n\
64861                   mftb    %L0\n\
64862                   mftbu   %0\n\
64863                   cmpw    %0,%1\n\
64864                   bne     1b"
64865                   : "=r" (retval), "=r" (junk));
64866       return retval;
64867   }
64868
64869 #else
64870
64871   #error Need implementation of sqlcipher3Hwtime() for your platform.
64872
64873   /*
64874   ** To compile without implementing sqlcipher3Hwtime() for your platform,
64875   ** you can remove the above #error and use the following
64876   ** stub function.  You will lose timing support for many
64877   ** of the debugging and testing utilities, but it should at
64878   ** least compile and run.
64879   */
64880 SQLCIPHER_PRIVATE   sqlcipher_uint64 sqlcipher3Hwtime(void){ return ((sqlcipher_uint64)0); }
64881
64882 #endif
64883
64884 #endif /* !defined(_HWTIME_H_) */
64885
64886 /************** End of hwtime.h **********************************************/
64887 /************** Continuing where we left off in vdbe.c ***********************/
64888
64889 #endif
64890
64891 /*
64892 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
64893 ** sqlcipher3_interrupt() routine has been called.  If it has been, then
64894 ** processing of the VDBE program is interrupted.
64895 **
64896 ** This macro added to every instruction that does a jump in order to
64897 ** implement a loop.  This test used to be on every single instruction,
64898 ** but that meant we more testing that we needed.  By only testing the
64899 ** flag on jump instructions, we get a (small) speed improvement.
64900 */
64901 #define CHECK_FOR_INTERRUPT \
64902    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
64903
64904
64905 #ifndef NDEBUG
64906 /*
64907 ** This function is only called from within an assert() expression. It
64908 ** checks that the sqlcipher3.nTransaction variable is correctly set to
64909 ** the number of non-transaction savepoints currently in the 
64910 ** linked list starting at sqlcipher3.pSavepoint.
64911 ** 
64912 ** Usage:
64913 **
64914 **     assert( checkSavepointCount(db) );
64915 */
64916 static int checkSavepointCount(sqlcipher3 *db){
64917   int n = 0;
64918   Savepoint *p;
64919   for(p=db->pSavepoint; p; p=p->pNext) n++;
64920   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
64921   return 1;
64922 }
64923 #endif
64924
64925 /*
64926 ** Transfer error message text from an sqlcipher3_vtab.zErrMsg (text stored
64927 ** in memory obtained from sqlcipher3_malloc) into a Vdbe.zErrMsg (text stored
64928 ** in memory obtained from sqlcipher3DbMalloc).
64929 */
64930 static void importVtabErrMsg(Vdbe *p, sqlcipher3_vtab *pVtab){
64931   sqlcipher3 *db = p->db;
64932   sqlcipher3DbFree(db, p->zErrMsg);
64933   p->zErrMsg = sqlcipher3DbStrDup(db, pVtab->zErrMsg);
64934   sqlcipher3_free(pVtab->zErrMsg);
64935   pVtab->zErrMsg = 0;
64936 }
64937
64938
64939 /*
64940 ** Execute as much of a VDBE program as we can then return.
64941 **
64942 ** sqlcipher3VdbeMakeReady() must be called before this routine in order to
64943 ** close the program with a final OP_Halt and to set up the callbacks
64944 ** and the error message pointer.
64945 **
64946 ** Whenever a row or result data is available, this routine will either
64947 ** invoke the result callback (if there is one) or return with
64948 ** SQLCIPHER_ROW.
64949 **
64950 ** If an attempt is made to open a locked database, then this routine
64951 ** will either invoke the busy callback (if there is one) or it will
64952 ** return SQLCIPHER_BUSY.
64953 **
64954 ** If an error occurs, an error message is written to memory obtained
64955 ** from sqlcipher3_malloc() and p->zErrMsg is made to point to that memory.
64956 ** The error code is stored in p->rc and this routine returns SQLCIPHER_ERROR.
64957 **
64958 ** If the callback ever returns non-zero, then the program exits
64959 ** immediately.  There will be no error message but the p->rc field is
64960 ** set to SQLCIPHER_ABORT and this routine will return SQLCIPHER_ERROR.
64961 **
64962 ** A memory allocation error causes p->rc to be set to SQLCIPHER_NOMEM and this
64963 ** routine to return SQLCIPHER_ERROR.
64964 **
64965 ** Other fatal errors return SQLCIPHER_ERROR.
64966 **
64967 ** After this routine has finished, sqlcipher3VdbeFinalize() should be
64968 ** used to clean up the mess that was left behind.
64969 */
64970 SQLCIPHER_PRIVATE int sqlcipher3VdbeExec(
64971   Vdbe *p                    /* The VDBE */
64972 ){
64973   int pc=0;                  /* The program counter */
64974   Op *aOp = p->aOp;          /* Copy of p->aOp */
64975   Op *pOp;                   /* Current operation */
64976   int rc = SQLCIPHER_OK;        /* Value to return */
64977   sqlcipher3 *db = p->db;       /* The database */
64978   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64979   u8 encoding = ENC(db);     /* The database encoding */
64980 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
64981   int checkProgress;         /* True if progress callbacks are enabled */
64982   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64983 #endif
64984   Mem *aMem = p->aMem;       /* Copy of p->aMem */
64985   Mem *pIn1 = 0;             /* 1st input operand */
64986   Mem *pIn2 = 0;             /* 2nd input operand */
64987   Mem *pIn3 = 0;             /* 3rd input operand */
64988   Mem *pOut = 0;             /* Output operand */
64989   int iCompare = 0;          /* Result of last OP_Compare operation */
64990   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
64991   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
64992 #ifdef VDBE_PROFILE
64993   u64 start;                 /* CPU clock count at start of opcode */
64994   int origPc;                /* Program counter at start of opcode */
64995 #endif
64996   /********************************************************************
64997   ** Automatically generated code
64998   **
64999   ** The following union is automatically generated by the
65000   ** vdbe-compress.tcl script.  The purpose of this union is to
65001   ** reduce the amount of stack space required by this function.
65002   ** See comments in the vdbe-compress.tcl script for details.
65003   */
65004   union vdbeExecUnion {
65005     struct OP_Yield_stack_vars {
65006       int pcDest;
65007     } aa;
65008     struct OP_Variable_stack_vars {
65009       Mem *pVar;       /* Value being transferred */
65010     } ab;
65011     struct OP_Move_stack_vars {
65012       char *zMalloc;   /* Holding variable for allocated memory */
65013       int n;           /* Number of registers left to copy */
65014       int p1;          /* Register to copy from */
65015       int p2;          /* Register to copy to */
65016     } ac;
65017     struct OP_ResultRow_stack_vars {
65018       Mem *pMem;
65019       int i;
65020     } ad;
65021     struct OP_Concat_stack_vars {
65022       i64 nByte;
65023     } ae;
65024     struct OP_Remainder_stack_vars {
65025       int flags;      /* Combined MEM_* flags from both inputs */
65026       i64 iA;         /* Integer value of left operand */
65027       i64 iB;         /* Integer value of right operand */
65028       double rA;      /* Real value of left operand */
65029       double rB;      /* Real value of right operand */
65030     } af;
65031     struct OP_Function_stack_vars {
65032       int i;
65033       Mem *pArg;
65034       sqlcipher3_context ctx;
65035       sqlcipher3_value **apVal;
65036       int n;
65037     } ag;
65038     struct OP_ShiftRight_stack_vars {
65039       i64 iA;
65040       u64 uA;
65041       i64 iB;
65042       u8 op;
65043     } ah;
65044     struct OP_Ge_stack_vars {
65045       int res;            /* Result of the comparison of pIn1 against pIn3 */
65046       char affinity;      /* Affinity to use for comparison */
65047       u16 flags1;         /* Copy of initial value of pIn1->flags */
65048       u16 flags3;         /* Copy of initial value of pIn3->flags */
65049     } ai;
65050     struct OP_Compare_stack_vars {
65051       int n;
65052       int i;
65053       int p1;
65054       int p2;
65055       const KeyInfo *pKeyInfo;
65056       int idx;
65057       CollSeq *pColl;    /* Collating sequence to use on this term */
65058       int bRev;          /* True for DESCENDING sort order */
65059     } aj;
65060     struct OP_Or_stack_vars {
65061       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65062       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65063     } ak;
65064     struct OP_IfNot_stack_vars {
65065       int c;
65066     } al;
65067     struct OP_Column_stack_vars {
65068       u32 payloadSize;   /* Number of bytes in the record */
65069       i64 payloadSize64; /* Number of bytes in the record */
65070       int p1;            /* P1 value of the opcode */
65071       int p2;            /* column number to retrieve */
65072       VdbeCursor *pC;    /* The VDBE cursor */
65073       char *zRec;        /* Pointer to complete record-data */
65074       BtCursor *pCrsr;   /* The BTree cursor */
65075       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65076       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65077       int nField;        /* number of fields in the record */
65078       int len;           /* The length of the serialized data for the column */
65079       int i;             /* Loop counter */
65080       char *zData;       /* Part of the record being decoded */
65081       Mem *pDest;        /* Where to write the extracted value */
65082       Mem sMem;          /* For storing the record being decoded */
65083       u8 *zIdx;          /* Index into header */
65084       u8 *zEndHdr;       /* Pointer to first byte after the header */
65085       u32 offset;        /* Offset into the data */
65086       u32 szField;       /* Number of bytes in the content of a field */
65087       int szHdr;         /* Size of the header size field at start of record */
65088       int avail;         /* Number of bytes of available data */
65089       u32 t;             /* A type code from the record header */
65090       Mem *pReg;         /* PseudoTable input register */
65091     } am;
65092     struct OP_Affinity_stack_vars {
65093       const char *zAffinity;   /* The affinity to be applied */
65094       char cAff;               /* A single character of affinity */
65095     } an;
65096     struct OP_MakeRecord_stack_vars {
65097       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65098       Mem *pRec;             /* The new record */
65099       u64 nData;             /* Number of bytes of data space */
65100       int nHdr;              /* Number of bytes of header space */
65101       i64 nByte;             /* Data space required for this record */
65102       int nZero;             /* Number of zero bytes at the end of the record */
65103       int nVarint;           /* Number of bytes in a varint */
65104       u32 serial_type;       /* Type field */
65105       Mem *pData0;           /* First field to be combined into the record */
65106       Mem *pLast;            /* Last field of the record */
65107       int nField;            /* Number of fields in the record */
65108       char *zAffinity;       /* The affinity string for the record */
65109       int file_format;       /* File format to use for encoding */
65110       int i;                 /* Space used in zNewRecord[] */
65111       int len;               /* Length of a field */
65112     } ao;
65113     struct OP_Count_stack_vars {
65114       i64 nEntry;
65115       BtCursor *pCrsr;
65116     } ap;
65117     struct OP_Savepoint_stack_vars {
65118       int p1;                         /* Value of P1 operand */
65119       char *zName;                    /* Name of savepoint */
65120       int nName;
65121       Savepoint *pNew;
65122       Savepoint *pSavepoint;
65123       Savepoint *pTmp;
65124       int iSavepoint;
65125       int ii;
65126     } aq;
65127     struct OP_AutoCommit_stack_vars {
65128       int desiredAutoCommit;
65129       int iRollback;
65130       int turnOnAC;
65131     } ar;
65132     struct OP_Transaction_stack_vars {
65133       Btree *pBt;
65134     } as;
65135     struct OP_ReadCookie_stack_vars {
65136       int iMeta;
65137       int iDb;
65138       int iCookie;
65139     } at;
65140     struct OP_SetCookie_stack_vars {
65141       Db *pDb;
65142     } au;
65143     struct OP_VerifyCookie_stack_vars {
65144       int iMeta;
65145       int iGen;
65146       Btree *pBt;
65147     } av;
65148     struct OP_OpenWrite_stack_vars {
65149       int nField;
65150       KeyInfo *pKeyInfo;
65151       int p2;
65152       int iDb;
65153       int wrFlag;
65154       Btree *pX;
65155       VdbeCursor *pCur;
65156       Db *pDb;
65157     } aw;
65158     struct OP_OpenEphemeral_stack_vars {
65159       VdbeCursor *pCx;
65160     } ax;
65161     struct OP_SorterOpen_stack_vars {
65162       VdbeCursor *pCx;
65163     } ay;
65164     struct OP_OpenPseudo_stack_vars {
65165       VdbeCursor *pCx;
65166     } az;
65167     struct OP_SeekGt_stack_vars {
65168       int res;
65169       int oc;
65170       VdbeCursor *pC;
65171       UnpackedRecord r;
65172       int nField;
65173       i64 iKey;      /* The rowid we are to seek to */
65174     } ba;
65175     struct OP_Seek_stack_vars {
65176       VdbeCursor *pC;
65177     } bb;
65178     struct OP_Found_stack_vars {
65179       int alreadyExists;
65180       VdbeCursor *pC;
65181       int res;
65182       char *pFree;
65183       UnpackedRecord *pIdxKey;
65184       UnpackedRecord r;
65185       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65186     } bc;
65187     struct OP_IsUnique_stack_vars {
65188       u16 ii;
65189       VdbeCursor *pCx;
65190       BtCursor *pCrsr;
65191       u16 nField;
65192       Mem *aMx;
65193       UnpackedRecord r;                  /* B-Tree index search key */
65194       i64 R;                             /* Rowid stored in register P3 */
65195     } bd;
65196     struct OP_NotExists_stack_vars {
65197       VdbeCursor *pC;
65198       BtCursor *pCrsr;
65199       int res;
65200       u64 iKey;
65201     } be;
65202     struct OP_NewRowid_stack_vars {
65203       i64 v;                 /* The new rowid */
65204       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65205       int res;               /* Result of an sqlcipher3BtreeLast() */
65206       int cnt;               /* Counter to limit the number of searches */
65207       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65208       VdbeFrame *pFrame;     /* Root frame of VDBE */
65209     } bf;
65210     struct OP_InsertInt_stack_vars {
65211       Mem *pData;       /* MEM cell holding data for the record to be inserted */
65212       Mem *pKey;        /* MEM cell holding key  for the record */
65213       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65214       VdbeCursor *pC;   /* Cursor to table into which insert is written */
65215       int nZero;        /* Number of zero-bytes to append */
65216       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65217       const char *zDb;  /* database name - used by the update hook */
65218       const char *zTbl; /* Table name - used by the opdate hook */
65219       int op;           /* Opcode for update hook: SQLCIPHER_UPDATE or SQLCIPHER_INSERT */
65220     } bg;
65221     struct OP_Delete_stack_vars {
65222       i64 iKey;
65223       VdbeCursor *pC;
65224     } bh;
65225     struct OP_SorterCompare_stack_vars {
65226       VdbeCursor *pC;
65227       int res;
65228     } bi;
65229     struct OP_SorterData_stack_vars {
65230       VdbeCursor *pC;
65231     } bj;
65232     struct OP_RowData_stack_vars {
65233       VdbeCursor *pC;
65234       BtCursor *pCrsr;
65235       u32 n;
65236       i64 n64;
65237     } bk;
65238     struct OP_Rowid_stack_vars {
65239       VdbeCursor *pC;
65240       i64 v;
65241       sqlcipher3_vtab *pVtab;
65242       const sqlcipher3_module *pModule;
65243     } bl;
65244     struct OP_NullRow_stack_vars {
65245       VdbeCursor *pC;
65246     } bm;
65247     struct OP_Last_stack_vars {
65248       VdbeCursor *pC;
65249       BtCursor *pCrsr;
65250       int res;
65251     } bn;
65252     struct OP_Rewind_stack_vars {
65253       VdbeCursor *pC;
65254       BtCursor *pCrsr;
65255       int res;
65256     } bo;
65257     struct OP_Next_stack_vars {
65258       VdbeCursor *pC;
65259       int res;
65260     } bp;
65261     struct OP_IdxInsert_stack_vars {
65262       VdbeCursor *pC;
65263       BtCursor *pCrsr;
65264       int nKey;
65265       const char *zKey;
65266     } bq;
65267     struct OP_IdxDelete_stack_vars {
65268       VdbeCursor *pC;
65269       BtCursor *pCrsr;
65270       int res;
65271       UnpackedRecord r;
65272     } br;
65273     struct OP_IdxRowid_stack_vars {
65274       BtCursor *pCrsr;
65275       VdbeCursor *pC;
65276       i64 rowid;
65277     } bs;
65278     struct OP_IdxGE_stack_vars {
65279       VdbeCursor *pC;
65280       int res;
65281       UnpackedRecord r;
65282     } bt;
65283     struct OP_Destroy_stack_vars {
65284       int iMoved;
65285       int iCnt;
65286       Vdbe *pVdbe;
65287       int iDb;
65288     } bu;
65289     struct OP_Clear_stack_vars {
65290       int nChange;
65291     } bv;
65292     struct OP_CreateTable_stack_vars {
65293       int pgno;
65294       int flags;
65295       Db *pDb;
65296     } bw;
65297     struct OP_ParseSchema_stack_vars {
65298       int iDb;
65299       const char *zMaster;
65300       char *zSql;
65301       InitData initData;
65302     } bx;
65303     struct OP_IntegrityCk_stack_vars {
65304       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65305       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65306       int j;          /* Loop counter */
65307       int nErr;       /* Number of errors reported */
65308       char *z;        /* Text of the error report */
65309       Mem *pnErr;     /* Register keeping track of errors remaining */
65310     } by;
65311     struct OP_RowSetRead_stack_vars {
65312       i64 val;
65313     } bz;
65314     struct OP_RowSetTest_stack_vars {
65315       int iSet;
65316       int exists;
65317     } ca;
65318     struct OP_Program_stack_vars {
65319       int nMem;               /* Number of memory registers for sub-program */
65320       int nByte;              /* Bytes of runtime space required for sub-program */
65321       Mem *pRt;               /* Register to allocate runtime space */
65322       Mem *pMem;              /* Used to iterate through memory cells */
65323       Mem *pEnd;              /* Last memory cell in new array */
65324       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65325       SubProgram *pProgram;   /* Sub-program to execute */
65326       void *t;                /* Token identifying trigger */
65327     } cb;
65328     struct OP_Param_stack_vars {
65329       VdbeFrame *pFrame;
65330       Mem *pIn;
65331     } cc;
65332     struct OP_MemMax_stack_vars {
65333       Mem *pIn1;
65334       VdbeFrame *pFrame;
65335     } cd;
65336     struct OP_AggStep_stack_vars {
65337       int n;
65338       int i;
65339       Mem *pMem;
65340       Mem *pRec;
65341       sqlcipher3_context ctx;
65342       sqlcipher3_value **apVal;
65343     } ce;
65344     struct OP_AggFinal_stack_vars {
65345       Mem *pMem;
65346     } cf;
65347     struct OP_Checkpoint_stack_vars {
65348       int i;                          /* Loop counter */
65349       int aRes[3];                    /* Results */
65350       Mem *pMem;                      /* Write results here */
65351     } cg;
65352     struct OP_JournalMode_stack_vars {
65353       Btree *pBt;                     /* Btree to change journal mode of */
65354       Pager *pPager;                  /* Pager associated with pBt */
65355       int eNew;                       /* New journal mode */
65356       int eOld;                       /* The old journal mode */
65357       const char *zFilename;          /* Name of database file for pPager */
65358     } ch;
65359     struct OP_IncrVacuum_stack_vars {
65360       Btree *pBt;
65361     } ci;
65362     struct OP_VBegin_stack_vars {
65363       VTable *pVTab;
65364     } cj;
65365     struct OP_VOpen_stack_vars {
65366       VdbeCursor *pCur;
65367       sqlcipher3_vtab_cursor *pVtabCursor;
65368       sqlcipher3_vtab *pVtab;
65369       sqlcipher3_module *pModule;
65370     } ck;
65371     struct OP_VFilter_stack_vars {
65372       int nArg;
65373       int iQuery;
65374       const sqlcipher3_module *pModule;
65375       Mem *pQuery;
65376       Mem *pArgc;
65377       sqlcipher3_vtab_cursor *pVtabCursor;
65378       sqlcipher3_vtab *pVtab;
65379       VdbeCursor *pCur;
65380       int res;
65381       int i;
65382       Mem **apArg;
65383     } cl;
65384     struct OP_VColumn_stack_vars {
65385       sqlcipher3_vtab *pVtab;
65386       const sqlcipher3_module *pModule;
65387       Mem *pDest;
65388       sqlcipher3_context sContext;
65389     } cm;
65390     struct OP_VNext_stack_vars {
65391       sqlcipher3_vtab *pVtab;
65392       const sqlcipher3_module *pModule;
65393       int res;
65394       VdbeCursor *pCur;
65395     } cn;
65396     struct OP_VRename_stack_vars {
65397       sqlcipher3_vtab *pVtab;
65398       Mem *pName;
65399     } co;
65400     struct OP_VUpdate_stack_vars {
65401       sqlcipher3_vtab *pVtab;
65402       sqlcipher3_module *pModule;
65403       int nArg;
65404       int i;
65405       sqlcipher_int64 rowid;
65406       Mem **apArg;
65407       Mem *pX;
65408     } cp;
65409     struct OP_Trace_stack_vars {
65410       char *zTrace;
65411       char *z;
65412     } cq;
65413   } u;
65414   /* End automatically generated code
65415   ********************************************************************/
65416
65417   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlcipher3_step() verifies this */
65418   sqlcipher3VdbeEnter(p);
65419   if( p->rc==SQLCIPHER_NOMEM ){
65420     /* This happens if a malloc() inside a call to sqlcipher3_column_text() or
65421     ** sqlcipher3_column_text16() failed.  */
65422     goto no_mem;
65423   }
65424   assert( p->rc==SQLCIPHER_OK || p->rc==SQLCIPHER_BUSY );
65425   p->rc = SQLCIPHER_OK;
65426   assert( p->explain==0 );
65427   p->pResultSet = 0;
65428   db->busyHandler.nBusy = 0;
65429   CHECK_FOR_INTERRUPT;
65430   sqlcipher3VdbeIOTraceSql(p);
65431 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
65432   checkProgress = db->xProgress!=0;
65433 #endif
65434 #ifdef SQLCIPHER_DEBUG
65435   sqlcipher3BeginBenignMalloc();
65436   if( p->pc==0  && (p->db->flags & SQLCIPHER_VdbeListing)!=0 ){
65437     int i;
65438     printf("VDBE Program Listing:\n");
65439     sqlcipher3VdbePrintSql(p);
65440     for(i=0; i<p->nOp; i++){
65441       sqlcipher3VdbePrintOp(stdout, i, &aOp[i]);
65442     }
65443   }
65444   sqlcipher3EndBenignMalloc();
65445 #endif
65446   for(pc=p->pc; rc==SQLCIPHER_OK; pc++){
65447     assert( pc>=0 && pc<p->nOp );
65448     if( db->mallocFailed ) goto no_mem;
65449 #ifdef VDBE_PROFILE
65450     origPc = pc;
65451     start = sqlcipher3Hwtime();
65452 #endif
65453     pOp = &aOp[pc];
65454
65455     /* Only allow tracing if SQLCIPHER_DEBUG is defined.
65456     */
65457 #ifdef SQLCIPHER_DEBUG
65458     if( p->trace ){
65459       if( pc==0 ){
65460         printf("VDBE Execution Trace:\n");
65461         sqlcipher3VdbePrintSql(p);
65462       }
65463       sqlcipher3VdbePrintOp(p->trace, pc, pOp);
65464     }
65465 #endif
65466       
65467
65468     /* Check to see if we need to simulate an interrupt.  This only happens
65469     ** if we have a special test build.
65470     */
65471 #ifdef SQLCIPHER_TEST
65472     if( sqlcipher3_interrupt_count>0 ){
65473       sqlcipher3_interrupt_count--;
65474       if( sqlcipher3_interrupt_count==0 ){
65475         sqlcipher3_interrupt(db);
65476       }
65477     }
65478 #endif
65479
65480 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
65481     /* Call the progress callback if it is configured and the required number
65482     ** of VDBE ops have been executed (either since this invocation of
65483     ** sqlcipher3VdbeExec() or since last time the progress callback was called).
65484     ** If the progress callback returns non-zero, exit the virtual machine with
65485     ** a return code SQLCIPHER_ABORT.
65486     */
65487     if( checkProgress ){
65488       if( db->nProgressOps==nProgressOps ){
65489         int prc;
65490         prc = db->xProgress(db->pProgressArg);
65491         if( prc!=0 ){
65492           rc = SQLCIPHER_INTERRUPT;
65493           goto vdbe_error_halt;
65494         }
65495         nProgressOps = 0;
65496       }
65497       nProgressOps++;
65498     }
65499 #endif
65500
65501     /* On any opcode with the "out2-prerelase" tag, free any
65502     ** external allocations out of mem[p2] and set mem[p2] to be
65503     ** an undefined integer.  Opcodes will either fill in the integer
65504     ** value or convert mem[p2] to a different type.
65505     */
65506     assert( pOp->opflags==sqlcipher3OpcodeProperty[pOp->opcode] );
65507     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
65508       assert( pOp->p2>0 );
65509       assert( pOp->p2<=p->nMem );
65510       pOut = &aMem[pOp->p2];
65511       memAboutToChange(p, pOut);
65512       MemReleaseExt(pOut);
65513       pOut->flags = MEM_Int;
65514     }
65515
65516     /* Sanity checking on other operands */
65517 #ifdef SQLCIPHER_DEBUG
65518     if( (pOp->opflags & OPFLG_IN1)!=0 ){
65519       assert( pOp->p1>0 );
65520       assert( pOp->p1<=p->nMem );
65521       assert( memIsValid(&aMem[pOp->p1]) );
65522       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
65523     }
65524     if( (pOp->opflags & OPFLG_IN2)!=0 ){
65525       assert( pOp->p2>0 );
65526       assert( pOp->p2<=p->nMem );
65527       assert( memIsValid(&aMem[pOp->p2]) );
65528       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
65529     }
65530     if( (pOp->opflags & OPFLG_IN3)!=0 ){
65531       assert( pOp->p3>0 );
65532       assert( pOp->p3<=p->nMem );
65533       assert( memIsValid(&aMem[pOp->p3]) );
65534       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
65535     }
65536     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
65537       assert( pOp->p2>0 );
65538       assert( pOp->p2<=p->nMem );
65539       memAboutToChange(p, &aMem[pOp->p2]);
65540     }
65541     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
65542       assert( pOp->p3>0 );
65543       assert( pOp->p3<=p->nMem );
65544       memAboutToChange(p, &aMem[pOp->p3]);
65545     }
65546 #endif
65547   
65548     switch( pOp->opcode ){
65549
65550 /*****************************************************************************
65551 ** What follows is a massive switch statement where each case implements a
65552 ** separate instruction in the virtual machine.  If we follow the usual
65553 ** indentation conventions, each case should be indented by 6 spaces.  But
65554 ** that is a lot of wasted space on the left margin.  So the code within
65555 ** the switch statement will break with convention and be flush-left. Another
65556 ** big comment (similar to this one) will mark the point in the code where
65557 ** we transition back to normal indentation.
65558 **
65559 ** The formatting of each case is important.  The makefile for SQLite
65560 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
65561 ** file looking for lines that begin with "case OP_".  The opcodes.h files
65562 ** will be filled with #defines that give unique integer values to each
65563 ** opcode and the opcodes.c file is filled with an array of strings where
65564 ** each string is the symbolic name for the corresponding opcode.  If the
65565 ** case statement is followed by a comment of the form "/# same as ... #/"
65566 ** that comment is used to determine the particular value of the opcode.
65567 **
65568 ** Other keywords in the comment that follows each case are used to
65569 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
65570 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
65571 ** the mkopcodeh.awk script for additional information.
65572 **
65573 ** Documentation about VDBE opcodes is generated by scanning this file
65574 ** for lines of that contain "Opcode:".  That line and all subsequent
65575 ** comment lines are used in the generation of the opcode.html documentation
65576 ** file.
65577 **
65578 ** SUMMARY:
65579 **
65580 **     Formatting is important to scripts that scan this file.
65581 **     Do not deviate from the formatting style currently in use.
65582 **
65583 *****************************************************************************/
65584
65585 /* Opcode:  Goto * P2 * * *
65586 **
65587 ** An unconditional jump to address P2.
65588 ** The next instruction executed will be 
65589 ** the one at index P2 from the beginning of
65590 ** the program.
65591 */
65592 case OP_Goto: {             /* jump */
65593   CHECK_FOR_INTERRUPT;
65594   pc = pOp->p2 - 1;
65595   break;
65596 }
65597
65598 /* Opcode:  Gosub P1 P2 * * *
65599 **
65600 ** Write the current address onto register P1
65601 ** and then jump to address P2.
65602 */
65603 case OP_Gosub: {            /* jump, in1 */
65604   pIn1 = &aMem[pOp->p1];
65605   assert( (pIn1->flags & MEM_Dyn)==0 );
65606   memAboutToChange(p, pIn1);
65607   pIn1->flags = MEM_Int;
65608   pIn1->u.i = pc;
65609   REGISTER_TRACE(pOp->p1, pIn1);
65610   pc = pOp->p2 - 1;
65611   break;
65612 }
65613
65614 /* Opcode:  Return P1 * * * *
65615 **
65616 ** Jump to the next instruction after the address in register P1.
65617 */
65618 case OP_Return: {           /* in1 */
65619   pIn1 = &aMem[pOp->p1];
65620   assert( pIn1->flags & MEM_Int );
65621   pc = (int)pIn1->u.i;
65622   break;
65623 }
65624
65625 /* Opcode:  Yield P1 * * * *
65626 **
65627 ** Swap the program counter with the value in register P1.
65628 */
65629 case OP_Yield: {            /* in1 */
65630 #if 0  /* local variables moved into u.aa */
65631   int pcDest;
65632 #endif /* local variables moved into u.aa */
65633   pIn1 = &aMem[pOp->p1];
65634   assert( (pIn1->flags & MEM_Dyn)==0 );
65635   pIn1->flags = MEM_Int;
65636   u.aa.pcDest = (int)pIn1->u.i;
65637   pIn1->u.i = pc;
65638   REGISTER_TRACE(pOp->p1, pIn1);
65639   pc = u.aa.pcDest;
65640   break;
65641 }
65642
65643 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
65644 **
65645 ** Check the value in register P3.  If it is NULL then Halt using
65646 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
65647 ** value in register P3 is not NULL, then this routine is a no-op.
65648 */
65649 case OP_HaltIfNull: {      /* in3 */
65650   pIn3 = &aMem[pOp->p3];
65651   if( (pIn3->flags & MEM_Null)==0 ) break;
65652   /* Fall through into OP_Halt */
65653 }
65654
65655 /* Opcode:  Halt P1 P2 * P4 *
65656 **
65657 ** Exit immediately.  All open cursors, etc are closed
65658 ** automatically.
65659 **
65660 ** P1 is the result code returned by sqlcipher3_exec(), sqlcipher3_reset(),
65661 ** or sqlcipher3_finalize().  For a normal halt, this should be SQLCIPHER_OK (0).
65662 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
65663 ** whether or not to rollback the current transaction.  Do not rollback
65664 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
65665 ** then back out all changes that have occurred during this execution of the
65666 ** VDBE, but do not rollback the transaction. 
65667 **
65668 ** If P4 is not null then it is an error message string.
65669 **
65670 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
65671 ** every program.  So a jump past the last instruction of the program
65672 ** is the same as executing Halt.
65673 */
65674 case OP_Halt: {
65675   if( pOp->p1==SQLCIPHER_OK && p->pFrame ){
65676     /* Halt the sub-program. Return control to the parent frame. */
65677     VdbeFrame *pFrame = p->pFrame;
65678     p->pFrame = pFrame->pParent;
65679     p->nFrame--;
65680     sqlcipher3VdbeSetChanges(db, p->nChange);
65681     pc = sqlcipher3VdbeFrameRestore(pFrame);
65682     lastRowid = db->lastRowid;
65683     if( pOp->p2==OE_Ignore ){
65684       /* Instruction pc is the OP_Program that invoked the sub-program 
65685       ** currently being halted. If the p2 instruction of this OP_Halt
65686       ** instruction is set to OE_Ignore, then the sub-program is throwing
65687       ** an IGNORE exception. In this case jump to the address specified
65688       ** as the p2 of the calling OP_Program.  */
65689       pc = p->aOp[pc].p2-1;
65690     }
65691     aOp = p->aOp;
65692     aMem = p->aMem;
65693     break;
65694   }
65695
65696   p->rc = pOp->p1;
65697   p->errorAction = (u8)pOp->p2;
65698   p->pc = pc;
65699   if( pOp->p4.z ){
65700     assert( p->rc!=SQLCIPHER_OK );
65701     sqlcipher3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
65702     testcase( sqlcipher3GlobalConfig.xLog!=0 );
65703     sqlcipher3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
65704   }else if( p->rc ){
65705     testcase( sqlcipher3GlobalConfig.xLog!=0 );
65706     sqlcipher3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
65707   }
65708   rc = sqlcipher3VdbeHalt(p);
65709   assert( rc==SQLCIPHER_BUSY || rc==SQLCIPHER_OK || rc==SQLCIPHER_ERROR );
65710   if( rc==SQLCIPHER_BUSY ){
65711     p->rc = rc = SQLCIPHER_BUSY;
65712   }else{
65713     assert( rc==SQLCIPHER_OK || p->rc==SQLCIPHER_CONSTRAINT );
65714     assert( rc==SQLCIPHER_OK || db->nDeferredCons>0 );
65715     rc = p->rc ? SQLCIPHER_ERROR : SQLCIPHER_DONE;
65716   }
65717   goto vdbe_return;
65718 }
65719
65720 /* Opcode: Integer P1 P2 * * *
65721 **
65722 ** The 32-bit integer value P1 is written into register P2.
65723 */
65724 case OP_Integer: {         /* out2-prerelease */
65725   pOut->u.i = pOp->p1;
65726   break;
65727 }
65728
65729 /* Opcode: Int64 * P2 * P4 *
65730 **
65731 ** P4 is a pointer to a 64-bit integer value.
65732 ** Write that value into register P2.
65733 */
65734 case OP_Int64: {           /* out2-prerelease */
65735   assert( pOp->p4.pI64!=0 );
65736   pOut->u.i = *pOp->p4.pI64;
65737   break;
65738 }
65739
65740 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
65741 /* Opcode: Real * P2 * P4 *
65742 **
65743 ** P4 is a pointer to a 64-bit floating point value.
65744 ** Write that value into register P2.
65745 */
65746 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
65747   pOut->flags = MEM_Real;
65748   assert( !sqlcipher3IsNaN(*pOp->p4.pReal) );
65749   pOut->r = *pOp->p4.pReal;
65750   break;
65751 }
65752 #endif
65753
65754 /* Opcode: String8 * P2 * P4 *
65755 **
65756 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
65757 ** into an OP_String before it is executed for the first time.
65758 */
65759 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
65760   assert( pOp->p4.z!=0 );
65761   pOp->opcode = OP_String;
65762   pOp->p1 = sqlcipher3Strlen30(pOp->p4.z);
65763
65764 #ifndef SQLCIPHER_OMIT_UTF16
65765   if( encoding!=SQLCIPHER_UTF8 ){
65766     rc = sqlcipher3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
65767     if( rc==SQLCIPHER_TOOBIG ) goto too_big;
65768     if( SQLCIPHER_OK!=sqlcipher3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
65769     assert( pOut->zMalloc==pOut->z );
65770     assert( pOut->flags & MEM_Dyn );
65771     pOut->zMalloc = 0;
65772     pOut->flags |= MEM_Static;
65773     pOut->flags &= ~MEM_Dyn;
65774     if( pOp->p4type==P4_DYNAMIC ){
65775       sqlcipher3DbFree(db, pOp->p4.z);
65776     }
65777     pOp->p4type = P4_DYNAMIC;
65778     pOp->p4.z = pOut->z;
65779     pOp->p1 = pOut->n;
65780   }
65781 #endif
65782   if( pOp->p1>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
65783     goto too_big;
65784   }
65785   /* Fall through to the next case, OP_String */
65786 }
65787   
65788 /* Opcode: String P1 P2 * P4 *
65789 **
65790 ** The string value P4 of length P1 (bytes) is stored in register P2.
65791 */
65792 case OP_String: {          /* out2-prerelease */
65793   assert( pOp->p4.z!=0 );
65794   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65795   pOut->z = pOp->p4.z;
65796   pOut->n = pOp->p1;
65797   pOut->enc = encoding;
65798   UPDATE_MAX_BLOBSIZE(pOut);
65799   break;
65800 }
65801
65802 /* Opcode: Null * P2 * * *
65803 **
65804 ** Write a NULL into register P2.
65805 */
65806 case OP_Null: {           /* out2-prerelease */
65807   pOut->flags = MEM_Null;
65808   break;
65809 }
65810
65811
65812 /* Opcode: Blob P1 P2 * P4
65813 **
65814 ** P4 points to a blob of data P1 bytes long.  Store this
65815 ** blob in register P2.
65816 */
65817 case OP_Blob: {                /* out2-prerelease */
65818   assert( pOp->p1 <= SQLCIPHER_MAX_LENGTH );
65819   sqlcipher3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
65820   pOut->enc = encoding;
65821   UPDATE_MAX_BLOBSIZE(pOut);
65822   break;
65823 }
65824
65825 /* Opcode: Variable P1 P2 * P4 *
65826 **
65827 ** Transfer the values of bound parameter P1 into register P2
65828 **
65829 ** If the parameter is named, then its name appears in P4 and P3==1.
65830 ** The P4 value is used by sqlcipher3_bind_parameter_name().
65831 */
65832 case OP_Variable: {            /* out2-prerelease */
65833 #if 0  /* local variables moved into u.ab */
65834   Mem *pVar;       /* Value being transferred */
65835 #endif /* local variables moved into u.ab */
65836
65837   assert( pOp->p1>0 && pOp->p1<=p->nVar );
65838   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
65839   u.ab.pVar = &p->aVar[pOp->p1 - 1];
65840   if( sqlcipher3VdbeMemTooBig(u.ab.pVar) ){
65841     goto too_big;
65842   }
65843   sqlcipher3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
65844   UPDATE_MAX_BLOBSIZE(pOut);
65845   break;
65846 }
65847
65848 /* Opcode: Move P1 P2 P3 * *
65849 **
65850 ** Move the values in register P1..P1+P3-1 over into
65851 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
65852 ** left holding a NULL.  It is an error for register ranges
65853 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
65854 */
65855 case OP_Move: {
65856 #if 0  /* local variables moved into u.ac */
65857   char *zMalloc;   /* Holding variable for allocated memory */
65858   int n;           /* Number of registers left to copy */
65859   int p1;          /* Register to copy from */
65860   int p2;          /* Register to copy to */
65861 #endif /* local variables moved into u.ac */
65862
65863   u.ac.n = pOp->p3;
65864   u.ac.p1 = pOp->p1;
65865   u.ac.p2 = pOp->p2;
65866   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
65867   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
65868
65869   pIn1 = &aMem[u.ac.p1];
65870   pOut = &aMem[u.ac.p2];
65871   while( u.ac.n-- ){
65872     assert( pOut<=&aMem[p->nMem] );
65873     assert( pIn1<=&aMem[p->nMem] );
65874     assert( memIsValid(pIn1) );
65875     memAboutToChange(p, pOut);
65876     u.ac.zMalloc = pOut->zMalloc;
65877     pOut->zMalloc = 0;
65878     sqlcipher3VdbeMemMove(pOut, pIn1);
65879 #ifdef SQLCIPHER_DEBUG
65880     if( pOut->pScopyFrom>=&aMem[u.ac.p1] && pOut->pScopyFrom<&aMem[u.ac.p1+pOp->p3] ){
65881       pOut->pScopyFrom += u.ac.p1 - pOp->p2;
65882     }
65883 #endif
65884     pIn1->zMalloc = u.ac.zMalloc;
65885     REGISTER_TRACE(u.ac.p2++, pOut);
65886     pIn1++;
65887     pOut++;
65888   }
65889   break;
65890 }
65891
65892 /* Opcode: Copy P1 P2 * * *
65893 **
65894 ** Make a copy of register P1 into register P2.
65895 **
65896 ** This instruction makes a deep copy of the value.  A duplicate
65897 ** is made of any string or blob constant.  See also OP_SCopy.
65898 */
65899 case OP_Copy: {             /* in1, out2 */
65900   pIn1 = &aMem[pOp->p1];
65901   pOut = &aMem[pOp->p2];
65902   assert( pOut!=pIn1 );
65903   sqlcipher3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65904   Deephemeralize(pOut);
65905   REGISTER_TRACE(pOp->p2, pOut);
65906   break;
65907 }
65908
65909 /* Opcode: SCopy P1 P2 * * *
65910 **
65911 ** Make a shallow copy of register P1 into register P2.
65912 **
65913 ** This instruction makes a shallow copy of the value.  If the value
65914 ** is a string or blob, then the copy is only a pointer to the
65915 ** original and hence if the original changes so will the copy.
65916 ** Worse, if the original is deallocated, the copy becomes invalid.
65917 ** Thus the program must guarantee that the original will not change
65918 ** during the lifetime of the copy.  Use OP_Copy to make a complete
65919 ** copy.
65920 */
65921 case OP_SCopy: {            /* in1, out2 */
65922   pIn1 = &aMem[pOp->p1];
65923   pOut = &aMem[pOp->p2];
65924   assert( pOut!=pIn1 );
65925   sqlcipher3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65926 #ifdef SQLCIPHER_DEBUG
65927   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65928 #endif
65929   REGISTER_TRACE(pOp->p2, pOut);
65930   break;
65931 }
65932
65933 /* Opcode: ResultRow P1 P2 * * *
65934 **
65935 ** The registers P1 through P1+P2-1 contain a single row of
65936 ** results. This opcode causes the sqlcipher3_step() call to terminate
65937 ** with an SQLCIPHER_ROW return code and it sets up the sqlcipher3_stmt
65938 ** structure to provide access to the top P1 values as the result
65939 ** row.
65940 */
65941 case OP_ResultRow: {
65942 #if 0  /* local variables moved into u.ad */
65943   Mem *pMem;
65944   int i;
65945 #endif /* local variables moved into u.ad */
65946   assert( p->nResColumn==pOp->p2 );
65947   assert( pOp->p1>0 );
65948   assert( pOp->p1+pOp->p2<=p->nMem+1 );
65949
65950   /* If this statement has violated immediate foreign key constraints, do
65951   ** not return the number of rows modified. And do not RELEASE the statement
65952   ** transaction. It needs to be rolled back.  */
65953   if( SQLCIPHER_OK!=(rc = sqlcipher3VdbeCheckFk(p, 0)) ){
65954     assert( db->flags&SQLCIPHER_CountRows );
65955     assert( p->usesStmtJournal );
65956     break;
65957   }
65958
65959   /* If the SQLCIPHER_CountRows flag is set in sqlcipher3.flags mask, then
65960   ** DML statements invoke this opcode to return the number of rows
65961   ** modified to the user. This is the only way that a VM that
65962   ** opens a statement transaction may invoke this opcode.
65963   **
65964   ** In case this is such a statement, close any statement transaction
65965   ** opened by this VM before returning control to the user. This is to
65966   ** ensure that statement-transactions are always nested, not overlapping.
65967   ** If the open statement-transaction is not closed here, then the user
65968   ** may step another VM that opens its own statement transaction. This
65969   ** may lead to overlapping statement transactions.
65970   **
65971   ** The statement transaction is never a top-level transaction.  Hence
65972   ** the RELEASE call below can never fail.
65973   */
65974   assert( p->iStatement==0 || db->flags&SQLCIPHER_CountRows );
65975   rc = sqlcipher3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
65976   if( NEVER(rc!=SQLCIPHER_OK) ){
65977     break;
65978   }
65979
65980   /* Invalidate all ephemeral cursor row caches */
65981   p->cacheCtr = (p->cacheCtr + 2)|1;
65982
65983   /* Make sure the results of the current row are \000 terminated
65984   ** and have an assigned type.  The results are de-ephemeralized as
65985   ** as side effect.
65986   */
65987   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
65988   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
65989     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
65990     Deephemeralize(&u.ad.pMem[u.ad.i]);
65991     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
65992             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
65993     sqlcipher3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
65994     sqlcipher3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
65995     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
65996   }
65997   if( db->mallocFailed ) goto no_mem;
65998
65999   /* Return SQLCIPHER_ROW
66000   */
66001   p->pc = pc + 1;
66002   rc = SQLCIPHER_ROW;
66003   goto vdbe_return;
66004 }
66005
66006 /* Opcode: Concat P1 P2 P3 * *
66007 **
66008 ** Add the text in register P1 onto the end of the text in
66009 ** register P2 and store the result in register P3.
66010 ** If either the P1 or P2 text are NULL then store NULL in P3.
66011 **
66012 **   P3 = P2 || P1
66013 **
66014 ** It is illegal for P1 and P3 to be the same register. Sometimes,
66015 ** if P3 is the same register as P2, the implementation is able
66016 ** to avoid a memcpy().
66017 */
66018 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66019 #if 0  /* local variables moved into u.ae */
66020   i64 nByte;
66021 #endif /* local variables moved into u.ae */
66022
66023   pIn1 = &aMem[pOp->p1];
66024   pIn2 = &aMem[pOp->p2];
66025   pOut = &aMem[pOp->p3];
66026   assert( pIn1!=pOut );
66027   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66028     sqlcipher3VdbeMemSetNull(pOut);
66029     break;
66030   }
66031   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66032   Stringify(pIn1, encoding);
66033   Stringify(pIn2, encoding);
66034   u.ae.nByte = pIn1->n + pIn2->n;
66035   if( u.ae.nByte>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
66036     goto too_big;
66037   }
66038   MemSetTypeFlag(pOut, MEM_Str);
66039   if( sqlcipher3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
66040     goto no_mem;
66041   }
66042   if( pOut!=pIn2 ){
66043     memcpy(pOut->z, pIn2->z, pIn2->n);
66044   }
66045   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66046   pOut->z[u.ae.nByte] = 0;
66047   pOut->z[u.ae.nByte+1] = 0;
66048   pOut->flags |= MEM_Term;
66049   pOut->n = (int)u.ae.nByte;
66050   pOut->enc = encoding;
66051   UPDATE_MAX_BLOBSIZE(pOut);
66052   break;
66053 }
66054
66055 /* Opcode: Add P1 P2 P3 * *
66056 **
66057 ** Add the value in register P1 to the value in register P2
66058 ** and store the result in register P3.
66059 ** If either input is NULL, the result is NULL.
66060 */
66061 /* Opcode: Multiply P1 P2 P3 * *
66062 **
66063 **
66064 ** Multiply the value in register P1 by the value in register P2
66065 ** and store the result in register P3.
66066 ** If either input is NULL, the result is NULL.
66067 */
66068 /* Opcode: Subtract P1 P2 P3 * *
66069 **
66070 ** Subtract the value in register P1 from the value in register P2
66071 ** and store the result in register P3.
66072 ** If either input is NULL, the result is NULL.
66073 */
66074 /* Opcode: Divide P1 P2 P3 * *
66075 **
66076 ** Divide the value in register P1 by the value in register P2
66077 ** and store the result in register P3 (P3=P2/P1). If the value in 
66078 ** register P1 is zero, then the result is NULL. If either input is 
66079 ** NULL, the result is NULL.
66080 */
66081 /* Opcode: Remainder P1 P2 P3 * *
66082 **
66083 ** Compute the remainder after integer division of the value in
66084 ** register P1 by the value in register P2 and store the result in P3. 
66085 ** If the value in register P2 is zero the result is NULL.
66086 ** If either operand is NULL, the result is NULL.
66087 */
66088 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66089 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66090 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66091 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66092 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66093 #if 0  /* local variables moved into u.af */
66094   int flags;      /* Combined MEM_* flags from both inputs */
66095   i64 iA;         /* Integer value of left operand */
66096   i64 iB;         /* Integer value of right operand */
66097   double rA;      /* Real value of left operand */
66098   double rB;      /* Real value of right operand */
66099 #endif /* local variables moved into u.af */
66100
66101   pIn1 = &aMem[pOp->p1];
66102   applyNumericAffinity(pIn1);
66103   pIn2 = &aMem[pOp->p2];
66104   applyNumericAffinity(pIn2);
66105   pOut = &aMem[pOp->p3];
66106   u.af.flags = pIn1->flags | pIn2->flags;
66107   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66108   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66109     u.af.iA = pIn1->u.i;
66110     u.af.iB = pIn2->u.i;
66111     switch( pOp->opcode ){
66112       case OP_Add:       if( sqlcipher3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
66113       case OP_Subtract:  if( sqlcipher3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
66114       case OP_Multiply:  if( sqlcipher3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
66115       case OP_Divide: {
66116         if( u.af.iA==0 ) goto arithmetic_result_is_null;
66117         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
66118         u.af.iB /= u.af.iA;
66119         break;
66120       }
66121       default: {
66122         if( u.af.iA==0 ) goto arithmetic_result_is_null;
66123         if( u.af.iA==-1 ) u.af.iA = 1;
66124         u.af.iB %= u.af.iA;
66125         break;
66126       }
66127     }
66128     pOut->u.i = u.af.iB;
66129     MemSetTypeFlag(pOut, MEM_Int);
66130   }else{
66131 fp_math:
66132     u.af.rA = sqlcipher3VdbeRealValue(pIn1);
66133     u.af.rB = sqlcipher3VdbeRealValue(pIn2);
66134     switch( pOp->opcode ){
66135       case OP_Add:         u.af.rB += u.af.rA;       break;
66136       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
66137       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
66138       case OP_Divide: {
66139         /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
66140         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
66141         u.af.rB /= u.af.rA;
66142         break;
66143       }
66144       default: {
66145         u.af.iA = (i64)u.af.rA;
66146         u.af.iB = (i64)u.af.rB;
66147         if( u.af.iA==0 ) goto arithmetic_result_is_null;
66148         if( u.af.iA==-1 ) u.af.iA = 1;
66149         u.af.rB = (double)(u.af.iB % u.af.iA);
66150         break;
66151       }
66152     }
66153 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
66154     pOut->u.i = u.af.rB;
66155     MemSetTypeFlag(pOut, MEM_Int);
66156 #else
66157     if( sqlcipher3IsNaN(u.af.rB) ){
66158       goto arithmetic_result_is_null;
66159     }
66160     pOut->r = u.af.rB;
66161     MemSetTypeFlag(pOut, MEM_Real);
66162     if( (u.af.flags & MEM_Real)==0 ){
66163       sqlcipher3VdbeIntegerAffinity(pOut);
66164     }
66165 #endif
66166   }
66167   break;
66168
66169 arithmetic_result_is_null:
66170   sqlcipher3VdbeMemSetNull(pOut);
66171   break;
66172 }
66173
66174 /* Opcode: CollSeq * * P4
66175 **
66176 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
66177 ** or aggregate calls sqlcipher3GetFuncCollSeq(), this collation sequence will
66178 ** be returned. This is used by the built-in min(), max() and nullif()
66179 ** functions.
66180 **
66181 ** The interface used by the implementation of the aforementioned functions
66182 ** to retrieve the collation sequence set by this opcode is not available
66183 ** publicly, only to user functions defined in func.c.
66184 */
66185 case OP_CollSeq: {
66186   assert( pOp->p4type==P4_COLLSEQ );
66187   break;
66188 }
66189
66190 /* Opcode: Function P1 P2 P3 P4 P5
66191 **
66192 ** Invoke a user function (P4 is a pointer to a Function structure that
66193 ** defines the function) with P5 arguments taken from register P2 and
66194 ** successors.  The result of the function is stored in register P3.
66195 ** Register P3 must not be one of the function inputs.
66196 **
66197 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
66198 ** function was determined to be constant at compile time. If the first
66199 ** argument was constant then bit 0 of P1 is set. This is used to determine
66200 ** whether meta data associated with a user function argument using the
66201 ** sqlcipher3_set_auxdata() API may be safely retained until the next
66202 ** invocation of this opcode.
66203 **
66204 ** See also: AggStep and AggFinal
66205 */
66206 case OP_Function: {
66207 #if 0  /* local variables moved into u.ag */
66208   int i;
66209   Mem *pArg;
66210   sqlcipher3_context ctx;
66211   sqlcipher3_value **apVal;
66212   int n;
66213 #endif /* local variables moved into u.ag */
66214
66215   u.ag.n = pOp->p5;
66216   u.ag.apVal = p->apArg;
66217   assert( u.ag.apVal || u.ag.n==0 );
66218   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66219   pOut = &aMem[pOp->p3];
66220   memAboutToChange(p, pOut);
66221
66222   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
66223   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
66224   u.ag.pArg = &aMem[pOp->p2];
66225   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
66226     assert( memIsValid(u.ag.pArg) );
66227     u.ag.apVal[u.ag.i] = u.ag.pArg;
66228     Deephemeralize(u.ag.pArg);
66229     sqlcipher3VdbeMemStoreType(u.ag.pArg);
66230     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
66231   }
66232
66233   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
66234   if( pOp->p4type==P4_FUNCDEF ){
66235     u.ag.ctx.pFunc = pOp->p4.pFunc;
66236     u.ag.ctx.pVdbeFunc = 0;
66237   }else{
66238     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
66239     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
66240   }
66241
66242   u.ag.ctx.s.flags = MEM_Null;
66243   u.ag.ctx.s.db = db;
66244   u.ag.ctx.s.xDel = 0;
66245   u.ag.ctx.s.zMalloc = 0;
66246
66247   /* The output cell may already have a buffer allocated. Move
66248   ** the pointer to u.ag.ctx.s so in case the user-function can use
66249   ** the already allocated buffer instead of allocating a new one.
66250   */
66251   sqlcipher3VdbeMemMove(&u.ag.ctx.s, pOut);
66252   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
66253
66254   u.ag.ctx.isError = 0;
66255   if( u.ag.ctx.pFunc->flags & SQLCIPHER_FUNC_NEEDCOLL ){
66256     assert( pOp>aOp );
66257     assert( pOp[-1].p4type==P4_COLLSEQ );
66258     assert( pOp[-1].opcode==OP_CollSeq );
66259     u.ag.ctx.pColl = pOp[-1].p4.pColl;
66260   }
66261   db->lastRowid = lastRowid;
66262   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
66263   lastRowid = db->lastRowid;
66264
66265   /* If any auxiliary data functions have been called by this user function,
66266   ** immediately call the destructor for any non-static values.
66267   */
66268   if( u.ag.ctx.pVdbeFunc ){
66269     sqlcipher3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
66270     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
66271     pOp->p4type = P4_VDBEFUNC;
66272   }
66273
66274   if( db->mallocFailed ){
66275     /* Even though a malloc() has failed, the implementation of the
66276     ** user function may have called an sqlcipher3_result_XXX() function
66277     ** to return a value. The following call releases any resources
66278     ** associated with such a value.
66279     */
66280     sqlcipher3VdbeMemRelease(&u.ag.ctx.s);
66281     goto no_mem;
66282   }
66283
66284   /* If the function returned an error, throw an exception */
66285   if( u.ag.ctx.isError ){
66286     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3_value_text(&u.ag.ctx.s));
66287     rc = u.ag.ctx.isError;
66288   }
66289
66290   /* Copy the result of the function into register P3 */
66291   sqlcipher3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
66292   sqlcipher3VdbeMemMove(pOut, &u.ag.ctx.s);
66293   if( sqlcipher3VdbeMemTooBig(pOut) ){
66294     goto too_big;
66295   }
66296
66297 #if 0
66298   /* The app-defined function has done something that as caused this
66299   ** statement to expire.  (Perhaps the function called sqlcipher3_exec()
66300   ** with a CREATE TABLE statement.)
66301   */
66302   if( p->expired ) rc = SQLCIPHER_ABORT;
66303 #endif
66304
66305   REGISTER_TRACE(pOp->p3, pOut);
66306   UPDATE_MAX_BLOBSIZE(pOut);
66307   break;
66308 }
66309
66310 /* Opcode: BitAnd P1 P2 P3 * *
66311 **
66312 ** Take the bit-wise AND of the values in register P1 and P2 and
66313 ** store the result in register P3.
66314 ** If either input is NULL, the result is NULL.
66315 */
66316 /* Opcode: BitOr P1 P2 P3 * *
66317 **
66318 ** Take the bit-wise OR of the values in register P1 and P2 and
66319 ** store the result in register P3.
66320 ** If either input is NULL, the result is NULL.
66321 */
66322 /* Opcode: ShiftLeft P1 P2 P3 * *
66323 **
66324 ** Shift the integer value in register P2 to the left by the
66325 ** number of bits specified by the integer in register P1.
66326 ** Store the result in register P3.
66327 ** If either input is NULL, the result is NULL.
66328 */
66329 /* Opcode: ShiftRight P1 P2 P3 * *
66330 **
66331 ** Shift the integer value in register P2 to the right by the
66332 ** number of bits specified by the integer in register P1.
66333 ** Store the result in register P3.
66334 ** If either input is NULL, the result is NULL.
66335 */
66336 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
66337 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
66338 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
66339 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
66340 #if 0  /* local variables moved into u.ah */
66341   i64 iA;
66342   u64 uA;
66343   i64 iB;
66344   u8 op;
66345 #endif /* local variables moved into u.ah */
66346
66347   pIn1 = &aMem[pOp->p1];
66348   pIn2 = &aMem[pOp->p2];
66349   pOut = &aMem[pOp->p3];
66350   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66351     sqlcipher3VdbeMemSetNull(pOut);
66352     break;
66353   }
66354   u.ah.iA = sqlcipher3VdbeIntValue(pIn2);
66355   u.ah.iB = sqlcipher3VdbeIntValue(pIn1);
66356   u.ah.op = pOp->opcode;
66357   if( u.ah.op==OP_BitAnd ){
66358     u.ah.iA &= u.ah.iB;
66359   }else if( u.ah.op==OP_BitOr ){
66360     u.ah.iA |= u.ah.iB;
66361   }else if( u.ah.iB!=0 ){
66362     assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
66363
66364     /* If shifting by a negative amount, shift in the other direction */
66365     if( u.ah.iB<0 ){
66366       assert( OP_ShiftRight==OP_ShiftLeft+1 );
66367       u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
66368       u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
66369     }
66370
66371     if( u.ah.iB>=64 ){
66372       u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
66373     }else{
66374       memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
66375       if( u.ah.op==OP_ShiftLeft ){
66376         u.ah.uA <<= u.ah.iB;
66377       }else{
66378         u.ah.uA >>= u.ah.iB;
66379         /* Sign-extend on a right shift of a negative number */
66380         if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
66381       }
66382       memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
66383     }
66384   }
66385   pOut->u.i = u.ah.iA;
66386   MemSetTypeFlag(pOut, MEM_Int);
66387   break;
66388 }
66389
66390 /* Opcode: AddImm  P1 P2 * * *
66391 ** 
66392 ** Add the constant P2 to the value in register P1.
66393 ** The result is always an integer.
66394 **
66395 ** To force any register to be an integer, just add 0.
66396 */
66397 case OP_AddImm: {            /* in1 */
66398   pIn1 = &aMem[pOp->p1];
66399   memAboutToChange(p, pIn1);
66400   sqlcipher3VdbeMemIntegerify(pIn1);
66401   pIn1->u.i += pOp->p2;
66402   break;
66403 }
66404
66405 /* Opcode: MustBeInt P1 P2 * * *
66406 ** 
66407 ** Force the value in register P1 to be an integer.  If the value
66408 ** in P1 is not an integer and cannot be converted into an integer
66409 ** without data loss, then jump immediately to P2, or if P2==0
66410 ** raise an SQLCIPHER_MISMATCH exception.
66411 */
66412 case OP_MustBeInt: {            /* jump, in1 */
66413   pIn1 = &aMem[pOp->p1];
66414   applyAffinity(pIn1, SQLCIPHER_AFF_NUMERIC, encoding);
66415   if( (pIn1->flags & MEM_Int)==0 ){
66416     if( pOp->p2==0 ){
66417       rc = SQLCIPHER_MISMATCH;
66418       goto abort_due_to_error;
66419     }else{
66420       pc = pOp->p2 - 1;
66421     }
66422   }else{
66423     MemSetTypeFlag(pIn1, MEM_Int);
66424   }
66425   break;
66426 }
66427
66428 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
66429 /* Opcode: RealAffinity P1 * * * *
66430 **
66431 ** If register P1 holds an integer convert it to a real value.
66432 **
66433 ** This opcode is used when extracting information from a column that
66434 ** has REAL affinity.  Such column values may still be stored as
66435 ** integers, for space efficiency, but after extraction we want them
66436 ** to have only a real value.
66437 */
66438 case OP_RealAffinity: {                  /* in1 */
66439   pIn1 = &aMem[pOp->p1];
66440   if( pIn1->flags & MEM_Int ){
66441     sqlcipher3VdbeMemRealify(pIn1);
66442   }
66443   break;
66444 }
66445 #endif
66446
66447 #ifndef SQLCIPHER_OMIT_CAST
66448 /* Opcode: ToText P1 * * * *
66449 **
66450 ** Force the value in register P1 to be text.
66451 ** If the value is numeric, convert it to a string using the
66452 ** equivalent of printf().  Blob values are unchanged and
66453 ** are afterwards simply interpreted as text.
66454 **
66455 ** A NULL value is not changed by this routine.  It remains NULL.
66456 */
66457 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
66458   pIn1 = &aMem[pOp->p1];
66459   memAboutToChange(p, pIn1);
66460   if( pIn1->flags & MEM_Null ) break;
66461   assert( MEM_Str==(MEM_Blob>>3) );
66462   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
66463   applyAffinity(pIn1, SQLCIPHER_AFF_TEXT, encoding);
66464   rc = ExpandBlob(pIn1);
66465   assert( pIn1->flags & MEM_Str || db->mallocFailed );
66466   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
66467   UPDATE_MAX_BLOBSIZE(pIn1);
66468   break;
66469 }
66470
66471 /* Opcode: ToBlob P1 * * * *
66472 **
66473 ** Force the value in register P1 to be a BLOB.
66474 ** If the value is numeric, convert it to a string first.
66475 ** Strings are simply reinterpreted as blobs with no change
66476 ** to the underlying data.
66477 **
66478 ** A NULL value is not changed by this routine.  It remains NULL.
66479 */
66480 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
66481   pIn1 = &aMem[pOp->p1];
66482   if( pIn1->flags & MEM_Null ) break;
66483   if( (pIn1->flags & MEM_Blob)==0 ){
66484     applyAffinity(pIn1, SQLCIPHER_AFF_TEXT, encoding);
66485     assert( pIn1->flags & MEM_Str || db->mallocFailed );
66486     MemSetTypeFlag(pIn1, MEM_Blob);
66487   }else{
66488     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
66489   }
66490   UPDATE_MAX_BLOBSIZE(pIn1);
66491   break;
66492 }
66493
66494 /* Opcode: ToNumeric P1 * * * *
66495 **
66496 ** Force the value in register P1 to be numeric (either an
66497 ** integer or a floating-point number.)
66498 ** If the value is text or blob, try to convert it to an using the
66499 ** equivalent of atoi() or atof() and store 0 if no such conversion 
66500 ** is possible.
66501 **
66502 ** A NULL value is not changed by this routine.  It remains NULL.
66503 */
66504 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
66505   pIn1 = &aMem[pOp->p1];
66506   sqlcipher3VdbeMemNumerify(pIn1);
66507   break;
66508 }
66509 #endif /* SQLCIPHER_OMIT_CAST */
66510
66511 /* Opcode: ToInt P1 * * * *
66512 **
66513 ** Force the value in register P1 to be an integer.  If
66514 ** The value is currently a real number, drop its fractional part.
66515 ** If the value is text or blob, try to convert it to an integer using the
66516 ** equivalent of atoi() and store 0 if no such conversion is possible.
66517 **
66518 ** A NULL value is not changed by this routine.  It remains NULL.
66519 */
66520 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
66521   pIn1 = &aMem[pOp->p1];
66522   if( (pIn1->flags & MEM_Null)==0 ){
66523     sqlcipher3VdbeMemIntegerify(pIn1);
66524   }
66525   break;
66526 }
66527
66528 #if !defined(SQLCIPHER_OMIT_CAST) && !defined(SQLCIPHER_OMIT_FLOATING_POINT)
66529 /* Opcode: ToReal P1 * * * *
66530 **
66531 ** Force the value in register P1 to be a floating point number.
66532 ** If The value is currently an integer, convert it.
66533 ** If the value is text or blob, try to convert it to an integer using the
66534 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
66535 **
66536 ** A NULL value is not changed by this routine.  It remains NULL.
66537 */
66538 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
66539   pIn1 = &aMem[pOp->p1];
66540   memAboutToChange(p, pIn1);
66541   if( (pIn1->flags & MEM_Null)==0 ){
66542     sqlcipher3VdbeMemRealify(pIn1);
66543   }
66544   break;
66545 }
66546 #endif /* !defined(SQLCIPHER_OMIT_CAST) && !defined(SQLCIPHER_OMIT_FLOATING_POINT) */
66547
66548 /* Opcode: Lt P1 P2 P3 P4 P5
66549 **
66550 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
66551 ** jump to address P2.  
66552 **
66553 ** If the SQLCIPHER_JUMPIFNULL bit of P5 is set and either reg(P1) or
66554 ** reg(P3) is NULL then take the jump.  If the SQLCIPHER_JUMPIFNULL 
66555 ** bit is clear then fall through if either operand is NULL.
66556 **
66557 ** The SQLCIPHER_AFF_MASK portion of P5 must be an affinity character -
66558 ** SQLCIPHER_AFF_TEXT, SQLCIPHER_AFF_INTEGER, and so forth. An attempt is made 
66559 ** to coerce both inputs according to this affinity before the
66560 ** comparison is made. If the SQLCIPHER_AFF_MASK is 0x00, then numeric
66561 ** affinity is used. Note that the affinity conversions are stored
66562 ** back into the input registers P1 and P3.  So this opcode can cause
66563 ** persistent changes to registers P1 and P3.
66564 **
66565 ** Once any conversions have taken place, and neither value is NULL, 
66566 ** the values are compared. If both values are blobs then memcmp() is
66567 ** used to determine the results of the comparison.  If both values
66568 ** are text, then the appropriate collating function specified in
66569 ** P4 is  used to do the comparison.  If P4 is not specified then
66570 ** memcmp() is used to compare text string.  If both values are
66571 ** numeric, then a numeric comparison is used. If the two values
66572 ** are of different types, then numbers are considered less than
66573 ** strings and strings are considered less than blobs.
66574 **
66575 ** If the SQLCIPHER_STOREP2 bit of P5 is set, then do not jump.  Instead,
66576 ** store a boolean result (either 0, or 1, or NULL) in register P2.
66577 */
66578 /* Opcode: Ne P1 P2 P3 P4 P5
66579 **
66580 ** This works just like the Lt opcode except that the jump is taken if
66581 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
66582 ** additional information.
66583 **
66584 ** If SQLCIPHER_NULLEQ is set in P5 then the result of comparison is always either
66585 ** true or false and is never NULL.  If both operands are NULL then the result
66586 ** of comparison is false.  If either operand is NULL then the result is true.
66587 ** If neither operand is NULL the result is the same as it would be if
66588 ** the SQLCIPHER_NULLEQ flag were omitted from P5.
66589 */
66590 /* Opcode: Eq P1 P2 P3 P4 P5
66591 **
66592 ** This works just like the Lt opcode except that the jump is taken if
66593 ** the operands in registers P1 and P3 are equal.
66594 ** See the Lt opcode for additional information.
66595 **
66596 ** If SQLCIPHER_NULLEQ is set in P5 then the result of comparison is always either
66597 ** true or false and is never NULL.  If both operands are NULL then the result
66598 ** of comparison is true.  If either operand is NULL then the result is false.
66599 ** If neither operand is NULL the result is the same as it would be if
66600 ** the SQLCIPHER_NULLEQ flag were omitted from P5.
66601 */
66602 /* Opcode: Le P1 P2 P3 P4 P5
66603 **
66604 ** This works just like the Lt opcode except that the jump is taken if
66605 ** the content of register P3 is less than or equal to the content of
66606 ** register P1.  See the Lt opcode for additional information.
66607 */
66608 /* Opcode: Gt P1 P2 P3 P4 P5
66609 **
66610 ** This works just like the Lt opcode except that the jump is taken if
66611 ** the content of register P3 is greater than the content of
66612 ** register P1.  See the Lt opcode for additional information.
66613 */
66614 /* Opcode: Ge P1 P2 P3 P4 P5
66615 **
66616 ** This works just like the Lt opcode except that the jump is taken if
66617 ** the content of register P3 is greater than or equal to the content of
66618 ** register P1.  See the Lt opcode for additional information.
66619 */
66620 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
66621 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
66622 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
66623 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
66624 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
66625 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
66626 #if 0  /* local variables moved into u.ai */
66627   int res;            /* Result of the comparison of pIn1 against pIn3 */
66628   char affinity;      /* Affinity to use for comparison */
66629   u16 flags1;         /* Copy of initial value of pIn1->flags */
66630   u16 flags3;         /* Copy of initial value of pIn3->flags */
66631 #endif /* local variables moved into u.ai */
66632
66633   pIn1 = &aMem[pOp->p1];
66634   pIn3 = &aMem[pOp->p3];
66635   u.ai.flags1 = pIn1->flags;
66636   u.ai.flags3 = pIn3->flags;
66637   if( (u.ai.flags1 | u.ai.flags3)&MEM_Null ){
66638     /* One or both operands are NULL */
66639     if( pOp->p5 & SQLCIPHER_NULLEQ ){
66640       /* If SQLCIPHER_NULLEQ is set (which will only happen if the operator is
66641       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
66642       ** or not both operands are null.
66643       */
66644       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
66645       u.ai.res = (u.ai.flags1 & u.ai.flags3 & MEM_Null)==0;
66646     }else{
66647       /* SQLCIPHER_NULLEQ is clear and at least one operand is NULL,
66648       ** then the result is always NULL.
66649       ** The jump is taken if the SQLCIPHER_JUMPIFNULL bit is set.
66650       */
66651       if( pOp->p5 & SQLCIPHER_STOREP2 ){
66652         pOut = &aMem[pOp->p2];
66653         MemSetTypeFlag(pOut, MEM_Null);
66654         REGISTER_TRACE(pOp->p2, pOut);
66655       }else if( pOp->p5 & SQLCIPHER_JUMPIFNULL ){
66656         pc = pOp->p2-1;
66657       }
66658       break;
66659     }
66660   }else{
66661     /* Neither operand is NULL.  Do a comparison. */
66662     u.ai.affinity = pOp->p5 & SQLCIPHER_AFF_MASK;
66663     if( u.ai.affinity ){
66664       applyAffinity(pIn1, u.ai.affinity, encoding);
66665       applyAffinity(pIn3, u.ai.affinity, encoding);
66666       if( db->mallocFailed ) goto no_mem;
66667     }
66668
66669     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
66670     ExpandBlob(pIn1);
66671     ExpandBlob(pIn3);
66672     u.ai.res = sqlcipher3MemCompare(pIn3, pIn1, pOp->p4.pColl);
66673   }
66674   switch( pOp->opcode ){
66675     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
66676     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
66677     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
66678     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
66679     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
66680     default:       u.ai.res = u.ai.res>=0;     break;
66681   }
66682
66683   if( pOp->p5 & SQLCIPHER_STOREP2 ){
66684     pOut = &aMem[pOp->p2];
66685     memAboutToChange(p, pOut);
66686     MemSetTypeFlag(pOut, MEM_Int);
66687     pOut->u.i = u.ai.res;
66688     REGISTER_TRACE(pOp->p2, pOut);
66689   }else if( u.ai.res ){
66690     pc = pOp->p2-1;
66691   }
66692
66693   /* Undo any changes made by applyAffinity() to the input registers. */
66694   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
66695   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
66696   break;
66697 }
66698
66699 /* Opcode: Permutation * * * P4 *
66700 **
66701 ** Set the permutation used by the OP_Compare operator to be the array
66702 ** of integers in P4.
66703 **
66704 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
66705 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
66706 ** immediately prior to the OP_Compare.
66707 */
66708 case OP_Permutation: {
66709   assert( pOp->p4type==P4_INTARRAY );
66710   assert( pOp->p4.ai );
66711   aPermute = pOp->p4.ai;
66712   break;
66713 }
66714
66715 /* Opcode: Compare P1 P2 P3 P4 *
66716 **
66717 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
66718 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
66719 ** the comparison for use by the next OP_Jump instruct.
66720 **
66721 ** P4 is a KeyInfo structure that defines collating sequences and sort
66722 ** orders for the comparison.  The permutation applies to registers
66723 ** only.  The KeyInfo elements are used sequentially.
66724 **
66725 ** The comparison is a sort comparison, so NULLs compare equal,
66726 ** NULLs are less than numbers, numbers are less than strings,
66727 ** and strings are less than blobs.
66728 */
66729 case OP_Compare: {
66730 #if 0  /* local variables moved into u.aj */
66731   int n;
66732   int i;
66733   int p1;
66734   int p2;
66735   const KeyInfo *pKeyInfo;
66736   int idx;
66737   CollSeq *pColl;    /* Collating sequence to use on this term */
66738   int bRev;          /* True for DESCENDING sort order */
66739 #endif /* local variables moved into u.aj */
66740
66741   u.aj.n = pOp->p3;
66742   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
66743   assert( u.aj.n>0 );
66744   assert( u.aj.pKeyInfo!=0 );
66745   u.aj.p1 = pOp->p1;
66746   u.aj.p2 = pOp->p2;
66747 #if SQLCIPHER_DEBUG
66748   if( aPermute ){
66749     int k, mx = 0;
66750     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
66751     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
66752     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
66753   }else{
66754     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
66755     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
66756   }
66757 #endif /* SQLCIPHER_DEBUG */
66758   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
66759     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
66760     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
66761     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
66762     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
66763     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
66764     assert( u.aj.i<u.aj.pKeyInfo->nField );
66765     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
66766     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
66767     iCompare = sqlcipher3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
66768     if( iCompare ){
66769       if( u.aj.bRev ) iCompare = -iCompare;
66770       break;
66771     }
66772   }
66773   aPermute = 0;
66774   break;
66775 }
66776
66777 /* Opcode: Jump P1 P2 P3 * *
66778 **
66779 ** Jump to the instruction at address P1, P2, or P3 depending on whether
66780 ** in the most recent OP_Compare instruction the P1 vector was less than
66781 ** equal to, or greater than the P2 vector, respectively.
66782 */
66783 case OP_Jump: {             /* jump */
66784   if( iCompare<0 ){
66785     pc = pOp->p1 - 1;
66786   }else if( iCompare==0 ){
66787     pc = pOp->p2 - 1;
66788   }else{
66789     pc = pOp->p3 - 1;
66790   }
66791   break;
66792 }
66793
66794 /* Opcode: And P1 P2 P3 * *
66795 **
66796 ** Take the logical AND of the values in registers P1 and P2 and
66797 ** write the result into register P3.
66798 **
66799 ** If either P1 or P2 is 0 (false) then the result is 0 even if
66800 ** the other input is NULL.  A NULL and true or two NULLs give
66801 ** a NULL output.
66802 */
66803 /* Opcode: Or P1 P2 P3 * *
66804 **
66805 ** Take the logical OR of the values in register P1 and P2 and
66806 ** store the answer in register P3.
66807 **
66808 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
66809 ** even if the other input is NULL.  A NULL and false or two NULLs
66810 ** give a NULL output.
66811 */
66812 case OP_And:              /* same as TK_AND, in1, in2, out3 */
66813 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
66814 #if 0  /* local variables moved into u.ak */
66815   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66816   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66817 #endif /* local variables moved into u.ak */
66818
66819   pIn1 = &aMem[pOp->p1];
66820   if( pIn1->flags & MEM_Null ){
66821     u.ak.v1 = 2;
66822   }else{
66823     u.ak.v1 = sqlcipher3VdbeIntValue(pIn1)!=0;
66824   }
66825   pIn2 = &aMem[pOp->p2];
66826   if( pIn2->flags & MEM_Null ){
66827     u.ak.v2 = 2;
66828   }else{
66829     u.ak.v2 = sqlcipher3VdbeIntValue(pIn2)!=0;
66830   }
66831   if( pOp->opcode==OP_And ){
66832     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
66833     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
66834   }else{
66835     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
66836     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
66837   }
66838   pOut = &aMem[pOp->p3];
66839   if( u.ak.v1==2 ){
66840     MemSetTypeFlag(pOut, MEM_Null);
66841   }else{
66842     pOut->u.i = u.ak.v1;
66843     MemSetTypeFlag(pOut, MEM_Int);
66844   }
66845   break;
66846 }
66847
66848 /* Opcode: Not P1 P2 * * *
66849 **
66850 ** Interpret the value in register P1 as a boolean value.  Store the
66851 ** boolean complement in register P2.  If the value in register P1 is 
66852 ** NULL, then a NULL is stored in P2.
66853 */
66854 case OP_Not: {                /* same as TK_NOT, in1, out2 */
66855   pIn1 = &aMem[pOp->p1];
66856   pOut = &aMem[pOp->p2];
66857   if( pIn1->flags & MEM_Null ){
66858     sqlcipher3VdbeMemSetNull(pOut);
66859   }else{
66860     sqlcipher3VdbeMemSetInt64(pOut, !sqlcipher3VdbeIntValue(pIn1));
66861   }
66862   break;
66863 }
66864
66865 /* Opcode: BitNot P1 P2 * * *
66866 **
66867 ** Interpret the content of register P1 as an integer.  Store the
66868 ** ones-complement of the P1 value into register P2.  If P1 holds
66869 ** a NULL then store a NULL in P2.
66870 */
66871 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66872   pIn1 = &aMem[pOp->p1];
66873   pOut = &aMem[pOp->p2];
66874   if( pIn1->flags & MEM_Null ){
66875     sqlcipher3VdbeMemSetNull(pOut);
66876   }else{
66877     sqlcipher3VdbeMemSetInt64(pOut, ~sqlcipher3VdbeIntValue(pIn1));
66878   }
66879   break;
66880 }
66881
66882 /* Opcode: Once P1 P2 * * *
66883 **
66884 ** Jump to P2 if the value in register P1 is a not null or zero.  If
66885 ** the value is NULL or zero, fall through and change the P1 register
66886 ** to an integer 1.
66887 **
66888 ** When P1 is not used otherwise in a program, this opcode falls through
66889 ** once and jumps on all subsequent invocations.  It is the equivalent
66890 ** of "OP_If P1 P2", followed by "OP_Integer 1 P1".
66891 */
66892 /* Opcode: If P1 P2 P3 * *
66893 **
66894 ** Jump to P2 if the value in register P1 is true.  The value
66895 ** is considered true if it is numeric and non-zero.  If the value
66896 ** in P1 is NULL then take the jump if P3 is true.
66897 */
66898 /* Opcode: IfNot P1 P2 P3 * *
66899 **
66900 ** Jump to P2 if the value in register P1 is False.  The value
66901 ** is considered true if it has a numeric value of zero.  If the value
66902 ** in P1 is NULL then take the jump if P3 is true.
66903 */
66904 case OP_Once:               /* jump, in1 */
66905 case OP_If:                 /* jump, in1 */
66906 case OP_IfNot: {            /* jump, in1 */
66907 #if 0  /* local variables moved into u.al */
66908   int c;
66909 #endif /* local variables moved into u.al */
66910   pIn1 = &aMem[pOp->p1];
66911   if( pIn1->flags & MEM_Null ){
66912     u.al.c = pOp->p3;
66913   }else{
66914 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
66915     u.al.c = sqlcipher3VdbeIntValue(pIn1)!=0;
66916 #else
66917     u.al.c = sqlcipher3VdbeRealValue(pIn1)!=0.0;
66918 #endif
66919     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
66920   }
66921   if( u.al.c ){
66922     pc = pOp->p2-1;
66923   }else if( pOp->opcode==OP_Once ){
66924     assert( (pIn1->flags & (MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))==0 );
66925     memAboutToChange(p, pIn1);
66926     pIn1->flags = MEM_Int;
66927     pIn1->u.i = 1;
66928     REGISTER_TRACE(pOp->p1, pIn1);
66929   }
66930   break;
66931 }
66932
66933 /* Opcode: IsNull P1 P2 * * *
66934 **
66935 ** Jump to P2 if the value in register P1 is NULL.
66936 */
66937 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66938   pIn1 = &aMem[pOp->p1];
66939   if( (pIn1->flags & MEM_Null)!=0 ){
66940     pc = pOp->p2 - 1;
66941   }
66942   break;
66943 }
66944
66945 /* Opcode: NotNull P1 P2 * * *
66946 **
66947 ** Jump to P2 if the value in register P1 is not NULL.  
66948 */
66949 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66950   pIn1 = &aMem[pOp->p1];
66951   if( (pIn1->flags & MEM_Null)==0 ){
66952     pc = pOp->p2 - 1;
66953   }
66954   break;
66955 }
66956
66957 /* Opcode: Column P1 P2 P3 P4 P5
66958 **
66959 ** Interpret the data that cursor P1 points to as a structure built using
66960 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
66961 ** information about the format of the data.)  Extract the P2-th column
66962 ** from this record.  If there are less that (P2+1) 
66963 ** values in the record, extract a NULL.
66964 **
66965 ** The value extracted is stored in register P3.
66966 **
66967 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
66968 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
66969 ** the result.
66970 **
66971 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
66972 ** then the cache of the cursor is reset prior to extracting the column.
66973 ** The first OP_Column against a pseudo-table after the value of the content
66974 ** register has changed should have this bit set.
66975 */
66976 case OP_Column: {
66977 #if 0  /* local variables moved into u.am */
66978   u32 payloadSize;   /* Number of bytes in the record */
66979   i64 payloadSize64; /* Number of bytes in the record */
66980   int p1;            /* P1 value of the opcode */
66981   int p2;            /* column number to retrieve */
66982   VdbeCursor *pC;    /* The VDBE cursor */
66983   char *zRec;        /* Pointer to complete record-data */
66984   BtCursor *pCrsr;   /* The BTree cursor */
66985   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
66986   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
66987   int nField;        /* number of fields in the record */
66988   int len;           /* The length of the serialized data for the column */
66989   int i;             /* Loop counter */
66990   char *zData;       /* Part of the record being decoded */
66991   Mem *pDest;        /* Where to write the extracted value */
66992   Mem sMem;          /* For storing the record being decoded */
66993   u8 *zIdx;          /* Index into header */
66994   u8 *zEndHdr;       /* Pointer to first byte after the header */
66995   u32 offset;        /* Offset into the data */
66996   u32 szField;       /* Number of bytes in the content of a field */
66997   int szHdr;         /* Size of the header size field at start of record */
66998   int avail;         /* Number of bytes of available data */
66999   u32 t;             /* A type code from the record header */
67000   Mem *pReg;         /* PseudoTable input register */
67001 #endif /* local variables moved into u.am */
67002
67003
67004   u.am.p1 = pOp->p1;
67005   u.am.p2 = pOp->p2;
67006   u.am.pC = 0;
67007   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
67008   assert( u.am.p1<p->nCursor );
67009   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67010   u.am.pDest = &aMem[pOp->p3];
67011   memAboutToChange(p, u.am.pDest);
67012   u.am.zRec = 0;
67013
67014   /* This block sets the variable u.am.payloadSize to be the total number of
67015   ** bytes in the record.
67016   **
67017   ** u.am.zRec is set to be the complete text of the record if it is available.
67018   ** The complete record text is always available for pseudo-tables
67019   ** If the record is stored in a cursor, the complete record text
67020   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
67021   ** If the data is unavailable,  u.am.zRec is set to NULL.
67022   **
67023   ** We also compute the number of columns in the record.  For cursors,
67024   ** the number of columns is stored in the VdbeCursor.nField element.
67025   */
67026   u.am.pC = p->apCsr[u.am.p1];
67027   assert( u.am.pC!=0 );
67028 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
67029   assert( u.am.pC->pVtabCursor==0 );
67030 #endif
67031   u.am.pCrsr = u.am.pC->pCursor;
67032   if( u.am.pCrsr!=0 ){
67033     /* The record is stored in a B-Tree */
67034     rc = sqlcipher3VdbeCursorMoveto(u.am.pC);
67035     if( rc ) goto abort_due_to_error;
67036     if( u.am.pC->nullRow ){
67037       u.am.payloadSize = 0;
67038     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
67039       u.am.payloadSize = u.am.pC->payloadSize;
67040       u.am.zRec = (char*)u.am.pC->aRow;
67041     }else if( u.am.pC->isIndex ){
67042       assert( sqlcipher3BtreeCursorIsValid(u.am.pCrsr) );
67043       VVA_ONLY(rc =) sqlcipher3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
67044       assert( rc==SQLCIPHER_OK );   /* True because of CursorMoveto() call above */
67045       /* sqlcipher3BtreeParseCellPtr() uses getVarint32() to extract the
67046       ** payload size, so it is impossible for u.am.payloadSize64 to be
67047       ** larger than 32 bits. */
67048       assert( (u.am.payloadSize64 & SQLCIPHER_MAX_U32)==(u64)u.am.payloadSize64 );
67049       u.am.payloadSize = (u32)u.am.payloadSize64;
67050     }else{
67051       assert( sqlcipher3BtreeCursorIsValid(u.am.pCrsr) );
67052       VVA_ONLY(rc =) sqlcipher3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
67053       assert( rc==SQLCIPHER_OK );   /* DataSize() cannot fail */
67054     }
67055   }else if( ALWAYS(u.am.pC->pseudoTableReg>0) ){
67056     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
67057     assert( u.am.pReg->flags & MEM_Blob );
67058     assert( memIsValid(u.am.pReg) );
67059     u.am.payloadSize = u.am.pReg->n;
67060     u.am.zRec = u.am.pReg->z;
67061     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67062     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
67063   }else{
67064     /* Consider the row to be NULL */
67065     u.am.payloadSize = 0;
67066   }
67067
67068   /* If u.am.payloadSize is 0, then just store a NULL.  This can happen because of
67069   ** nullRow or because of a corrupt database. */
67070   if( u.am.payloadSize==0 ){
67071     MemSetTypeFlag(u.am.pDest, MEM_Null);
67072     goto op_column_out;
67073   }
67074   assert( db->aLimit[SQLCIPHER_LIMIT_LENGTH]>=0 );
67075   if( u.am.payloadSize > (u32)db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
67076     goto too_big;
67077   }
67078
67079   u.am.nField = u.am.pC->nField;
67080   assert( u.am.p2<u.am.nField );
67081
67082   /* Read and parse the table header.  Store the results of the parse
67083   ** into the record header cache fields of the cursor.
67084   */
67085   u.am.aType = u.am.pC->aType;
67086   if( u.am.pC->cacheStatus==p->cacheCtr ){
67087     u.am.aOffset = u.am.pC->aOffset;
67088   }else{
67089     assert(u.am.aType);
67090     u.am.avail = 0;
67091     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
67092     u.am.pC->payloadSize = u.am.payloadSize;
67093     u.am.pC->cacheStatus = p->cacheCtr;
67094
67095     /* Figure out how many bytes are in the header */
67096     if( u.am.zRec ){
67097       u.am.zData = u.am.zRec;
67098     }else{
67099       if( u.am.pC->isIndex ){
67100         u.am.zData = (char*)sqlcipher3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
67101       }else{
67102         u.am.zData = (char*)sqlcipher3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
67103       }
67104       /* If KeyFetch()/DataFetch() managed to get the entire payload,
67105       ** save the payload in the u.am.pC->aRow cache.  That will save us from
67106       ** having to make additional calls to fetch the content portion of
67107       ** the record.
67108       */
67109       assert( u.am.avail>=0 );
67110       if( u.am.payloadSize <= (u32)u.am.avail ){
67111         u.am.zRec = u.am.zData;
67112         u.am.pC->aRow = (u8*)u.am.zData;
67113       }else{
67114         u.am.pC->aRow = 0;
67115       }
67116     }
67117     /* The following assert is true in all cases accept when
67118     ** the database file has been corrupted externally.
67119     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
67120     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
67121
67122     /* Make sure a corrupt database has not given us an oversize header.
67123     ** Do this now to avoid an oversize memory allocation.
67124     **
67125     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67126     ** types use so much data space that there can only be 4096 and 32 of
67127     ** them, respectively.  So the maximum header length results from a
67128     ** 3-byte type for each of the maximum of 32768 columns plus three
67129     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67130     */
67131     if( u.am.offset > 98307 ){
67132       rc = SQLCIPHER_CORRUPT_BKPT;
67133       goto op_column_out;
67134     }
67135
67136     /* Compute in u.am.len the number of bytes of data we need to read in order
67137     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
67138     ** u.am.nField might be significantly less than the true number of columns
67139     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
67140     ** We want to minimize u.am.len in order to limit the size of the memory
67141     ** allocation, especially if a corrupt database file has caused u.am.offset
67142     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67143     ** still exceed Robson memory allocation limits on some configurations.
67144     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
67145     ** will likely be much smaller since u.am.nField will likely be less than
67146     ** 20 or so.  This insures that Robson memory allocation limits are
67147     ** not exceeded even for corrupt database files.
67148     */
67149     u.am.len = u.am.nField*5 + 3;
67150     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
67151
67152     /* The KeyFetch() or DataFetch() above are fast and will get the entire
67153     ** record header in most cases.  But they will fail to get the complete
67154     ** record header if the record header does not fit on a single page
67155     ** in the B-Tree.  When that happens, use sqlcipher3VdbeMemFromBtree() to
67156     ** acquire the complete header text.
67157     */
67158     if( !u.am.zRec && u.am.avail<u.am.len ){
67159       u.am.sMem.flags = 0;
67160       u.am.sMem.db = 0;
67161       rc = sqlcipher3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
67162       if( rc!=SQLCIPHER_OK ){
67163         goto op_column_out;
67164       }
67165       u.am.zData = u.am.sMem.z;
67166     }
67167     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
67168     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
67169
67170     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
67171     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
67172     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
67173     ** of the record to the start of the data for the u.am.i-th column
67174     */
67175     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
67176       if( u.am.zIdx<u.am.zEndHdr ){
67177         u.am.aOffset[u.am.i] = u.am.offset;
67178         if( u.am.zIdx[0]<0x80 ){
67179           u.am.t = u.am.zIdx[0];
67180           u.am.zIdx++;
67181         }else{
67182           u.am.zIdx += sqlcipher3GetVarint32(u.am.zIdx, &u.am.t);
67183         }
67184         u.am.aType[u.am.i] = u.am.t;
67185         u.am.szField = sqlcipher3VdbeSerialTypeLen(u.am.t);
67186         u.am.offset += u.am.szField;
67187         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
67188           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLCIPHER_CORRUPT return below */
67189           break;
67190         }
67191       }else{
67192         /* If u.am.i is less that u.am.nField, then there are less fields in this
67193         ** record than SetNumColumns indicated there are columns in the
67194         ** table. Set the u.am.offset for any extra columns not present in
67195         ** the record to 0. This tells code below to store a NULL
67196         ** instead of deserializing a value from the record.
67197         */
67198         u.am.aOffset[u.am.i] = 0;
67199       }
67200     }
67201     sqlcipher3VdbeMemRelease(&u.am.sMem);
67202     u.am.sMem.flags = MEM_Null;
67203
67204     /* If we have read more header data than was contained in the header,
67205     ** or if the end of the last field appears to be past the end of the
67206     ** record, or if the end of the last field appears to be before the end
67207     ** of the record (when all fields present), then we must be dealing
67208     ** with a corrupt database.
67209     */
67210     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
67211          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
67212       rc = SQLCIPHER_CORRUPT_BKPT;
67213       goto op_column_out;
67214     }
67215   }
67216
67217   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
67218   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
67219   ** then there are not enough fields in the record to satisfy the
67220   ** request.  In this case, set the value NULL or to P4 if P4 is
67221   ** a pointer to a Mem object.
67222   */
67223   if( u.am.aOffset[u.am.p2] ){
67224     assert( rc==SQLCIPHER_OK );
67225     if( u.am.zRec ){
67226       MemReleaseExt(u.am.pDest);
67227       sqlcipher3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
67228     }else{
67229       u.am.len = sqlcipher3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
67230       sqlcipher3VdbeMemMove(&u.am.sMem, u.am.pDest);
67231       rc = sqlcipher3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
67232       if( rc!=SQLCIPHER_OK ){
67233         goto op_column_out;
67234       }
67235       u.am.zData = u.am.sMem.z;
67236       sqlcipher3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
67237     }
67238     u.am.pDest->enc = encoding;
67239   }else{
67240     if( pOp->p4type==P4_MEM ){
67241       sqlcipher3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
67242     }else{
67243       MemSetTypeFlag(u.am.pDest, MEM_Null);
67244     }
67245   }
67246
67247   /* If we dynamically allocated space to hold the data (in the
67248   ** sqlcipher3VdbeMemFromBtree() call above) then transfer control of that
67249   ** dynamically allocated space over to the u.am.pDest structure.
67250   ** This prevents a memory copy.
67251   */
67252   if( u.am.sMem.zMalloc ){
67253     assert( u.am.sMem.z==u.am.sMem.zMalloc );
67254     assert( !(u.am.pDest->flags & MEM_Dyn) );
67255     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
67256     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67257     u.am.pDest->flags |= MEM_Term;
67258     u.am.pDest->z = u.am.sMem.z;
67259     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
67260   }
67261
67262   rc = sqlcipher3VdbeMemMakeWriteable(u.am.pDest);
67263
67264 op_column_out:
67265   UPDATE_MAX_BLOBSIZE(u.am.pDest);
67266   REGISTER_TRACE(pOp->p3, u.am.pDest);
67267   break;
67268 }
67269
67270 /* Opcode: Affinity P1 P2 * P4 *
67271 **
67272 ** Apply affinities to a range of P2 registers starting with P1.
67273 **
67274 ** P4 is 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 ** memory cell in the range.
67277 */
67278 case OP_Affinity: {
67279 #if 0  /* local variables moved into u.an */
67280   const char *zAffinity;   /* The affinity to be applied */
67281   char cAff;               /* A single character of affinity */
67282 #endif /* local variables moved into u.an */
67283
67284   u.an.zAffinity = pOp->p4.z;
67285   assert( u.an.zAffinity!=0 );
67286   assert( u.an.zAffinity[pOp->p2]==0 );
67287   pIn1 = &aMem[pOp->p1];
67288   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
67289     assert( pIn1 <= &p->aMem[p->nMem] );
67290     assert( memIsValid(pIn1) );
67291     ExpandBlob(pIn1);
67292     applyAffinity(pIn1, u.an.cAff, encoding);
67293     pIn1++;
67294   }
67295   break;
67296 }
67297
67298 /* Opcode: MakeRecord P1 P2 P3 P4 *
67299 **
67300 ** Convert P2 registers beginning with P1 into the [record format]
67301 ** use as a data record in a database table or as a key
67302 ** in an index.  The OP_Column opcode can decode the record later.
67303 **
67304 ** P4 may be a string that is P2 characters long.  The nth character of the
67305 ** string indicates the column affinity that should be used for the nth
67306 ** field of the index key.
67307 **
67308 ** The mapping from character to affinity is given by the SQLCIPHER_AFF_
67309 ** macros defined in sqlcipherInt.h.
67310 **
67311 ** If P4 is NULL then all index fields have the affinity NONE.
67312 */
67313 case OP_MakeRecord: {
67314 #if 0  /* local variables moved into u.ao */
67315   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
67316   Mem *pRec;             /* The new record */
67317   u64 nData;             /* Number of bytes of data space */
67318   int nHdr;              /* Number of bytes of header space */
67319   i64 nByte;             /* Data space required for this record */
67320   int nZero;             /* Number of zero bytes at the end of the record */
67321   int nVarint;           /* Number of bytes in a varint */
67322   u32 serial_type;       /* Type field */
67323   Mem *pData0;           /* First field to be combined into the record */
67324   Mem *pLast;            /* Last field of the record */
67325   int nField;            /* Number of fields in the record */
67326   char *zAffinity;       /* The affinity string for the record */
67327   int file_format;       /* File format to use for encoding */
67328   int i;                 /* Space used in zNewRecord[] */
67329   int len;               /* Length of a field */
67330 #endif /* local variables moved into u.ao */
67331
67332   /* Assuming the record contains N fields, the record format looks
67333   ** like this:
67334   **
67335   ** ------------------------------------------------------------------------
67336   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
67337   ** ------------------------------------------------------------------------
67338   **
67339   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
67340   ** and so froth.
67341   **
67342   ** Each type field is a varint representing the serial type of the
67343   ** corresponding data element (see sqlcipher3VdbeSerialType()). The
67344   ** hdr-size field is also a varint which is the offset from the beginning
67345   ** of the record to data0.
67346   */
67347   u.ao.nData = 0;         /* Number of bytes of data space */
67348   u.ao.nHdr = 0;          /* Number of bytes of header space */
67349   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
67350   u.ao.nField = pOp->p1;
67351   u.ao.zAffinity = pOp->p4.z;
67352   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
67353   u.ao.pData0 = &aMem[u.ao.nField];
67354   u.ao.nField = pOp->p2;
67355   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
67356   u.ao.file_format = p->minWriteFileFormat;
67357
67358   /* Identify the output register */
67359   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
67360   pOut = &aMem[pOp->p3];
67361   memAboutToChange(p, pOut);
67362
67363   /* Loop through the elements that will make up the record to figure
67364   ** out how much space is required for the new record.
67365   */
67366   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
67367     assert( memIsValid(u.ao.pRec) );
67368     if( u.ao.zAffinity ){
67369       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
67370     }
67371     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
67372       sqlcipher3VdbeMemExpandBlob(u.ao.pRec);
67373     }
67374     u.ao.serial_type = sqlcipher3VdbeSerialType(u.ao.pRec, u.ao.file_format);
67375     u.ao.len = sqlcipher3VdbeSerialTypeLen(u.ao.serial_type);
67376     u.ao.nData += u.ao.len;
67377     u.ao.nHdr += sqlcipher3VarintLen(u.ao.serial_type);
67378     if( u.ao.pRec->flags & MEM_Zero ){
67379       /* Only pure zero-filled BLOBs can be input to this Opcode.
67380       ** We do not allow blobs with a prefix and a zero-filled tail. */
67381       u.ao.nZero += u.ao.pRec->u.nZero;
67382     }else if( u.ao.len ){
67383       u.ao.nZero = 0;
67384     }
67385   }
67386
67387   /* Add the initial header varint and total the size */
67388   u.ao.nHdr += u.ao.nVarint = sqlcipher3VarintLen(u.ao.nHdr);
67389   if( u.ao.nVarint<sqlcipher3VarintLen(u.ao.nHdr) ){
67390     u.ao.nHdr++;
67391   }
67392   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
67393   if( u.ao.nByte>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
67394     goto too_big;
67395   }
67396
67397   /* Make sure the output register has a buffer large enough to store
67398   ** the new record. The output register (pOp->p3) is not allowed to
67399   ** be one of the input registers (because the following call to
67400   ** sqlcipher3VdbeMemGrow() could clobber the value before it is used).
67401   */
67402   if( sqlcipher3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
67403     goto no_mem;
67404   }
67405   u.ao.zNewRecord = (u8 *)pOut->z;
67406
67407   /* Write the record */
67408   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
67409   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
67410     u.ao.serial_type = sqlcipher3VdbeSerialType(u.ao.pRec, u.ao.file_format);
67411     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
67412   }
67413   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
67414     u.ao.i += sqlcipher3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
67415   }
67416   assert( u.ao.i==u.ao.nByte );
67417
67418   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67419   pOut->n = (int)u.ao.nByte;
67420   pOut->flags = MEM_Blob | MEM_Dyn;
67421   pOut->xDel = 0;
67422   if( u.ao.nZero ){
67423     pOut->u.nZero = u.ao.nZero;
67424     pOut->flags |= MEM_Zero;
67425   }
67426   pOut->enc = SQLCIPHER_UTF8;  /* In case the blob is ever converted to text */
67427   REGISTER_TRACE(pOp->p3, pOut);
67428   UPDATE_MAX_BLOBSIZE(pOut);
67429   break;
67430 }
67431
67432 /* Opcode: Count P1 P2 * * *
67433 **
67434 ** Store the number of entries (an integer value) in the table or index 
67435 ** opened by cursor P1 in register P2
67436 */
67437 #ifndef SQLCIPHER_OMIT_BTREECOUNT
67438 case OP_Count: {         /* out2-prerelease */
67439 #if 0  /* local variables moved into u.ap */
67440   i64 nEntry;
67441   BtCursor *pCrsr;
67442 #endif /* local variables moved into u.ap */
67443
67444   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
67445   if( ALWAYS(u.ap.pCrsr) ){
67446     rc = sqlcipher3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
67447   }else{
67448     u.ap.nEntry = 0;
67449   }
67450   pOut->u.i = u.ap.nEntry;
67451   break;
67452 }
67453 #endif
67454
67455 /* Opcode: Savepoint P1 * * P4 *
67456 **
67457 ** Open, release or rollback the savepoint named by parameter P4, depending
67458 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
67459 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
67460 */
67461 case OP_Savepoint: {
67462 #if 0  /* local variables moved into u.aq */
67463   int p1;                         /* Value of P1 operand */
67464   char *zName;                    /* Name of savepoint */
67465   int nName;
67466   Savepoint *pNew;
67467   Savepoint *pSavepoint;
67468   Savepoint *pTmp;
67469   int iSavepoint;
67470   int ii;
67471 #endif /* local variables moved into u.aq */
67472
67473   u.aq.p1 = pOp->p1;
67474   u.aq.zName = pOp->p4.z;
67475
67476   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
67477   ** transaction, then there cannot be any savepoints.
67478   */
67479   assert( db->pSavepoint==0 || db->autoCommit==0 );
67480   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
67481   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
67482   assert( checkSavepointCount(db) );
67483
67484   if( u.aq.p1==SAVEPOINT_BEGIN ){
67485     if( db->writeVdbeCnt>0 ){
67486       /* A new savepoint cannot be created if there are active write
67487       ** statements (i.e. open read/write incremental blob handles).
67488       */
67489       sqlcipher3SetString(&p->zErrMsg, db, "cannot open savepoint - "
67490         "SQL statements in progress");
67491       rc = SQLCIPHER_BUSY;
67492     }else{
67493       u.aq.nName = sqlcipher3Strlen30(u.aq.zName);
67494
67495 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
67496       /* This call is Ok even if this savepoint is actually a transaction
67497       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
67498       ** If this is a transaction savepoint being opened, it is guaranteed
67499       ** that the db->aVTrans[] array is empty.  */
67500       assert( db->autoCommit==0 || db->nVTrans==0 );
67501       rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_BEGIN,
67502                                 db->nStatement+db->nSavepoint);
67503       if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
67504 #endif
67505
67506       /* Create a new savepoint structure. */
67507       u.aq.pNew = sqlcipher3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
67508       if( u.aq.pNew ){
67509         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
67510         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
67511
67512         /* If there is no open transaction, then mark this as a special
67513         ** "transaction savepoint". */
67514         if( db->autoCommit ){
67515           db->autoCommit = 0;
67516           db->isTransactionSavepoint = 1;
67517         }else{
67518           db->nSavepoint++;
67519         }
67520
67521         /* Link the new savepoint into the database handle's list. */
67522         u.aq.pNew->pNext = db->pSavepoint;
67523         db->pSavepoint = u.aq.pNew;
67524         u.aq.pNew->nDeferredCons = db->nDeferredCons;
67525       }
67526     }
67527   }else{
67528     u.aq.iSavepoint = 0;
67529
67530     /* Find the named savepoint. If there is no such savepoint, then an
67531     ** an error is returned to the user.  */
67532     for(
67533       u.aq.pSavepoint = db->pSavepoint;
67534       u.aq.pSavepoint && sqlcipher3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
67535       u.aq.pSavepoint = u.aq.pSavepoint->pNext
67536     ){
67537       u.aq.iSavepoint++;
67538     }
67539     if( !u.aq.pSavepoint ){
67540       sqlcipher3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
67541       rc = SQLCIPHER_ERROR;
67542     }else if(
67543         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
67544     ){
67545       /* It is not possible to release (commit) a savepoint if there are
67546       ** active write statements. It is not possible to rollback a savepoint
67547       ** if there are any active statements at all.
67548       */
67549       sqlcipher3SetString(&p->zErrMsg, db,
67550         "cannot %s savepoint - SQL statements in progress",
67551         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
67552       );
67553       rc = SQLCIPHER_BUSY;
67554     }else{
67555
67556       /* Determine whether or not this is a transaction savepoint. If so,
67557       ** and this is a RELEASE command, then the current transaction
67558       ** is committed.
67559       */
67560       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
67561       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
67562         if( (rc = sqlcipher3VdbeCheckFk(p, 1))!=SQLCIPHER_OK ){
67563           goto vdbe_return;
67564         }
67565         db->autoCommit = 1;
67566         if( sqlcipher3VdbeHalt(p)==SQLCIPHER_BUSY ){
67567           p->pc = pc;
67568           db->autoCommit = 0;
67569           p->rc = rc = SQLCIPHER_BUSY;
67570           goto vdbe_return;
67571         }
67572         db->isTransactionSavepoint = 0;
67573         rc = p->rc;
67574       }else{
67575         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
67576         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
67577           rc = sqlcipher3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
67578           if( rc!=SQLCIPHER_OK ){
67579             goto abort_due_to_error;
67580           }
67581         }
67582         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLCIPHER_InternChanges)!=0 ){
67583           sqlcipher3ExpirePreparedStatements(db);
67584           sqlcipher3ResetInternalSchema(db, -1);
67585           db->flags = (db->flags | SQLCIPHER_InternChanges);
67586         }
67587       }
67588
67589       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
67590       ** savepoints nested inside of the savepoint being operated on. */
67591       while( db->pSavepoint!=u.aq.pSavepoint ){
67592         u.aq.pTmp = db->pSavepoint;
67593         db->pSavepoint = u.aq.pTmp->pNext;
67594         sqlcipher3DbFree(db, u.aq.pTmp);
67595         db->nSavepoint--;
67596       }
67597
67598       /* If it is a RELEASE, then destroy the savepoint being operated on
67599       ** too. If it is a ROLLBACK TO, then set the number of deferred
67600       ** constraint violations present in the database to the value stored
67601       ** when the savepoint was created.  */
67602       if( u.aq.p1==SAVEPOINT_RELEASE ){
67603         assert( u.aq.pSavepoint==db->pSavepoint );
67604         db->pSavepoint = u.aq.pSavepoint->pNext;
67605         sqlcipher3DbFree(db, u.aq.pSavepoint);
67606         if( !isTransaction ){
67607           db->nSavepoint--;
67608         }
67609       }else{
67610         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
67611       }
67612
67613       if( !isTransaction ){
67614         rc = sqlcipher3VtabSavepoint(db, u.aq.p1, u.aq.iSavepoint);
67615         if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
67616       }
67617     }
67618   }
67619
67620   break;
67621 }
67622
67623 /* Opcode: AutoCommit P1 P2 * * *
67624 **
67625 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
67626 ** back any currently active btree transactions. If there are any active
67627 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
67628 ** there are active writing VMs or active VMs that use shared cache.
67629 **
67630 ** This instruction causes the VM to halt.
67631 */
67632 case OP_AutoCommit: {
67633 #if 0  /* local variables moved into u.ar */
67634   int desiredAutoCommit;
67635   int iRollback;
67636   int turnOnAC;
67637 #endif /* local variables moved into u.ar */
67638
67639   u.ar.desiredAutoCommit = pOp->p1;
67640   u.ar.iRollback = pOp->p2;
67641   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
67642   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
67643   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
67644   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
67645
67646   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
67647     /* If this instruction implements a ROLLBACK and other VMs are
67648     ** still running, and a transaction is active, return an error indicating
67649     ** that the other VMs must complete first.
67650     */
67651     sqlcipher3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
67652         "SQL statements in progress");
67653     rc = SQLCIPHER_BUSY;
67654   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
67655     /* If this instruction implements a COMMIT and other VMs are writing
67656     ** return an error indicating that the other VMs must complete first.
67657     */
67658     sqlcipher3SetString(&p->zErrMsg, db, "cannot commit transaction - "
67659         "SQL statements in progress");
67660     rc = SQLCIPHER_BUSY;
67661   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
67662     if( u.ar.iRollback ){
67663       assert( u.ar.desiredAutoCommit==1 );
67664       sqlcipher3RollbackAll(db);
67665       db->autoCommit = 1;
67666     }else if( (rc = sqlcipher3VdbeCheckFk(p, 1))!=SQLCIPHER_OK ){
67667       goto vdbe_return;
67668     }else{
67669       db->autoCommit = (u8)u.ar.desiredAutoCommit;
67670       if( sqlcipher3VdbeHalt(p)==SQLCIPHER_BUSY ){
67671         p->pc = pc;
67672         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
67673         p->rc = rc = SQLCIPHER_BUSY;
67674         goto vdbe_return;
67675       }
67676     }
67677     assert( db->nStatement==0 );
67678     sqlcipher3CloseSavepoints(db);
67679     if( p->rc==SQLCIPHER_OK ){
67680       rc = SQLCIPHER_DONE;
67681     }else{
67682       rc = SQLCIPHER_ERROR;
67683     }
67684     goto vdbe_return;
67685   }else{
67686     sqlcipher3SetString(&p->zErrMsg, db,
67687         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
67688         (u.ar.iRollback)?"cannot rollback - no transaction is active":
67689                    "cannot commit - no transaction is active"));
67690
67691     rc = SQLCIPHER_ERROR;
67692   }
67693   break;
67694 }
67695
67696 /* Opcode: Transaction P1 P2 * * *
67697 **
67698 ** Begin a transaction.  The transaction ends when a Commit or Rollback
67699 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
67700 ** transaction might also be rolled back if an error is encountered.
67701 **
67702 ** P1 is the index of the database file on which the transaction is
67703 ** started.  Index 0 is the main database file and index 1 is the
67704 ** file used for temporary tables.  Indices of 2 or more are used for
67705 ** attached databases.
67706 **
67707 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
67708 ** obtained on the database file when a write-transaction is started.  No
67709 ** other process can start another write transaction while this transaction is
67710 ** underway.  Starting a write transaction also creates a rollback journal. A
67711 ** write transaction must be started before any changes can be made to the
67712 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
67713 ** on the file.
67714 **
67715 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
67716 ** true (this flag is set if the Vdbe may modify more than one row and may
67717 ** throw an ABORT exception), a statement transaction may also be opened.
67718 ** More specifically, a statement transaction is opened iff the database
67719 ** connection is currently not in autocommit mode, or if there are other
67720 ** active statements. A statement transaction allows the affects of this
67721 ** VDBE to be rolled back after an error without having to roll back the
67722 ** entire transaction. If no error is encountered, the statement transaction
67723 ** will automatically commit when the VDBE halts.
67724 **
67725 ** If P2 is zero, then a read-lock is obtained on the database file.
67726 */
67727 case OP_Transaction: {
67728 #if 0  /* local variables moved into u.as */
67729   Btree *pBt;
67730 #endif /* local variables moved into u.as */
67731
67732   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67733   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67734   u.as.pBt = db->aDb[pOp->p1].pBt;
67735
67736   if( u.as.pBt ){
67737     rc = sqlcipher3BtreeBeginTrans(u.as.pBt, pOp->p2);
67738     if( rc==SQLCIPHER_BUSY ){
67739       p->pc = pc;
67740       p->rc = rc = SQLCIPHER_BUSY;
67741       goto vdbe_return;
67742     }
67743     if( rc!=SQLCIPHER_OK ){
67744       goto abort_due_to_error;
67745     }
67746
67747     if( pOp->p2 && p->usesStmtJournal
67748      && (db->autoCommit==0 || db->activeVdbeCnt>1)
67749     ){
67750       assert( sqlcipher3BtreeIsInTrans(u.as.pBt) );
67751       if( p->iStatement==0 ){
67752         assert( db->nStatement>=0 && db->nSavepoint>=0 );
67753         db->nStatement++;
67754         p->iStatement = db->nSavepoint + db->nStatement;
67755       }
67756
67757       rc = sqlcipher3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
67758       if( rc==SQLCIPHER_OK ){
67759         rc = sqlcipher3BtreeBeginStmt(u.as.pBt, p->iStatement);
67760       }
67761
67762       /* Store the current value of the database handles deferred constraint
67763       ** counter. If the statement transaction needs to be rolled back,
67764       ** the value of this counter needs to be restored too.  */
67765       p->nStmtDefCons = db->nDeferredCons;
67766     }
67767   }
67768   break;
67769 }
67770
67771 /* Opcode: ReadCookie P1 P2 P3 * *
67772 **
67773 ** Read cookie number P3 from database P1 and write it into register P2.
67774 ** P3==1 is the schema version.  P3==2 is the database format.
67775 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
67776 ** the main database file and P1==1 is the database file used to store
67777 ** temporary tables.
67778 **
67779 ** There must be a read-lock on the database (either a transaction
67780 ** must be started or there must be an open cursor) before
67781 ** executing this instruction.
67782 */
67783 case OP_ReadCookie: {               /* out2-prerelease */
67784 #if 0  /* local variables moved into u.at */
67785   int iMeta;
67786   int iDb;
67787   int iCookie;
67788 #endif /* local variables moved into u.at */
67789
67790   u.at.iDb = pOp->p1;
67791   u.at.iCookie = pOp->p3;
67792   assert( pOp->p3<SQLCIPHER_N_BTREE_META );
67793   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
67794   assert( db->aDb[u.at.iDb].pBt!=0 );
67795   assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
67796
67797   sqlcipher3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
67798   pOut->u.i = u.at.iMeta;
67799   break;
67800 }
67801
67802 /* Opcode: SetCookie P1 P2 P3 * *
67803 **
67804 ** Write the content of register P3 (interpreted as an integer)
67805 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
67806 ** P2==2 is the database format. P2==3 is the recommended pager cache 
67807 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
67808 ** database file used to store temporary tables.
67809 **
67810 ** A transaction must be started before executing this opcode.
67811 */
67812 case OP_SetCookie: {       /* in3 */
67813 #if 0  /* local variables moved into u.au */
67814   Db *pDb;
67815 #endif /* local variables moved into u.au */
67816   assert( pOp->p2<SQLCIPHER_N_BTREE_META );
67817   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67818   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67819   u.au.pDb = &db->aDb[pOp->p1];
67820   assert( u.au.pDb->pBt!=0 );
67821   assert( sqlcipher3SchemaMutexHeld(db, pOp->p1, 0) );
67822   pIn3 = &aMem[pOp->p3];
67823   sqlcipher3VdbeMemIntegerify(pIn3);
67824   /* See note about index shifting on OP_ReadCookie */
67825   rc = sqlcipher3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
67826   if( pOp->p2==BTREE_SCHEMA_VERSION ){
67827     /* When the schema cookie changes, record the new cookie internally */
67828     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
67829     db->flags |= SQLCIPHER_InternChanges;
67830   }else if( pOp->p2==BTREE_FILE_FORMAT ){
67831     /* Record changes in the file format */
67832     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
67833   }
67834   if( pOp->p1==1 ){
67835     /* Invalidate all prepared statements whenever the TEMP database
67836     ** schema is changed.  Ticket #1644 */
67837     sqlcipher3ExpirePreparedStatements(db);
67838     p->expired = 0;
67839   }
67840   break;
67841 }
67842
67843 /* Opcode: VerifyCookie P1 P2 P3 * *
67844 **
67845 ** Check the value of global database parameter number 0 (the
67846 ** schema version) and make sure it is equal to P2 and that the
67847 ** generation counter on the local schema parse equals P3.
67848 **
67849 ** P1 is the database number which is 0 for the main database file
67850 ** and 1 for the file holding temporary tables and some higher number
67851 ** for auxiliary databases.
67852 **
67853 ** The cookie changes its value whenever the database schema changes.
67854 ** This operation is used to detect when that the cookie has changed
67855 ** and that the current process needs to reread the schema.
67856 **
67857 ** Either a transaction needs to have been started or an OP_Open needs
67858 ** to be executed (to establish a read lock) before this opcode is
67859 ** invoked.
67860 */
67861 case OP_VerifyCookie: {
67862 #if 0  /* local variables moved into u.av */
67863   int iMeta;
67864   int iGen;
67865   Btree *pBt;
67866 #endif /* local variables moved into u.av */
67867
67868   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67869   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67870   assert( sqlcipher3SchemaMutexHeld(db, pOp->p1, 0) );
67871   u.av.pBt = db->aDb[pOp->p1].pBt;
67872   if( u.av.pBt ){
67873     sqlcipher3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
67874     u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67875   }else{
67876     u.av.iGen = u.av.iMeta = 0;
67877   }
67878   if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
67879     sqlcipher3DbFree(db, p->zErrMsg);
67880     p->zErrMsg = sqlcipher3DbStrDup(db, "database schema has changed");
67881     /* If the schema-cookie from the database file matches the cookie
67882     ** stored with the in-memory representation of the schema, do
67883     ** not reload the schema from the database file.
67884     **
67885     ** If virtual-tables are in use, this is not just an optimization.
67886     ** Often, v-tables store their data in other SQLite tables, which
67887     ** are queried from within xNext() and other v-table methods using
67888     ** prepared queries. If such a query is out-of-date, we do not want to
67889     ** discard the database schema, as the user code implementing the
67890     ** v-table would have to be ready for the sqlcipher3_vtab structure itself
67891     ** to be invalidated whenever sqlcipher3_step() is called from within
67892     ** a v-table method.
67893     */
67894     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
67895       sqlcipher3ResetInternalSchema(db, pOp->p1);
67896     }
67897
67898     p->expired = 1;
67899     rc = SQLCIPHER_SCHEMA;
67900   }
67901   break;
67902 }
67903
67904 /* Opcode: OpenRead P1 P2 P3 P4 P5
67905 **
67906 ** Open a read-only cursor for the database table whose root page is
67907 ** P2 in a database file.  The database file is determined by P3. 
67908 ** P3==0 means the main database, P3==1 means the database used for 
67909 ** temporary tables, and P3>1 means used the corresponding attached
67910 ** database.  Give the new cursor an identifier of P1.  The P1
67911 ** values need not be contiguous but all P1 values should be small integers.
67912 ** It is an error for P1 to be negative.
67913 **
67914 ** If P5!=0 then use the content of register P2 as the root page, not
67915 ** the value of P2 itself.
67916 **
67917 ** There will be a read lock on the database whenever there is an
67918 ** open cursor.  If the database was unlocked prior to this instruction
67919 ** then a read lock is acquired as part of this instruction.  A read
67920 ** lock allows other processes to read the database but prohibits
67921 ** any other process from modifying the database.  The read lock is
67922 ** released when all cursors are closed.  If this instruction attempts
67923 ** to get a read lock but fails, the script terminates with an
67924 ** SQLCIPHER_BUSY error code.
67925 **
67926 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67927 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67928 ** structure, then said structure defines the content and collating 
67929 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67930 ** value, it is set to the number of columns in the table.
67931 **
67932 ** See also OpenWrite.
67933 */
67934 /* Opcode: OpenWrite P1 P2 P3 P4 P5
67935 **
67936 ** Open a read/write cursor named P1 on the table or index whose root
67937 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
67938 ** root page.
67939 **
67940 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67941 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67942 ** structure, then said structure defines the content and collating 
67943 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67944 ** value, it is set to the number of columns in the table, or to the
67945 ** largest index of any column of the table that is actually used.
67946 **
67947 ** This instruction works just like OpenRead except that it opens the cursor
67948 ** in read/write mode.  For a given table, there can be one or more read-only
67949 ** cursors or a single read/write cursor but not both.
67950 **
67951 ** See also OpenRead.
67952 */
67953 case OP_OpenRead:
67954 case OP_OpenWrite: {
67955 #if 0  /* local variables moved into u.aw */
67956   int nField;
67957   KeyInfo *pKeyInfo;
67958   int p2;
67959   int iDb;
67960   int wrFlag;
67961   Btree *pX;
67962   VdbeCursor *pCur;
67963   Db *pDb;
67964 #endif /* local variables moved into u.aw */
67965
67966   if( p->expired ){
67967     rc = SQLCIPHER_ABORT;
67968     break;
67969   }
67970
67971   u.aw.nField = 0;
67972   u.aw.pKeyInfo = 0;
67973   u.aw.p2 = pOp->p2;
67974   u.aw.iDb = pOp->p3;
67975   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
67976   assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
67977   u.aw.pDb = &db->aDb[u.aw.iDb];
67978   u.aw.pX = u.aw.pDb->pBt;
67979   assert( u.aw.pX!=0 );
67980   if( pOp->opcode==OP_OpenWrite ){
67981     u.aw.wrFlag = 1;
67982     assert( sqlcipher3SchemaMutexHeld(db, u.aw.iDb, 0) );
67983     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
67984       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
67985     }
67986   }else{
67987     u.aw.wrFlag = 0;
67988   }
67989   if( pOp->p5 ){
67990     assert( u.aw.p2>0 );
67991     assert( u.aw.p2<=p->nMem );
67992     pIn2 = &aMem[u.aw.p2];
67993     assert( memIsValid(pIn2) );
67994     assert( (pIn2->flags & MEM_Int)!=0 );
67995     sqlcipher3VdbeMemIntegerify(pIn2);
67996     u.aw.p2 = (int)pIn2->u.i;
67997     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
67998     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
67999     ** If there were a failure, the prepared statement would have halted
68000     ** before reaching this instruction. */
68001     if( NEVER(u.aw.p2<2) ) {
68002       rc = SQLCIPHER_CORRUPT_BKPT;
68003       goto abort_due_to_error;
68004     }
68005   }
68006   if( pOp->p4type==P4_KEYINFO ){
68007     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
68008     u.aw.pKeyInfo->enc = ENC(p->db);
68009     u.aw.nField = u.aw.pKeyInfo->nField+1;
68010   }else if( pOp->p4type==P4_INT32 ){
68011     u.aw.nField = pOp->p4.i;
68012   }
68013   assert( pOp->p1>=0 );
68014   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
68015   if( u.aw.pCur==0 ) goto no_mem;
68016   u.aw.pCur->nullRow = 1;
68017   u.aw.pCur->isOrdered = 1;
68018   rc = sqlcipher3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
68019   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
68020
68021   /* Since it performs no memory allocation or IO, the only value that
68022   ** sqlcipher3BtreeCursor() may return is SQLCIPHER_OK. */
68023   assert( rc==SQLCIPHER_OK );
68024
68025   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68026   ** SQLite used to check if the root-page flags were sane at this point
68027   ** and report database corruption if they were not, but this check has
68028   ** since moved into the btree layer.  */
68029   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68030   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
68031   break;
68032 }
68033
68034 /* Opcode: OpenEphemeral P1 P2 * P4 P5
68035 **
68036 ** Open a new cursor P1 to a transient table.
68037 ** The cursor is always opened read/write even if 
68038 ** the main database is read-only.  The ephemeral
68039 ** table is deleted automatically when the cursor is closed.
68040 **
68041 ** P2 is the number of columns in the ephemeral table.
68042 ** The cursor points to a BTree table if P4==0 and to a BTree index
68043 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68044 ** that defines the format of keys in the index.
68045 **
68046 ** This opcode was once called OpenTemp.  But that created
68047 ** confusion because the term "temp table", might refer either
68048 ** to a TEMP table at the SQL level, or to a table opened by
68049 ** this opcode.  Then this opcode was call OpenVirtual.  But
68050 ** that created confusion with the whole virtual-table idea.
68051 **
68052 ** The P5 parameter can be a mask of the BTREE_* flags defined
68053 ** in btree.h.  These flags control aspects of the operation of
68054 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68055 ** added automatically.
68056 */
68057 /* Opcode: OpenAutoindex P1 P2 * P4 *
68058 **
68059 ** This opcode works the same as OP_OpenEphemeral.  It has a
68060 ** different name to distinguish its use.  Tables created using
68061 ** by this opcode will be used for automatically created transient
68062 ** indices in joins.
68063 */
68064 case OP_OpenAutoindex: 
68065 case OP_OpenEphemeral: {
68066 #if 0  /* local variables moved into u.ax */
68067   VdbeCursor *pCx;
68068 #endif /* local variables moved into u.ax */
68069   static const int vfsFlags =
68070       SQLCIPHER_OPEN_READWRITE |
68071       SQLCIPHER_OPEN_CREATE |
68072       SQLCIPHER_OPEN_EXCLUSIVE |
68073       SQLCIPHER_OPEN_DELETEONCLOSE |
68074       SQLCIPHER_OPEN_TRANSIENT_DB;
68075
68076   assert( pOp->p1>=0 );
68077   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68078   if( u.ax.pCx==0 ) goto no_mem;
68079   u.ax.pCx->nullRow = 1;
68080   rc = sqlcipher3BtreeOpen(db->pVfs, 0, db, &u.ax.pCx->pBt,
68081                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68082   if( rc==SQLCIPHER_OK ){
68083     rc = sqlcipher3BtreeBeginTrans(u.ax.pCx->pBt, 1);
68084   }
68085   if( rc==SQLCIPHER_OK ){
68086     /* If a transient index is required, create it by calling
68087     ** sqlcipher3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68088     ** opening it. If a transient table is required, just use the
68089     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68090     */
68091     if( pOp->p4.pKeyInfo ){
68092       int pgno;
68093       assert( pOp->p4type==P4_KEYINFO );
68094       rc = sqlcipher3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68095       if( rc==SQLCIPHER_OK ){
68096         assert( pgno==MASTER_ROOT+1 );
68097         rc = sqlcipher3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
68098                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
68099         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68100         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
68101       }
68102       u.ax.pCx->isTable = 0;
68103     }else{
68104       rc = sqlcipher3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
68105       u.ax.pCx->isTable = 1;
68106     }
68107   }
68108   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68109   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
68110   break;
68111 }
68112
68113 /* Opcode: OpenSorter P1 P2 * P4 *
68114 **
68115 ** This opcode works like OP_OpenEphemeral except that it opens
68116 ** a transient index that is specifically designed to sort large
68117 ** tables using an external merge-sort algorithm.
68118 */
68119 case OP_SorterOpen: {
68120 #if 0  /* local variables moved into u.ay */
68121   VdbeCursor *pCx;
68122 #endif /* local variables moved into u.ay */
68123 #ifndef SQLCIPHER_OMIT_MERGE_SORT
68124   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68125   if( u.ay.pCx==0 ) goto no_mem;
68126   u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68127   u.ay.pCx->pKeyInfo->enc = ENC(p->db);
68128   u.ay.pCx->isSorter = 1;
68129   rc = sqlcipher3VdbeSorterInit(db, u.ay.pCx);
68130 #else
68131   pOp->opcode = OP_OpenEphemeral;
68132   pc--;
68133 #endif
68134   break;
68135 }
68136
68137 /* Opcode: OpenPseudo P1 P2 P3 * *
68138 **
68139 ** Open a new cursor that points to a fake table that contains a single
68140 ** row of data.  The content of that one row in the content of memory
68141 ** register P2.  In other words, cursor P1 becomes an alias for the 
68142 ** MEM_Blob content contained in register P2.
68143 **
68144 ** A pseudo-table created by this opcode is used to hold a single
68145 ** row output from the sorter so that the row can be decomposed into
68146 ** individual columns using the OP_Column opcode.  The OP_Column opcode
68147 ** is the only cursor opcode that works with a pseudo-table.
68148 **
68149 ** P3 is the number of fields in the records that will be stored by
68150 ** the pseudo-table.
68151 */
68152 case OP_OpenPseudo: {
68153 #if 0  /* local variables moved into u.az */
68154   VdbeCursor *pCx;
68155 #endif /* local variables moved into u.az */
68156
68157   assert( pOp->p1>=0 );
68158   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68159   if( u.az.pCx==0 ) goto no_mem;
68160   u.az.pCx->nullRow = 1;
68161   u.az.pCx->pseudoTableReg = pOp->p2;
68162   u.az.pCx->isTable = 1;
68163   u.az.pCx->isIndex = 0;
68164   break;
68165 }
68166
68167 /* Opcode: Close P1 * * * *
68168 **
68169 ** Close a cursor previously opened as P1.  If P1 is not
68170 ** currently open, this instruction is a no-op.
68171 */
68172 case OP_Close: {
68173   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68174   sqlcipher3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68175   p->apCsr[pOp->p1] = 0;
68176   break;
68177 }
68178
68179 /* Opcode: SeekGe P1 P2 P3 P4 *
68180 **
68181 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68182 ** use the value in register P3 as the key.  If cursor P1 refers 
68183 ** to an SQL index, then P3 is the first in an array of P4 registers 
68184 ** that are used as an unpacked index key. 
68185 **
68186 ** Reposition cursor P1 so that  it points to the smallest entry that 
68187 ** is greater than or equal to the key value. If there are no records 
68188 ** greater than or equal to the key and P2 is not zero, then jump to P2.
68189 **
68190 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68191 */
68192 /* Opcode: SeekGt P1 P2 P3 P4 *
68193 **
68194 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68195 ** use the value in register P3 as a key. If cursor P1 refers 
68196 ** to an SQL index, then P3 is the first in an array of P4 registers 
68197 ** that are used as an unpacked index key. 
68198 **
68199 ** Reposition cursor P1 so that  it points to the smallest entry that 
68200 ** is greater than the key value. If there are no records greater than 
68201 ** the key and P2 is not zero, then jump to P2.
68202 **
68203 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68204 */
68205 /* Opcode: SeekLt P1 P2 P3 P4 * 
68206 **
68207 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68208 ** use the value in register P3 as a key. If cursor P1 refers 
68209 ** to an SQL index, then P3 is the first in an array of P4 registers 
68210 ** that are used as an unpacked index key. 
68211 **
68212 ** Reposition cursor P1 so that  it points to the largest entry that 
68213 ** is less than the key value. If there are no records less than 
68214 ** the key and P2 is not zero, then jump to P2.
68215 **
68216 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68217 */
68218 /* Opcode: SeekLe P1 P2 P3 P4 *
68219 **
68220 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68221 ** use the value in register P3 as a key. If cursor P1 refers 
68222 ** to an SQL index, then P3 is the first in an array of P4 registers 
68223 ** that are used as an unpacked index key. 
68224 **
68225 ** Reposition cursor P1 so that it points to the largest entry that 
68226 ** is less than or equal to the key value. If there are no records 
68227 ** less than or equal to the key and P2 is not zero, then jump to P2.
68228 **
68229 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68230 */
68231 case OP_SeekLt:         /* jump, in3 */
68232 case OP_SeekLe:         /* jump, in3 */
68233 case OP_SeekGe:         /* jump, in3 */
68234 case OP_SeekGt: {       /* jump, in3 */
68235 #if 0  /* local variables moved into u.ba */
68236   int res;
68237   int oc;
68238   VdbeCursor *pC;
68239   UnpackedRecord r;
68240   int nField;
68241   i64 iKey;      /* The rowid we are to seek to */
68242 #endif /* local variables moved into u.ba */
68243
68244   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68245   assert( pOp->p2!=0 );
68246   u.ba.pC = p->apCsr[pOp->p1];
68247   assert( u.ba.pC!=0 );
68248   assert( u.ba.pC->pseudoTableReg==0 );
68249   assert( OP_SeekLe == OP_SeekLt+1 );
68250   assert( OP_SeekGe == OP_SeekLt+2 );
68251   assert( OP_SeekGt == OP_SeekLt+3 );
68252   assert( u.ba.pC->isOrdered );
68253   if( ALWAYS(u.ba.pC->pCursor!=0) ){
68254     u.ba.oc = pOp->opcode;
68255     u.ba.pC->nullRow = 0;
68256     if( u.ba.pC->isTable ){
68257       /* The input value in P3 might be of any type: integer, real, string,
68258       ** blob, or NULL.  But it needs to be an integer before we can do
68259       ** the seek, so covert it. */
68260       pIn3 = &aMem[pOp->p3];
68261       applyNumericAffinity(pIn3);
68262       u.ba.iKey = sqlcipher3VdbeIntValue(pIn3);
68263       u.ba.pC->rowidIsValid = 0;
68264
68265       /* If the P3 value could not be converted into an integer without
68266       ** loss of information, then special processing is required... */
68267       if( (pIn3->flags & MEM_Int)==0 ){
68268         if( (pIn3->flags & MEM_Real)==0 ){
68269           /* If the P3 value cannot be converted into any kind of a number,
68270           ** then the seek is not possible, so jump to P2 */
68271           pc = pOp->p2 - 1;
68272           break;
68273         }
68274         /* If we reach this point, then the P3 value must be a floating
68275         ** point number. */
68276         assert( (pIn3->flags & MEM_Real)!=0 );
68277
68278         if( u.ba.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.ba.iKey || pIn3->r>0) ){
68279           /* The P3 value is too large in magnitude to be expressed as an
68280           ** integer. */
68281           u.ba.res = 1;
68282           if( pIn3->r<0 ){
68283             if( u.ba.oc>=OP_SeekGe ){  assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
68284               rc = sqlcipher3BtreeFirst(u.ba.pC->pCursor, &u.ba.res);
68285               if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68286             }
68287           }else{
68288             if( u.ba.oc<=OP_SeekLe ){  assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
68289               rc = sqlcipher3BtreeLast(u.ba.pC->pCursor, &u.ba.res);
68290               if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68291             }
68292           }
68293           if( u.ba.res ){
68294             pc = pOp->p2 - 1;
68295           }
68296           break;
68297         }else if( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekGe ){
68298           /* Use the ceiling() function to convert real->int */
68299           if( pIn3->r > (double)u.ba.iKey ) u.ba.iKey++;
68300         }else{
68301           /* Use the floor() function to convert real->int */
68302           assert( u.ba.oc==OP_SeekLe || u.ba.oc==OP_SeekGt );
68303           if( pIn3->r < (double)u.ba.iKey ) u.ba.iKey--;
68304         }
68305       }
68306       rc = sqlcipher3BtreeMovetoUnpacked(u.ba.pC->pCursor, 0, (u64)u.ba.iKey, 0, &u.ba.res);
68307       if( rc!=SQLCIPHER_OK ){
68308         goto abort_due_to_error;
68309       }
68310       if( u.ba.res==0 ){
68311         u.ba.pC->rowidIsValid = 1;
68312         u.ba.pC->lastRowid = u.ba.iKey;
68313       }
68314     }else{
68315       u.ba.nField = pOp->p4.i;
68316       assert( pOp->p4type==P4_INT32 );
68317       assert( u.ba.nField>0 );
68318       u.ba.r.pKeyInfo = u.ba.pC->pKeyInfo;
68319       u.ba.r.nField = (u16)u.ba.nField;
68320
68321       /* The next line of code computes as follows, only faster:
68322       **   if( u.ba.oc==OP_SeekGt || u.ba.oc==OP_SeekLe ){
68323       **     u.ba.r.flags = UNPACKED_INCRKEY;
68324       **   }else{
68325       **     u.ba.r.flags = 0;
68326       **   }
68327       */
68328       u.ba.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.ba.oc - OP_SeekLt)));
68329       assert( u.ba.oc!=OP_SeekGt || u.ba.r.flags==UNPACKED_INCRKEY );
68330       assert( u.ba.oc!=OP_SeekLe || u.ba.r.flags==UNPACKED_INCRKEY );
68331       assert( u.ba.oc!=OP_SeekGe || u.ba.r.flags==0 );
68332       assert( u.ba.oc!=OP_SeekLt || u.ba.r.flags==0 );
68333
68334       u.ba.r.aMem = &aMem[pOp->p3];
68335 #ifdef SQLCIPHER_DEBUG
68336       { int i; for(i=0; i<u.ba.r.nField; i++) assert( memIsValid(&u.ba.r.aMem[i]) ); }
68337 #endif
68338       ExpandBlob(u.ba.r.aMem);
68339       rc = sqlcipher3BtreeMovetoUnpacked(u.ba.pC->pCursor, &u.ba.r, 0, 0, &u.ba.res);
68340       if( rc!=SQLCIPHER_OK ){
68341         goto abort_due_to_error;
68342       }
68343       u.ba.pC->rowidIsValid = 0;
68344     }
68345     u.ba.pC->deferredMoveto = 0;
68346     u.ba.pC->cacheStatus = CACHE_STALE;
68347 #ifdef SQLCIPHER_TEST
68348     sqlcipher3_search_count++;
68349 #endif
68350     if( u.ba.oc>=OP_SeekGe ){  assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
68351       if( u.ba.res<0 || (u.ba.res==0 && u.ba.oc==OP_SeekGt) ){
68352         rc = sqlcipher3BtreeNext(u.ba.pC->pCursor, &u.ba.res);
68353         if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68354         u.ba.pC->rowidIsValid = 0;
68355       }else{
68356         u.ba.res = 0;
68357       }
68358     }else{
68359       assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
68360       if( u.ba.res>0 || (u.ba.res==0 && u.ba.oc==OP_SeekLt) ){
68361         rc = sqlcipher3BtreePrevious(u.ba.pC->pCursor, &u.ba.res);
68362         if( rc!=SQLCIPHER_OK ) goto abort_due_to_error;
68363         u.ba.pC->rowidIsValid = 0;
68364       }else{
68365         /* u.ba.res might be negative because the table is empty.  Check to
68366         ** see if this is the case.
68367         */
68368         u.ba.res = sqlcipher3BtreeEof(u.ba.pC->pCursor);
68369       }
68370     }
68371     assert( pOp->p2>0 );
68372     if( u.ba.res ){
68373       pc = pOp->p2 - 1;
68374     }
68375   }else{
68376     /* This happens when attempting to open the sqlcipher3_master table
68377     ** for read access returns SQLCIPHER_EMPTY. In this case always
68378     ** take the jump (since there are no records in the table).
68379     */
68380     pc = pOp->p2 - 1;
68381   }
68382   break;
68383 }
68384
68385 /* Opcode: Seek P1 P2 * * *
68386 **
68387 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
68388 ** for P1 to move so that it points to the rowid given by P2.
68389 **
68390 ** This is actually a deferred seek.  Nothing actually happens until
68391 ** the cursor is used to read a record.  That way, if no reads
68392 ** occur, no unnecessary I/O happens.
68393 */
68394 case OP_Seek: {    /* in2 */
68395 #if 0  /* local variables moved into u.bb */
68396   VdbeCursor *pC;
68397 #endif /* local variables moved into u.bb */
68398
68399   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68400   u.bb.pC = p->apCsr[pOp->p1];
68401   assert( u.bb.pC!=0 );
68402   if( ALWAYS(u.bb.pC->pCursor!=0) ){
68403     assert( u.bb.pC->isTable );
68404     u.bb.pC->nullRow = 0;
68405     pIn2 = &aMem[pOp->p2];
68406     u.bb.pC->movetoTarget = sqlcipher3VdbeIntValue(pIn2);
68407     u.bb.pC->rowidIsValid = 0;
68408     u.bb.pC->deferredMoveto = 1;
68409   }
68410   break;
68411 }
68412   
68413
68414 /* Opcode: Found P1 P2 P3 P4 *
68415 **
68416 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68417 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
68418 ** record.
68419 **
68420 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68421 ** is a prefix of any entry in P1 then a jump is made to P2 and
68422 ** P1 is left pointing at the matching entry.
68423 */
68424 /* Opcode: NotFound P1 P2 P3 P4 *
68425 **
68426 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68427 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
68428 ** record.
68429 ** 
68430 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68431 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
68432 ** does contain an entry whose prefix matches the P3/P4 record then control
68433 ** falls through to the next instruction and P1 is left pointing at the
68434 ** matching entry.
68435 **
68436 ** See also: Found, NotExists, IsUnique
68437 */
68438 case OP_NotFound:       /* jump, in3 */
68439 case OP_Found: {        /* jump, in3 */
68440 #if 0  /* local variables moved into u.bc */
68441   int alreadyExists;
68442   VdbeCursor *pC;
68443   int res;
68444   char *pFree;
68445   UnpackedRecord *pIdxKey;
68446   UnpackedRecord r;
68447   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
68448 #endif /* local variables moved into u.bc */
68449
68450 #ifdef SQLCIPHER_TEST
68451   sqlcipher3_found_count++;
68452 #endif
68453
68454   u.bc.alreadyExists = 0;
68455   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68456   assert( pOp->p4type==P4_INT32 );
68457   u.bc.pC = p->apCsr[pOp->p1];
68458   assert( u.bc.pC!=0 );
68459   pIn3 = &aMem[pOp->p3];
68460   if( ALWAYS(u.bc.pC->pCursor!=0) ){
68461
68462     assert( u.bc.pC->isTable==0 );
68463     if( pOp->p4.i>0 ){
68464       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
68465       u.bc.r.nField = (u16)pOp->p4.i;
68466       u.bc.r.aMem = pIn3;
68467 #ifdef SQLCIPHER_DEBUG
68468       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
68469 #endif
68470       u.bc.r.flags = UNPACKED_PREFIX_MATCH;
68471       u.bc.pIdxKey = &u.bc.r;
68472     }else{
68473       u.bc.pIdxKey = sqlcipher3VdbeAllocUnpackedRecord(
68474           u.bc.pC->pKeyInfo, u.bc.aTempRec, sizeof(u.bc.aTempRec), &u.bc.pFree
68475       );
68476       if( u.bc.pIdxKey==0 ) goto no_mem;
68477       assert( pIn3->flags & MEM_Blob );
68478       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
68479       sqlcipher3VdbeRecordUnpack(u.bc.pC->pKeyInfo, pIn3->n, pIn3->z, u.bc.pIdxKey);
68480       u.bc.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
68481     }
68482     rc = sqlcipher3BtreeMovetoUnpacked(u.bc.pC->pCursor, u.bc.pIdxKey, 0, 0, &u.bc.res);
68483     if( pOp->p4.i==0 ){
68484       sqlcipher3DbFree(db, u.bc.pFree);
68485     }
68486     if( rc!=SQLCIPHER_OK ){
68487       break;
68488     }
68489     u.bc.alreadyExists = (u.bc.res==0);
68490     u.bc.pC->deferredMoveto = 0;
68491     u.bc.pC->cacheStatus = CACHE_STALE;
68492   }
68493   if( pOp->opcode==OP_Found ){
68494     if( u.bc.alreadyExists ) pc = pOp->p2 - 1;
68495   }else{
68496     if( !u.bc.alreadyExists ) pc = pOp->p2 - 1;
68497   }
68498   break;
68499 }
68500
68501 /* Opcode: IsUnique P1 P2 P3 P4 *
68502 **
68503 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
68504 ** no data and where the key are records generated by OP_MakeRecord with
68505 ** the list field being the integer ROWID of the entry that the index
68506 ** entry refers to.
68507 **
68508 ** The P3 register contains an integer record number. Call this record 
68509 ** number R. Register P4 is the first in a set of N contiguous registers
68510 ** that make up an unpacked index key that can be used with cursor P1.
68511 ** The value of N can be inferred from the cursor. N includes the rowid
68512 ** value appended to the end of the index record. This rowid value may
68513 ** or may not be the same as R.
68514 **
68515 ** If any of the N registers beginning with register P4 contains a NULL
68516 ** value, jump immediately to P2.
68517 **
68518 ** Otherwise, this instruction checks if cursor P1 contains an entry
68519 ** where the first (N-1) fields match but the rowid value at the end
68520 ** of the index entry is not R. If there is no such entry, control jumps
68521 ** to instruction P2. Otherwise, the rowid of the conflicting index
68522 ** entry is copied to register P3 and control falls through to the next
68523 ** instruction.
68524 **
68525 ** See also: NotFound, NotExists, Found
68526 */
68527 case OP_IsUnique: {        /* jump, in3 */
68528 #if 0  /* local variables moved into u.bd */
68529   u16 ii;
68530   VdbeCursor *pCx;
68531   BtCursor *pCrsr;
68532   u16 nField;
68533   Mem *aMx;
68534   UnpackedRecord r;                  /* B-Tree index search key */
68535   i64 R;                             /* Rowid stored in register P3 */
68536 #endif /* local variables moved into u.bd */
68537
68538   pIn3 = &aMem[pOp->p3];
68539   u.bd.aMx = &aMem[pOp->p4.i];
68540   /* Assert that the values of parameters P1 and P4 are in range. */
68541   assert( pOp->p4type==P4_INT32 );
68542   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
68543   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68544
68545   /* Find the index cursor. */
68546   u.bd.pCx = p->apCsr[pOp->p1];
68547   assert( u.bd.pCx->deferredMoveto==0 );
68548   u.bd.pCx->seekResult = 0;
68549   u.bd.pCx->cacheStatus = CACHE_STALE;
68550   u.bd.pCrsr = u.bd.pCx->pCursor;
68551
68552   /* If any of the values are NULL, take the jump. */
68553   u.bd.nField = u.bd.pCx->pKeyInfo->nField;
68554   for(u.bd.ii=0; u.bd.ii<u.bd.nField; u.bd.ii++){
68555     if( u.bd.aMx[u.bd.ii].flags & MEM_Null ){
68556       pc = pOp->p2 - 1;
68557       u.bd.pCrsr = 0;
68558       break;
68559     }
68560   }
68561   assert( (u.bd.aMx[u.bd.nField].flags & MEM_Null)==0 );
68562
68563   if( u.bd.pCrsr!=0 ){
68564     /* Populate the index search key. */
68565     u.bd.r.pKeyInfo = u.bd.pCx->pKeyInfo;
68566     u.bd.r.nField = u.bd.nField + 1;
68567     u.bd.r.flags = UNPACKED_PREFIX_SEARCH;
68568     u.bd.r.aMem = u.bd.aMx;
68569 #ifdef SQLCIPHER_DEBUG
68570     { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
68571 #endif
68572
68573     /* Extract the value of u.bd.R from register P3. */
68574     sqlcipher3VdbeMemIntegerify(pIn3);
68575     u.bd.R = pIn3->u.i;
68576
68577     /* Search the B-Tree index. If no conflicting record is found, jump
68578     ** to P2. Otherwise, copy the rowid of the conflicting record to
68579     ** register P3 and fall through to the next instruction.  */
68580     rc = sqlcipher3BtreeMovetoUnpacked(u.bd.pCrsr, &u.bd.r, 0, 0, &u.bd.pCx->seekResult);
68581     if( (u.bd.r.flags & UNPACKED_PREFIX_SEARCH) || u.bd.r.rowid==u.bd.R ){
68582       pc = pOp->p2 - 1;
68583     }else{
68584       pIn3->u.i = u.bd.r.rowid;
68585     }
68586   }
68587   break;
68588 }
68589
68590 /* Opcode: NotExists P1 P2 P3 * *
68591 **
68592 ** Use the content of register P3 as an integer key.  If a record 
68593 ** with that key does not exist in table of P1, then jump to P2. 
68594 ** If the record does exist, then fall through.  The cursor is left 
68595 ** pointing to the record if it exists.
68596 **
68597 ** The difference between this operation and NotFound is that this
68598 ** operation assumes the key is an integer and that P1 is a table whereas
68599 ** NotFound assumes key is a blob constructed from MakeRecord and
68600 ** P1 is an index.
68601 **
68602 ** See also: Found, NotFound, IsUnique
68603 */
68604 case OP_NotExists: {        /* jump, in3 */
68605 #if 0  /* local variables moved into u.be */
68606   VdbeCursor *pC;
68607   BtCursor *pCrsr;
68608   int res;
68609   u64 iKey;
68610 #endif /* local variables moved into u.be */
68611
68612   pIn3 = &aMem[pOp->p3];
68613   assert( pIn3->flags & MEM_Int );
68614   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68615   u.be.pC = p->apCsr[pOp->p1];
68616   assert( u.be.pC!=0 );
68617   assert( u.be.pC->isTable );
68618   assert( u.be.pC->pseudoTableReg==0 );
68619   u.be.pCrsr = u.be.pC->pCursor;
68620   if( ALWAYS(u.be.pCrsr!=0) ){
68621     u.be.res = 0;
68622     u.be.iKey = pIn3->u.i;
68623     rc = sqlcipher3BtreeMovetoUnpacked(u.be.pCrsr, 0, u.be.iKey, 0, &u.be.res);
68624     u.be.pC->lastRowid = pIn3->u.i;
68625     u.be.pC->rowidIsValid = u.be.res==0 ?1:0;
68626     u.be.pC->nullRow = 0;
68627     u.be.pC->cacheStatus = CACHE_STALE;
68628     u.be.pC->deferredMoveto = 0;
68629     if( u.be.res!=0 ){
68630       pc = pOp->p2 - 1;
68631       assert( u.be.pC->rowidIsValid==0 );
68632     }
68633     u.be.pC->seekResult = u.be.res;
68634   }else{
68635     /* This happens when an attempt to open a read cursor on the
68636     ** sqlcipher_master table returns SQLCIPHER_EMPTY.
68637     */
68638     pc = pOp->p2 - 1;
68639     assert( u.be.pC->rowidIsValid==0 );
68640     u.be.pC->seekResult = 0;
68641   }
68642   break;
68643 }
68644
68645 /* Opcode: Sequence P1 P2 * * *
68646 **
68647 ** Find the next available sequence number for cursor P1.
68648 ** Write the sequence number into register P2.
68649 ** The sequence number on the cursor is incremented after this
68650 ** instruction.  
68651 */
68652 case OP_Sequence: {           /* out2-prerelease */
68653   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68654   assert( p->apCsr[pOp->p1]!=0 );
68655   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
68656   break;
68657 }
68658
68659
68660 /* Opcode: NewRowid P1 P2 P3 * *
68661 **
68662 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
68663 ** The record number is not previously used as a key in the database
68664 ** table that cursor P1 points to.  The new record number is written
68665 ** written to register P2.
68666 **
68667 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
68668 ** the largest previously generated record number. No new record numbers are
68669 ** allowed to be less than this value. When this value reaches its maximum, 
68670 ** an SQLCIPHER_FULL error is generated. The P3 register is updated with the '
68671 ** generated record number. This P3 mechanism is used to help implement the
68672 ** AUTOINCREMENT feature.
68673 */
68674 case OP_NewRowid: {           /* out2-prerelease */
68675 #if 0  /* local variables moved into u.bf */
68676   i64 v;                 /* The new rowid */
68677   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
68678   int res;               /* Result of an sqlcipher3BtreeLast() */
68679   int cnt;               /* Counter to limit the number of searches */
68680   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
68681   VdbeFrame *pFrame;     /* Root frame of VDBE */
68682 #endif /* local variables moved into u.bf */
68683
68684   u.bf.v = 0;
68685   u.bf.res = 0;
68686   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68687   u.bf.pC = p->apCsr[pOp->p1];
68688   assert( u.bf.pC!=0 );
68689   if( NEVER(u.bf.pC->pCursor==0) ){
68690     /* The zero initialization above is all that is needed */
68691   }else{
68692     /* The next rowid or record number (different terms for the same
68693     ** thing) is obtained in a two-step algorithm.
68694     **
68695     ** First we attempt to find the largest existing rowid and add one
68696     ** to that.  But if the largest existing rowid is already the maximum
68697     ** positive integer, we have to fall through to the second
68698     ** probabilistic algorithm
68699     **
68700     ** The second algorithm is to select a rowid at random and see if
68701     ** it already exists in the table.  If it does not exist, we have
68702     ** succeeded.  If the random rowid does exist, we select a new one
68703     ** and try again, up to 100 times.
68704     */
68705     assert( u.bf.pC->isTable );
68706
68707 #ifdef SQLCIPHER_32BIT_ROWID
68708 #   define MAX_ROWID 0x7fffffff
68709 #else
68710     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
68711     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
68712     ** to provide the constant while making all compilers happy.
68713     */
68714 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
68715 #endif
68716
68717     if( !u.bf.pC->useRandomRowid ){
68718       u.bf.v = sqlcipher3BtreeGetCachedRowid(u.bf.pC->pCursor);
68719       if( u.bf.v==0 ){
68720         rc = sqlcipher3BtreeLast(u.bf.pC->pCursor, &u.bf.res);
68721         if( rc!=SQLCIPHER_OK ){
68722           goto abort_due_to_error;
68723         }
68724         if( u.bf.res ){
68725           u.bf.v = 1;   /* IMP: R-61914-48074 */
68726         }else{
68727           assert( sqlcipher3BtreeCursorIsValid(u.bf.pC->pCursor) );
68728           rc = sqlcipher3BtreeKeySize(u.bf.pC->pCursor, &u.bf.v);
68729           assert( rc==SQLCIPHER_OK );   /* Cannot fail following BtreeLast() */
68730           if( u.bf.v==MAX_ROWID ){
68731             u.bf.pC->useRandomRowid = 1;
68732           }else{
68733             u.bf.v++;   /* IMP: R-29538-34987 */
68734           }
68735         }
68736       }
68737
68738 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
68739       if( pOp->p3 ){
68740         /* Assert that P3 is a valid memory cell. */
68741         assert( pOp->p3>0 );
68742         if( p->pFrame ){
68743           for(u.bf.pFrame=p->pFrame; u.bf.pFrame->pParent; u.bf.pFrame=u.bf.pFrame->pParent);
68744           /* Assert that P3 is a valid memory cell. */
68745           assert( pOp->p3<=u.bf.pFrame->nMem );
68746           u.bf.pMem = &u.bf.pFrame->aMem[pOp->p3];
68747         }else{
68748           /* Assert that P3 is a valid memory cell. */
68749           assert( pOp->p3<=p->nMem );
68750           u.bf.pMem = &aMem[pOp->p3];
68751           memAboutToChange(p, u.bf.pMem);
68752         }
68753         assert( memIsValid(u.bf.pMem) );
68754
68755         REGISTER_TRACE(pOp->p3, u.bf.pMem);
68756         sqlcipher3VdbeMemIntegerify(u.bf.pMem);
68757         assert( (u.bf.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
68758         if( u.bf.pMem->u.i==MAX_ROWID || u.bf.pC->useRandomRowid ){
68759           rc = SQLCIPHER_FULL;   /* IMP: R-12275-61338 */
68760           goto abort_due_to_error;
68761         }
68762         if( u.bf.v<u.bf.pMem->u.i+1 ){
68763           u.bf.v = u.bf.pMem->u.i + 1;
68764         }
68765         u.bf.pMem->u.i = u.bf.v;
68766       }
68767 #endif
68768
68769       sqlcipher3BtreeSetCachedRowid(u.bf.pC->pCursor, u.bf.v<MAX_ROWID ? u.bf.v+1 : 0);
68770     }
68771     if( u.bf.pC->useRandomRowid ){
68772       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
68773       ** largest possible integer (9223372036854775807) then the database
68774       ** engine starts picking positive candidate ROWIDs at random until
68775       ** it finds one that is not previously used. */
68776       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
68777                              ** an AUTOINCREMENT table. */
68778       /* on the first attempt, simply do one more than previous */
68779       u.bf.v = lastRowid;
68780       u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68781       u.bf.v++; /* ensure non-zero */
68782       u.bf.cnt = 0;
68783       while(   ((rc = sqlcipher3BtreeMovetoUnpacked(u.bf.pC->pCursor, 0, (u64)u.bf.v,
68784                                                  0, &u.bf.res))==SQLCIPHER_OK)
68785             && (u.bf.res==0)
68786             && (++u.bf.cnt<100)){
68787         /* collision - try another random rowid */
68788         sqlcipher3_randomness(sizeof(u.bf.v), &u.bf.v);
68789         if( u.bf.cnt<5 ){
68790           /* try "small" random rowids for the initial attempts */
68791           u.bf.v &= 0xffffff;
68792         }else{
68793           u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68794         }
68795         u.bf.v++; /* ensure non-zero */
68796       }
68797       if( rc==SQLCIPHER_OK && u.bf.res==0 ){
68798         rc = SQLCIPHER_FULL;   /* IMP: R-38219-53002 */
68799         goto abort_due_to_error;
68800       }
68801       assert( u.bf.v>0 );  /* EV: R-40812-03570 */
68802     }
68803     u.bf.pC->rowidIsValid = 0;
68804     u.bf.pC->deferredMoveto = 0;
68805     u.bf.pC->cacheStatus = CACHE_STALE;
68806   }
68807   pOut->u.i = u.bf.v;
68808   break;
68809 }
68810
68811 /* Opcode: Insert P1 P2 P3 P4 P5
68812 **
68813 ** Write an entry into the table of cursor P1.  A new entry is
68814 ** created if it doesn't already exist or the data for an existing
68815 ** entry is overwritten.  The data is the value MEM_Blob stored in register
68816 ** number P2. The key is stored in register P3. The key must
68817 ** be a MEM_Int.
68818 **
68819 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
68820 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
68821 ** then rowid is stored for subsequent return by the
68822 ** sqlcipher3_last_insert_rowid() function (otherwise it is unmodified).
68823 **
68824 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
68825 ** the last seek operation (OP_NotExists) was a success, then this
68826 ** operation will not attempt to find the appropriate row before doing
68827 ** the insert but will instead overwrite the row that the cursor is
68828 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
68829 ** has already positioned the cursor correctly.  This is an optimization
68830 ** that boosts performance by avoiding redundant seeks.
68831 **
68832 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68833 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68834 ** is part of an INSERT operation.  The difference is only important to
68835 ** the update hook.
68836 **
68837 ** Parameter P4 may point to a string containing the table-name, or
68838 ** may be NULL. If it is not NULL, then the update-hook 
68839 ** (sqlcipher3.xUpdateCallback) is invoked following a successful insert.
68840 **
68841 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68842 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
68843 ** and register P2 becomes ephemeral.  If the cursor is changed, the
68844 ** value of register P2 will then change.  Make sure this does not
68845 ** cause any problems.)
68846 **
68847 ** This instruction only works on tables.  The equivalent instruction
68848 ** for indices is OP_IdxInsert.
68849 */
68850 /* Opcode: InsertInt P1 P2 P3 P4 P5
68851 **
68852 ** This works exactly like OP_Insert except that the key is the
68853 ** integer value P3, not the value of the integer stored in register P3.
68854 */
68855 case OP_Insert: 
68856 case OP_InsertInt: {
68857 #if 0  /* local variables moved into u.bg */
68858   Mem *pData;       /* MEM cell holding data for the record to be inserted */
68859   Mem *pKey;        /* MEM cell holding key  for the record */
68860   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68861   VdbeCursor *pC;   /* Cursor to table into which insert is written */
68862   int nZero;        /* Number of zero-bytes to append */
68863   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68864   const char *zDb;  /* database name - used by the update hook */
68865   const char *zTbl; /* Table name - used by the opdate hook */
68866   int op;           /* Opcode for update hook: SQLCIPHER_UPDATE or SQLCIPHER_INSERT */
68867 #endif /* local variables moved into u.bg */
68868
68869   u.bg.pData = &aMem[pOp->p2];
68870   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68871   assert( memIsValid(u.bg.pData) );
68872   u.bg.pC = p->apCsr[pOp->p1];
68873   assert( u.bg.pC!=0 );
68874   assert( u.bg.pC->pCursor!=0 );
68875   assert( u.bg.pC->pseudoTableReg==0 );
68876   assert( u.bg.pC->isTable );
68877   REGISTER_TRACE(pOp->p2, u.bg.pData);
68878
68879   if( pOp->opcode==OP_Insert ){
68880     u.bg.pKey = &aMem[pOp->p3];
68881     assert( u.bg.pKey->flags & MEM_Int );
68882     assert( memIsValid(u.bg.pKey) );
68883     REGISTER_TRACE(pOp->p3, u.bg.pKey);
68884     u.bg.iKey = u.bg.pKey->u.i;
68885   }else{
68886     assert( pOp->opcode==OP_InsertInt );
68887     u.bg.iKey = pOp->p3;
68888   }
68889
68890   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68891   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bg.iKey;
68892   if( u.bg.pData->flags & MEM_Null ){
68893     u.bg.pData->z = 0;
68894     u.bg.pData->n = 0;
68895   }else{
68896     assert( u.bg.pData->flags & (MEM_Blob|MEM_Str) );
68897   }
68898   u.bg.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bg.pC->seekResult : 0);
68899   if( u.bg.pData->flags & MEM_Zero ){
68900     u.bg.nZero = u.bg.pData->u.nZero;
68901   }else{
68902     u.bg.nZero = 0;
68903   }
68904   sqlcipher3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
68905   rc = sqlcipher3BtreeInsert(u.bg.pC->pCursor, 0, u.bg.iKey,
68906                           u.bg.pData->z, u.bg.pData->n, u.bg.nZero,
68907                           pOp->p5 & OPFLAG_APPEND, u.bg.seekResult
68908   );
68909   u.bg.pC->rowidIsValid = 0;
68910   u.bg.pC->deferredMoveto = 0;
68911   u.bg.pC->cacheStatus = CACHE_STALE;
68912
68913   /* Invoke the update-hook if required. */
68914   if( rc==SQLCIPHER_OK && db->xUpdateCallback && pOp->p4.z ){
68915     u.bg.zDb = db->aDb[u.bg.pC->iDb].zName;
68916     u.bg.zTbl = pOp->p4.z;
68917     u.bg.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLCIPHER_UPDATE : SQLCIPHER_INSERT);
68918     assert( u.bg.pC->isTable );
68919     db->xUpdateCallback(db->pUpdateArg, u.bg.op, u.bg.zDb, u.bg.zTbl, u.bg.iKey);
68920     assert( u.bg.pC->iDb>=0 );
68921   }
68922   break;
68923 }
68924
68925 /* Opcode: Delete P1 P2 * P4 *
68926 **
68927 ** Delete the record at which the P1 cursor is currently pointing.
68928 **
68929 ** The cursor will be left pointing at either the next or the previous
68930 ** record in the table. If it is left pointing at the next record, then
68931 ** the next Next instruction will be a no-op.  Hence it is OK to delete
68932 ** a record from within an Next loop.
68933 **
68934 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68935 ** incremented (otherwise not).
68936 **
68937 ** P1 must not be pseudo-table.  It has to be a real table with
68938 ** multiple rows.
68939 **
68940 ** If P4 is not NULL, then it is the name of the table that P1 is
68941 ** pointing to.  The update hook will be invoked, if it exists.
68942 ** If P4 is not NULL then the P1 cursor must have been positioned
68943 ** using OP_NotFound prior to invoking this opcode.
68944 */
68945 case OP_Delete: {
68946 #if 0  /* local variables moved into u.bh */
68947   i64 iKey;
68948   VdbeCursor *pC;
68949 #endif /* local variables moved into u.bh */
68950
68951   u.bh.iKey = 0;
68952   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68953   u.bh.pC = p->apCsr[pOp->p1];
68954   assert( u.bh.pC!=0 );
68955   assert( u.bh.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68956
68957   /* If the update-hook will be invoked, set u.bh.iKey to the rowid of the
68958   ** row being deleted.
68959   */
68960   if( db->xUpdateCallback && pOp->p4.z ){
68961     assert( u.bh.pC->isTable );
68962     assert( u.bh.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
68963     u.bh.iKey = u.bh.pC->lastRowid;
68964   }
68965
68966   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
68967   ** OP_Column on the same table without any intervening operations that
68968   ** might move or invalidate the cursor.  Hence cursor u.bh.pC is always pointing
68969   ** to the row to be deleted and the sqlcipher3VdbeCursorMoveto() operation
68970   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
68971   ** to guard against future changes to the code generator.
68972   **/
68973   assert( u.bh.pC->deferredMoveto==0 );
68974   rc = sqlcipher3VdbeCursorMoveto(u.bh.pC);
68975   if( NEVER(rc!=SQLCIPHER_OK) ) goto abort_due_to_error;
68976
68977   sqlcipher3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
68978   rc = sqlcipher3BtreeDelete(u.bh.pC->pCursor);
68979   u.bh.pC->cacheStatus = CACHE_STALE;
68980
68981   /* Invoke the update-hook if required. */
68982   if( rc==SQLCIPHER_OK && db->xUpdateCallback && pOp->p4.z ){
68983     const char *zDb = db->aDb[u.bh.pC->iDb].zName;
68984     const char *zTbl = pOp->p4.z;
68985     db->xUpdateCallback(db->pUpdateArg, SQLCIPHER_DELETE, zDb, zTbl, u.bh.iKey);
68986     assert( u.bh.pC->iDb>=0 );
68987   }
68988   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
68989   break;
68990 }
68991 /* Opcode: ResetCount * * * * *
68992 **
68993 ** The value of the change counter is copied to the database handle
68994 ** change counter (returned by subsequent calls to sqlcipher3_changes()).
68995 ** Then the VMs internal change counter resets to 0.
68996 ** This is used by trigger programs.
68997 */
68998 case OP_ResetCount: {
68999   sqlcipher3VdbeSetChanges(db, p->nChange);
69000   p->nChange = 0;
69001   break;
69002 }
69003
69004 /* Opcode: SorterCompare P1 P2 P3
69005 **
69006 ** P1 is a sorter cursor. This instruction compares the record blob in 
69007 ** register P3 with the entry that the sorter cursor currently points to.
69008 ** If, excluding the rowid fields at the end, the two records are a match,
69009 ** fall through to the next instruction. Otherwise, jump to instruction P2.
69010 */
69011 case OP_SorterCompare: {
69012 #if 0  /* local variables moved into u.bi */
69013   VdbeCursor *pC;
69014   int res;
69015 #endif /* local variables moved into u.bi */
69016
69017   u.bi.pC = p->apCsr[pOp->p1];
69018   assert( isSorter(u.bi.pC) );
69019   pIn3 = &aMem[pOp->p3];
69020   rc = sqlcipher3VdbeSorterCompare(u.bi.pC, pIn3, &u.bi.res);
69021   if( u.bi.res ){
69022     pc = pOp->p2-1;
69023   }
69024   break;
69025 };
69026
69027 /* Opcode: SorterData P1 P2 * * *
69028 **
69029 ** Write into register P2 the current sorter data for sorter cursor P1.
69030 */
69031 case OP_SorterData: {
69032 #if 0  /* local variables moved into u.bj */
69033   VdbeCursor *pC;
69034 #endif /* local variables moved into u.bj */
69035 #ifndef SQLCIPHER_OMIT_MERGE_SORT
69036   pOut = &aMem[pOp->p2];
69037   u.bj.pC = p->apCsr[pOp->p1];
69038   assert( u.bj.pC->isSorter );
69039   rc = sqlcipher3VdbeSorterRowkey(u.bj.pC, pOut);
69040 #else
69041   pOp->opcode = OP_RowKey;
69042   pc--;
69043 #endif
69044   break;
69045 }
69046
69047 /* Opcode: RowData P1 P2 * * *
69048 **
69049 ** Write into register P2 the complete row data for cursor P1.
69050 ** There is no interpretation of the data.  
69051 ** It is just copied onto the P2 register exactly as 
69052 ** it is found in the database file.
69053 **
69054 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69055 ** of a real table, not a pseudo-table.
69056 */
69057 /* Opcode: RowKey P1 P2 * * *
69058 **
69059 ** Write into register P2 the complete row key for cursor P1.
69060 ** There is no interpretation of the data.  
69061 ** The key is copied onto the P3 register exactly as 
69062 ** it is found in the database file.
69063 **
69064 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69065 ** of a real table, not a pseudo-table.
69066 */
69067 case OP_RowKey:
69068 case OP_RowData: {
69069 #if 0  /* local variables moved into u.bk */
69070   VdbeCursor *pC;
69071   BtCursor *pCrsr;
69072   u32 n;
69073   i64 n64;
69074 #endif /* local variables moved into u.bk */
69075
69076   pOut = &aMem[pOp->p2];
69077   memAboutToChange(p, pOut);
69078
69079   /* Note that RowKey and RowData are really exactly the same instruction */
69080   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69081   u.bk.pC = p->apCsr[pOp->p1];
69082   assert( u.bk.pC->isSorter==0 );
69083   assert( u.bk.pC->isTable || pOp->opcode!=OP_RowData );
69084   assert( u.bk.pC->isIndex || pOp->opcode==OP_RowData );
69085   assert( u.bk.pC!=0 );
69086   assert( u.bk.pC->nullRow==0 );
69087   assert( u.bk.pC->pseudoTableReg==0 );
69088   assert( !u.bk.pC->isSorter );
69089   assert( u.bk.pC->pCursor!=0 );
69090   u.bk.pCrsr = u.bk.pC->pCursor;
69091   assert( sqlcipher3BtreeCursorIsValid(u.bk.pCrsr) );
69092
69093   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69094   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69095   ** the cursor.  Hence the following sqlcipher3VdbeCursorMoveto() call is always
69096   ** a no-op and can never fail.  But we leave it in place as a safety.
69097   */
69098   assert( u.bk.pC->deferredMoveto==0 );
69099   rc = sqlcipher3VdbeCursorMoveto(u.bk.pC);
69100   if( NEVER(rc!=SQLCIPHER_OK) ) goto abort_due_to_error;
69101
69102   if( u.bk.pC->isIndex ){
69103     assert( !u.bk.pC->isTable );
69104     VVA_ONLY(rc =) sqlcipher3BtreeKeySize(u.bk.pCrsr, &u.bk.n64);
69105     assert( rc==SQLCIPHER_OK );    /* True because of CursorMoveto() call above */
69106     if( u.bk.n64>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
69107       goto too_big;
69108     }
69109     u.bk.n = (u32)u.bk.n64;
69110   }else{
69111     VVA_ONLY(rc =) sqlcipher3BtreeDataSize(u.bk.pCrsr, &u.bk.n);
69112     assert( rc==SQLCIPHER_OK );    /* DataSize() cannot fail */
69113     if( u.bk.n>(u32)db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
69114       goto too_big;
69115     }
69116   }
69117   if( sqlcipher3VdbeMemGrow(pOut, u.bk.n, 0) ){
69118     goto no_mem;
69119   }
69120   pOut->n = u.bk.n;
69121   MemSetTypeFlag(pOut, MEM_Blob);
69122   if( u.bk.pC->isIndex ){
69123     rc = sqlcipher3BtreeKey(u.bk.pCrsr, 0, u.bk.n, pOut->z);
69124   }else{
69125     rc = sqlcipher3BtreeData(u.bk.pCrsr, 0, u.bk.n, pOut->z);
69126   }
69127   pOut->enc = SQLCIPHER_UTF8;  /* In case the blob is ever cast to text */
69128   UPDATE_MAX_BLOBSIZE(pOut);
69129   break;
69130 }
69131
69132 /* Opcode: Rowid P1 P2 * * *
69133 **
69134 ** Store in register P2 an integer which is the key of the table entry that
69135 ** P1 is currently point to.
69136 **
69137 ** P1 can be either an ordinary table or a virtual table.  There used to
69138 ** be a separate OP_VRowid opcode for use with virtual tables, but this
69139 ** one opcode now works for both table types.
69140 */
69141 case OP_Rowid: {                 /* out2-prerelease */
69142 #if 0  /* local variables moved into u.bl */
69143   VdbeCursor *pC;
69144   i64 v;
69145   sqlcipher3_vtab *pVtab;
69146   const sqlcipher3_module *pModule;
69147 #endif /* local variables moved into u.bl */
69148
69149   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69150   u.bl.pC = p->apCsr[pOp->p1];
69151   assert( u.bl.pC!=0 );
69152   assert( u.bl.pC->pseudoTableReg==0 );
69153   if( u.bl.pC->nullRow ){
69154     pOut->flags = MEM_Null;
69155     break;
69156   }else if( u.bl.pC->deferredMoveto ){
69157     u.bl.v = u.bl.pC->movetoTarget;
69158 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
69159   }else if( u.bl.pC->pVtabCursor ){
69160     u.bl.pVtab = u.bl.pC->pVtabCursor->pVtab;
69161     u.bl.pModule = u.bl.pVtab->pModule;
69162     assert( u.bl.pModule->xRowid );
69163     rc = u.bl.pModule->xRowid(u.bl.pC->pVtabCursor, &u.bl.v);
69164     importVtabErrMsg(p, u.bl.pVtab);
69165 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
69166   }else{
69167     assert( u.bl.pC->pCursor!=0 );
69168     rc = sqlcipher3VdbeCursorMoveto(u.bl.pC);
69169     if( rc ) goto abort_due_to_error;
69170     if( u.bl.pC->rowidIsValid ){
69171       u.bl.v = u.bl.pC->lastRowid;
69172     }else{
69173       rc = sqlcipher3BtreeKeySize(u.bl.pC->pCursor, &u.bl.v);
69174       assert( rc==SQLCIPHER_OK );  /* Always so because of CursorMoveto() above */
69175     }
69176   }
69177   pOut->u.i = u.bl.v;
69178   break;
69179 }
69180
69181 /* Opcode: NullRow P1 * * * *
69182 **
69183 ** Move the cursor P1 to a null row.  Any OP_Column operations
69184 ** that occur while the cursor is on the null row will always
69185 ** write a NULL.
69186 */
69187 case OP_NullRow: {
69188 #if 0  /* local variables moved into u.bm */
69189   VdbeCursor *pC;
69190 #endif /* local variables moved into u.bm */
69191
69192   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69193   u.bm.pC = p->apCsr[pOp->p1];
69194   assert( u.bm.pC!=0 );
69195   u.bm.pC->nullRow = 1;
69196   u.bm.pC->rowidIsValid = 0;
69197   assert( u.bm.pC->pCursor || u.bm.pC->pVtabCursor );
69198   if( u.bm.pC->pCursor ){
69199     sqlcipher3BtreeClearCursor(u.bm.pC->pCursor);
69200   }
69201   break;
69202 }
69203
69204 /* Opcode: Last P1 P2 * * *
69205 **
69206 ** The next use of the Rowid or Column or Next instruction for P1 
69207 ** will refer to the last entry in the database table or index.
69208 ** If the table or index is empty and P2>0, then jump immediately to P2.
69209 ** If P2 is 0 or if the table or index is not empty, fall through
69210 ** to the following instruction.
69211 */
69212 case OP_Last: {        /* jump */
69213 #if 0  /* local variables moved into u.bn */
69214   VdbeCursor *pC;
69215   BtCursor *pCrsr;
69216   int res;
69217 #endif /* local variables moved into u.bn */
69218
69219   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69220   u.bn.pC = p->apCsr[pOp->p1];
69221   assert( u.bn.pC!=0 );
69222   u.bn.pCrsr = u.bn.pC->pCursor;
69223   u.bn.res = 0;
69224   if( ALWAYS(u.bn.pCrsr!=0) ){
69225     rc = sqlcipher3BtreeLast(u.bn.pCrsr, &u.bn.res);
69226   }
69227   u.bn.pC->nullRow = (u8)u.bn.res;
69228   u.bn.pC->deferredMoveto = 0;
69229   u.bn.pC->rowidIsValid = 0;
69230   u.bn.pC->cacheStatus = CACHE_STALE;
69231   if( pOp->p2>0 && u.bn.res ){
69232     pc = pOp->p2 - 1;
69233   }
69234   break;
69235 }
69236
69237
69238 /* Opcode: Sort P1 P2 * * *
69239 **
69240 ** This opcode does exactly the same thing as OP_Rewind except that
69241 ** it increments an undocumented global variable used for testing.
69242 **
69243 ** Sorting is accomplished by writing records into a sorting index,
69244 ** then rewinding that index and playing it back from beginning to
69245 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
69246 ** rewinding so that the global variable will be incremented and
69247 ** regression tests can determine whether or not the optimizer is
69248 ** correctly optimizing out sorts.
69249 */
69250 case OP_SorterSort:    /* jump */
69251 #ifdef SQLCIPHER_OMIT_MERGE_SORT
69252   pOp->opcode = OP_Sort;
69253 #endif
69254 case OP_Sort: {        /* jump */
69255 #ifdef SQLCIPHER_TEST
69256   sqlcipher3_sort_count++;
69257   sqlcipher3_search_count--;
69258 #endif
69259   p->aCounter[SQLCIPHER_STMTSTATUS_SORT-1]++;
69260   /* Fall through into OP_Rewind */
69261 }
69262 /* Opcode: Rewind P1 P2 * * *
69263 **
69264 ** The next use of the Rowid or Column or Next instruction for P1 
69265 ** will refer to the first entry in the database table or index.
69266 ** If the table or index is empty and P2>0, then jump immediately to P2.
69267 ** If P2 is 0 or if the table or index is not empty, fall through
69268 ** to the following instruction.
69269 */
69270 case OP_Rewind: {        /* jump */
69271 #if 0  /* local variables moved into u.bo */
69272   VdbeCursor *pC;
69273   BtCursor *pCrsr;
69274   int res;
69275 #endif /* local variables moved into u.bo */
69276
69277   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69278   u.bo.pC = p->apCsr[pOp->p1];
69279   assert( u.bo.pC!=0 );
69280   assert( u.bo.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69281   u.bo.res = 1;
69282   if( isSorter(u.bo.pC) ){
69283     rc = sqlcipher3VdbeSorterRewind(db, u.bo.pC, &u.bo.res);
69284   }else{
69285     u.bo.pCrsr = u.bo.pC->pCursor;
69286     assert( u.bo.pCrsr );
69287     rc = sqlcipher3BtreeFirst(u.bo.pCrsr, &u.bo.res);
69288     u.bo.pC->atFirst = u.bo.res==0 ?1:0;
69289     u.bo.pC->deferredMoveto = 0;
69290     u.bo.pC->cacheStatus = CACHE_STALE;
69291     u.bo.pC->rowidIsValid = 0;
69292   }
69293   u.bo.pC->nullRow = (u8)u.bo.res;
69294   assert( pOp->p2>0 && pOp->p2<p->nOp );
69295   if( u.bo.res ){
69296     pc = pOp->p2 - 1;
69297   }
69298   break;
69299 }
69300
69301 /* Opcode: Next P1 P2 * P4 P5
69302 **
69303 ** Advance cursor P1 so that it points to the next key/data pair in its
69304 ** table or index.  If there are no more key/value pairs then fall through
69305 ** to the following instruction.  But if the cursor advance was successful,
69306 ** jump immediately to P2.
69307 **
69308 ** The P1 cursor must be for a real table, not a pseudo-table.
69309 **
69310 ** P4 is always of type P4_ADVANCE. The function pointer points to
69311 ** sqlcipher3BtreeNext().
69312 **
69313 ** If P5 is positive and the jump is taken, then event counter
69314 ** number P5-1 in the prepared statement is incremented.
69315 **
69316 ** See also: Prev
69317 */
69318 /* Opcode: Prev P1 P2 * * P5
69319 **
69320 ** Back up cursor P1 so that it points to the previous key/data pair in its
69321 ** table or index.  If there is no previous key/value pairs then fall through
69322 ** to the following instruction.  But if the cursor backup was successful,
69323 ** jump immediately to P2.
69324 **
69325 ** The P1 cursor must be for a real table, not a pseudo-table.
69326 **
69327 ** P4 is always of type P4_ADVANCE. The function pointer points to
69328 ** sqlcipher3BtreePrevious().
69329 **
69330 ** If P5 is positive and the jump is taken, then event counter
69331 ** number P5-1 in the prepared statement is incremented.
69332 */
69333 case OP_SorterNext:    /* jump */
69334 #ifdef SQLCIPHER_OMIT_MERGE_SORT
69335   pOp->opcode = OP_Next;
69336 #endif
69337 case OP_Prev:          /* jump */
69338 case OP_Next: {        /* jump */
69339 #if 0  /* local variables moved into u.bp */
69340   VdbeCursor *pC;
69341   int res;
69342 #endif /* local variables moved into u.bp */
69343
69344   CHECK_FOR_INTERRUPT;
69345   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69346   assert( pOp->p5<=ArraySize(p->aCounter) );
69347   u.bp.pC = p->apCsr[pOp->p1];
69348   if( u.bp.pC==0 ){
69349     break;  /* See ticket #2273 */
69350   }
69351   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterNext) );
69352   if( isSorter(u.bp.pC) ){
69353     assert( pOp->opcode==OP_SorterNext );
69354     rc = sqlcipher3VdbeSorterNext(db, u.bp.pC, &u.bp.res);
69355   }else{
69356     u.bp.res = 1;
69357     assert( u.bp.pC->deferredMoveto==0 );
69358     assert( u.bp.pC->pCursor );
69359     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlcipher3BtreeNext );
69360     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlcipher3BtreePrevious );
69361     rc = pOp->p4.xAdvance(u.bp.pC->pCursor, &u.bp.res);
69362   }
69363   u.bp.pC->nullRow = (u8)u.bp.res;
69364   u.bp.pC->cacheStatus = CACHE_STALE;
69365   if( u.bp.res==0 ){
69366     pc = pOp->p2 - 1;
69367     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
69368 #ifdef SQLCIPHER_TEST
69369     sqlcipher3_search_count++;
69370 #endif
69371   }
69372   u.bp.pC->rowidIsValid = 0;
69373   break;
69374 }
69375
69376 /* Opcode: IdxInsert P1 P2 P3 * P5
69377 **
69378 ** Register P2 holds an SQL index key made using the
69379 ** MakeRecord instructions.  This opcode writes that key
69380 ** into the index P1.  Data for the entry is nil.
69381 **
69382 ** P3 is a flag that provides a hint to the b-tree layer that this
69383 ** insert is likely to be an append.
69384 **
69385 ** This instruction only works for indices.  The equivalent instruction
69386 ** for tables is OP_Insert.
69387 */
69388 case OP_SorterInsert:       /* in2 */
69389 #ifdef SQLCIPHER_OMIT_MERGE_SORT
69390   pOp->opcode = OP_IdxInsert;
69391 #endif
69392 case OP_IdxInsert: {        /* in2 */
69393 #if 0  /* local variables moved into u.bq */
69394   VdbeCursor *pC;
69395   BtCursor *pCrsr;
69396   int nKey;
69397   const char *zKey;
69398 #endif /* local variables moved into u.bq */
69399
69400   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69401   u.bq.pC = p->apCsr[pOp->p1];
69402   assert( u.bq.pC!=0 );
69403   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
69404   pIn2 = &aMem[pOp->p2];
69405   assert( pIn2->flags & MEM_Blob );
69406   u.bq.pCrsr = u.bq.pC->pCursor;
69407   if( ALWAYS(u.bq.pCrsr!=0) ){
69408     assert( u.bq.pC->isTable==0 );
69409     rc = ExpandBlob(pIn2);
69410     if( rc==SQLCIPHER_OK ){
69411       if( isSorter(u.bq.pC) ){
69412         rc = sqlcipher3VdbeSorterWrite(db, u.bq.pC, pIn2);
69413       }else{
69414         u.bq.nKey = pIn2->n;
69415         u.bq.zKey = pIn2->z;
69416         rc = sqlcipher3BtreeInsert(u.bq.pCrsr, u.bq.zKey, u.bq.nKey, "", 0, 0, pOp->p3,
69417             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bq.pC->seekResult : 0)
69418             );
69419         assert( u.bq.pC->deferredMoveto==0 );
69420         u.bq.pC->cacheStatus = CACHE_STALE;
69421       }
69422     }
69423   }
69424   break;
69425 }
69426
69427 /* Opcode: IdxDelete P1 P2 P3 * *
69428 **
69429 ** The content of P3 registers starting at register P2 form
69430 ** an unpacked index key. This opcode removes that entry from the 
69431 ** index opened by cursor P1.
69432 */
69433 case OP_IdxDelete: {
69434 #if 0  /* local variables moved into u.br */
69435   VdbeCursor *pC;
69436   BtCursor *pCrsr;
69437   int res;
69438   UnpackedRecord r;
69439 #endif /* local variables moved into u.br */
69440
69441   assert( pOp->p3>0 );
69442   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
69443   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69444   u.br.pC = p->apCsr[pOp->p1];
69445   assert( u.br.pC!=0 );
69446   u.br.pCrsr = u.br.pC->pCursor;
69447   if( ALWAYS(u.br.pCrsr!=0) ){
69448     u.br.r.pKeyInfo = u.br.pC->pKeyInfo;
69449     u.br.r.nField = (u16)pOp->p3;
69450     u.br.r.flags = 0;
69451     u.br.r.aMem = &aMem[pOp->p2];
69452 #ifdef SQLCIPHER_DEBUG
69453     { int i; for(i=0; i<u.br.r.nField; i++) assert( memIsValid(&u.br.r.aMem[i]) ); }
69454 #endif
69455     rc = sqlcipher3BtreeMovetoUnpacked(u.br.pCrsr, &u.br.r, 0, 0, &u.br.res);
69456     if( rc==SQLCIPHER_OK && u.br.res==0 ){
69457       rc = sqlcipher3BtreeDelete(u.br.pCrsr);
69458     }
69459     assert( u.br.pC->deferredMoveto==0 );
69460     u.br.pC->cacheStatus = CACHE_STALE;
69461   }
69462   break;
69463 }
69464
69465 /* Opcode: IdxRowid P1 P2 * * *
69466 **
69467 ** Write into register P2 an integer which is the last entry in the record at
69468 ** the end of the index key pointed to by cursor P1.  This integer should be
69469 ** the rowid of the table entry to which this index entry points.
69470 **
69471 ** See also: Rowid, MakeRecord.
69472 */
69473 case OP_IdxRowid: {              /* out2-prerelease */
69474 #if 0  /* local variables moved into u.bs */
69475   BtCursor *pCrsr;
69476   VdbeCursor *pC;
69477   i64 rowid;
69478 #endif /* local variables moved into u.bs */
69479
69480   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69481   u.bs.pC = p->apCsr[pOp->p1];
69482   assert( u.bs.pC!=0 );
69483   u.bs.pCrsr = u.bs.pC->pCursor;
69484   pOut->flags = MEM_Null;
69485   if( ALWAYS(u.bs.pCrsr!=0) ){
69486     rc = sqlcipher3VdbeCursorMoveto(u.bs.pC);
69487     if( NEVER(rc) ) goto abort_due_to_error;
69488     assert( u.bs.pC->deferredMoveto==0 );
69489     assert( u.bs.pC->isTable==0 );
69490     if( !u.bs.pC->nullRow ){
69491       rc = sqlcipher3VdbeIdxRowid(db, u.bs.pCrsr, &u.bs.rowid);
69492       if( rc!=SQLCIPHER_OK ){
69493         goto abort_due_to_error;
69494       }
69495       pOut->u.i = u.bs.rowid;
69496       pOut->flags = MEM_Int;
69497     }
69498   }
69499   break;
69500 }
69501
69502 /* Opcode: IdxGE P1 P2 P3 P4 P5
69503 **
69504 ** The P4 register values beginning with P3 form an unpacked index 
69505 ** key that omits the ROWID.  Compare this key value against the index 
69506 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69507 **
69508 ** If the P1 index entry is greater than or equal to the key value
69509 ** then jump to P2.  Otherwise fall through to the next instruction.
69510 **
69511 ** If P5 is non-zero then the key value is increased by an epsilon 
69512 ** prior to the comparison.  This make the opcode work like IdxGT except
69513 ** that if the key from register P3 is a prefix of the key in the cursor,
69514 ** the result is false whereas it would be true with IdxGT.
69515 */
69516 /* Opcode: IdxLT P1 P2 P3 P4 P5
69517 **
69518 ** The P4 register values beginning with P3 form an unpacked index 
69519 ** key that omits the ROWID.  Compare this key value against the index 
69520 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69521 **
69522 ** If the P1 index entry is less than the key value then jump to P2.
69523 ** Otherwise fall through to the next instruction.
69524 **
69525 ** If P5 is non-zero then the key value is increased by an epsilon prior 
69526 ** to the comparison.  This makes the opcode work like IdxLE.
69527 */
69528 case OP_IdxLT:          /* jump */
69529 case OP_IdxGE: {        /* jump */
69530 #if 0  /* local variables moved into u.bt */
69531   VdbeCursor *pC;
69532   int res;
69533   UnpackedRecord r;
69534 #endif /* local variables moved into u.bt */
69535
69536   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69537   u.bt.pC = p->apCsr[pOp->p1];
69538   assert( u.bt.pC!=0 );
69539   assert( u.bt.pC->isOrdered );
69540   if( ALWAYS(u.bt.pC->pCursor!=0) ){
69541     assert( u.bt.pC->deferredMoveto==0 );
69542     assert( pOp->p5==0 || pOp->p5==1 );
69543     assert( pOp->p4type==P4_INT32 );
69544     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
69545     u.bt.r.nField = (u16)pOp->p4.i;
69546     if( pOp->p5 ){
69547       u.bt.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
69548     }else{
69549       u.bt.r.flags = UNPACKED_IGNORE_ROWID;
69550     }
69551     u.bt.r.aMem = &aMem[pOp->p3];
69552 #ifdef SQLCIPHER_DEBUG
69553     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
69554 #endif
69555     rc = sqlcipher3VdbeIdxKeyCompare(u.bt.pC, &u.bt.r, &u.bt.res);
69556     if( pOp->opcode==OP_IdxLT ){
69557       u.bt.res = -u.bt.res;
69558     }else{
69559       assert( pOp->opcode==OP_IdxGE );
69560       u.bt.res++;
69561     }
69562     if( u.bt.res>0 ){
69563       pc = pOp->p2 - 1 ;
69564     }
69565   }
69566   break;
69567 }
69568
69569 /* Opcode: Destroy P1 P2 P3 * *
69570 **
69571 ** Delete an entire database table or index whose root page in the database
69572 ** file is given by P1.
69573 **
69574 ** The table being destroyed is in the main database file if P3==0.  If
69575 ** P3==1 then the table to be clear is in the auxiliary database file
69576 ** that is used to store tables create using CREATE TEMPORARY TABLE.
69577 **
69578 ** If AUTOVACUUM is enabled then it is possible that another root page
69579 ** might be moved into the newly deleted root page in order to keep all
69580 ** root pages contiguous at the beginning of the database.  The former
69581 ** value of the root page that moved - its value before the move occurred -
69582 ** is stored in register P2.  If no page 
69583 ** movement was required (because the table being dropped was already 
69584 ** the last one in the database) then a zero is stored in register P2.
69585 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
69586 **
69587 ** See also: Clear
69588 */
69589 case OP_Destroy: {     /* out2-prerelease */
69590 #if 0  /* local variables moved into u.bu */
69591   int iMoved;
69592   int iCnt;
69593   Vdbe *pVdbe;
69594   int iDb;
69595 #endif /* local variables moved into u.bu */
69596 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
69597   u.bu.iCnt = 0;
69598   for(u.bu.pVdbe=db->pVdbe; u.bu.pVdbe; u.bu.pVdbe = u.bu.pVdbe->pNext){
69599     if( u.bu.pVdbe->magic==VDBE_MAGIC_RUN && u.bu.pVdbe->inVtabMethod<2 && u.bu.pVdbe->pc>=0 ){
69600       u.bu.iCnt++;
69601     }
69602   }
69603 #else
69604   u.bu.iCnt = db->activeVdbeCnt;
69605 #endif
69606   pOut->flags = MEM_Null;
69607   if( u.bu.iCnt>1 ){
69608     rc = SQLCIPHER_LOCKED;
69609     p->errorAction = OE_Abort;
69610   }else{
69611     u.bu.iDb = pOp->p3;
69612     assert( u.bu.iCnt==1 );
69613     assert( (p->btreeMask & (((yDbMask)1)<<u.bu.iDb))!=0 );
69614     rc = sqlcipher3BtreeDropTable(db->aDb[u.bu.iDb].pBt, pOp->p1, &u.bu.iMoved);
69615     pOut->flags = MEM_Int;
69616     pOut->u.i = u.bu.iMoved;
69617 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
69618     if( rc==SQLCIPHER_OK && u.bu.iMoved!=0 ){
69619       sqlcipher3RootPageMoved(db, u.bu.iDb, u.bu.iMoved, pOp->p1);
69620       /* All OP_Destroy operations occur on the same btree */
69621       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bu.iDb+1 );
69622       resetSchemaOnFault = u.bu.iDb+1;
69623     }
69624 #endif
69625   }
69626   break;
69627 }
69628
69629 /* Opcode: Clear P1 P2 P3
69630 **
69631 ** Delete all contents of the database table or index whose root page
69632 ** in the database file is given by P1.  But, unlike Destroy, do not
69633 ** remove the table or index from the database file.
69634 **
69635 ** The table being clear is in the main database file if P2==0.  If
69636 ** P2==1 then the table to be clear is in the auxiliary database file
69637 ** that is used to store tables create using CREATE TEMPORARY TABLE.
69638 **
69639 ** If the P3 value is non-zero, then the table referred to must be an
69640 ** intkey table (an SQL table, not an index). In this case the row change 
69641 ** count is incremented by the number of rows in the table being cleared. 
69642 ** If P3 is greater than zero, then the value stored in register P3 is
69643 ** also incremented by the number of rows in the table being cleared.
69644 **
69645 ** See also: Destroy
69646 */
69647 case OP_Clear: {
69648 #if 0  /* local variables moved into u.bv */
69649   int nChange;
69650 #endif /* local variables moved into u.bv */
69651
69652   u.bv.nChange = 0;
69653   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
69654   rc = sqlcipher3BtreeClearTable(
69655       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bv.nChange : 0)
69656   );
69657   if( pOp->p3 ){
69658     p->nChange += u.bv.nChange;
69659     if( pOp->p3>0 ){
69660       assert( memIsValid(&aMem[pOp->p3]) );
69661       memAboutToChange(p, &aMem[pOp->p3]);
69662       aMem[pOp->p3].u.i += u.bv.nChange;
69663     }
69664   }
69665   break;
69666 }
69667
69668 /* Opcode: CreateTable P1 P2 * * *
69669 **
69670 ** Allocate a new table in the main database file if P1==0 or in the
69671 ** auxiliary database file if P1==1 or in an attached database if
69672 ** P1>1.  Write the root page number of the new table into
69673 ** register P2
69674 **
69675 ** The difference between a table and an index is this:  A table must
69676 ** have a 4-byte integer key and can have arbitrary data.  An index
69677 ** has an arbitrary key but no data.
69678 **
69679 ** See also: CreateIndex
69680 */
69681 /* Opcode: CreateIndex P1 P2 * * *
69682 **
69683 ** Allocate a new index in the main database file if P1==0 or in the
69684 ** auxiliary database file if P1==1 or in an attached database if
69685 ** P1>1.  Write the root page number of the new table into
69686 ** register P2.
69687 **
69688 ** See documentation on OP_CreateTable for additional information.
69689 */
69690 case OP_CreateIndex:            /* out2-prerelease */
69691 case OP_CreateTable: {          /* out2-prerelease */
69692 #if 0  /* local variables moved into u.bw */
69693   int pgno;
69694   int flags;
69695   Db *pDb;
69696 #endif /* local variables moved into u.bw */
69697
69698   u.bw.pgno = 0;
69699   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69700   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69701   u.bw.pDb = &db->aDb[pOp->p1];
69702   assert( u.bw.pDb->pBt!=0 );
69703   if( pOp->opcode==OP_CreateTable ){
69704     /* u.bw.flags = BTREE_INTKEY; */
69705     u.bw.flags = BTREE_INTKEY;
69706   }else{
69707     u.bw.flags = BTREE_BLOBKEY;
69708   }
69709   rc = sqlcipher3BtreeCreateTable(u.bw.pDb->pBt, &u.bw.pgno, u.bw.flags);
69710   pOut->u.i = u.bw.pgno;
69711   break;
69712 }
69713
69714 /* Opcode: ParseSchema P1 * * P4 *
69715 **
69716 ** Read and parse all entries from the SQLCIPHER_MASTER table of database P1
69717 ** that match the WHERE clause P4. 
69718 **
69719 ** This opcode invokes the parser to create a new virtual machine,
69720 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
69721 */
69722 case OP_ParseSchema: {
69723 #if 0  /* local variables moved into u.bx */
69724   int iDb;
69725   const char *zMaster;
69726   char *zSql;
69727   InitData initData;
69728 #endif /* local variables moved into u.bx */
69729
69730   /* Any prepared statement that invokes this opcode will hold mutexes
69731   ** on every btree.  This is a prerequisite for invoking
69732   ** sqlcipher3InitCallback().
69733   */
69734 #ifdef SQLCIPHER_DEBUG
69735   for(u.bx.iDb=0; u.bx.iDb<db->nDb; u.bx.iDb++){
69736     assert( u.bx.iDb==1 || sqlcipher3BtreeHoldsMutex(db->aDb[u.bx.iDb].pBt) );
69737   }
69738 #endif
69739
69740   u.bx.iDb = pOp->p1;
69741   assert( u.bx.iDb>=0 && u.bx.iDb<db->nDb );
69742   assert( DbHasProperty(db, u.bx.iDb, DB_SchemaLoaded) );
69743   /* Used to be a conditional */ {
69744     u.bx.zMaster = SCHEMA_TABLE(u.bx.iDb);
69745     u.bx.initData.db = db;
69746     u.bx.initData.iDb = pOp->p1;
69747     u.bx.initData.pzErrMsg = &p->zErrMsg;
69748     u.bx.zSql = sqlcipher3MPrintf(db,
69749        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
69750        db->aDb[u.bx.iDb].zName, u.bx.zMaster, pOp->p4.z);
69751     if( u.bx.zSql==0 ){
69752       rc = SQLCIPHER_NOMEM;
69753     }else{
69754       assert( db->init.busy==0 );
69755       db->init.busy = 1;
69756       u.bx.initData.rc = SQLCIPHER_OK;
69757       assert( !db->mallocFailed );
69758       rc = sqlcipher3_exec(db, u.bx.zSql, sqlcipher3InitCallback, &u.bx.initData, 0);
69759       if( rc==SQLCIPHER_OK ) rc = u.bx.initData.rc;
69760       sqlcipher3DbFree(db, u.bx.zSql);
69761       db->init.busy = 0;
69762     }
69763   }
69764   if( rc==SQLCIPHER_NOMEM ){
69765     goto no_mem;
69766   }
69767   break;
69768 }
69769
69770 #if !defined(SQLCIPHER_OMIT_ANALYZE)
69771 /* Opcode: LoadAnalysis P1 * * * *
69772 **
69773 ** Read the sqlcipher_stat1 table for database P1 and load the content
69774 ** of that table into the internal index hash table.  This will cause
69775 ** the analysis to be used when preparing all subsequent queries.
69776 */
69777 case OP_LoadAnalysis: {
69778   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69779   rc = sqlcipher3AnalysisLoad(db, pOp->p1);
69780   break;  
69781 }
69782 #endif /* !defined(SQLCIPHER_OMIT_ANALYZE) */
69783
69784 /* Opcode: DropTable P1 * * P4 *
69785 **
69786 ** Remove the internal (in-memory) data structures that describe
69787 ** the table named P4 in database P1.  This is called after a table
69788 ** is dropped in order to keep the internal representation of the
69789 ** schema consistent with what is on disk.
69790 */
69791 case OP_DropTable: {
69792   sqlcipher3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
69793   break;
69794 }
69795
69796 /* Opcode: DropIndex P1 * * P4 *
69797 **
69798 ** Remove the internal (in-memory) data structures that describe
69799 ** the index named P4 in database P1.  This is called after an index
69800 ** is dropped in order to keep the internal representation of the
69801 ** schema consistent with what is on disk.
69802 */
69803 case OP_DropIndex: {
69804   sqlcipher3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
69805   break;
69806 }
69807
69808 /* Opcode: DropTrigger P1 * * P4 *
69809 **
69810 ** Remove the internal (in-memory) data structures that describe
69811 ** the trigger named P4 in database P1.  This is called after a trigger
69812 ** is dropped in order to keep the internal representation of the
69813 ** schema consistent with what is on disk.
69814 */
69815 case OP_DropTrigger: {
69816   sqlcipher3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
69817   break;
69818 }
69819
69820
69821 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
69822 /* Opcode: IntegrityCk P1 P2 P3 * P5
69823 **
69824 ** Do an analysis of the currently open database.  Store in
69825 ** register P1 the text of an error message describing any problems.
69826 ** If no problems are found, store a NULL in register P1.
69827 **
69828 ** The register P3 contains the maximum number of allowed errors.
69829 ** At most reg(P3) errors will be reported.
69830 ** In other words, the analysis stops as soon as reg(P1) errors are 
69831 ** seen.  Reg(P1) is updated with the number of errors remaining.
69832 **
69833 ** The root page numbers of all tables in the database are integer
69834 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69835 ** total.
69836 **
69837 ** If P5 is not zero, the check is done on the auxiliary database
69838 ** file, not the main database file.
69839 **
69840 ** This opcode is used to implement the integrity_check pragma.
69841 */
69842 case OP_IntegrityCk: {
69843 #if 0  /* local variables moved into u.by */
69844   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69845   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69846   int j;          /* Loop counter */
69847   int nErr;       /* Number of errors reported */
69848   char *z;        /* Text of the error report */
69849   Mem *pnErr;     /* Register keeping track of errors remaining */
69850 #endif /* local variables moved into u.by */
69851
69852   u.by.nRoot = pOp->p2;
69853   assert( u.by.nRoot>0 );
69854   u.by.aRoot = sqlcipher3DbMallocRaw(db, sizeof(int)*(u.by.nRoot+1) );
69855   if( u.by.aRoot==0 ) goto no_mem;
69856   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69857   u.by.pnErr = &aMem[pOp->p3];
69858   assert( (u.by.pnErr->flags & MEM_Int)!=0 );
69859   assert( (u.by.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69860   pIn1 = &aMem[pOp->p1];
69861   for(u.by.j=0; u.by.j<u.by.nRoot; u.by.j++){
69862     u.by.aRoot[u.by.j] = (int)sqlcipher3VdbeIntValue(&pIn1[u.by.j]);
69863   }
69864   u.by.aRoot[u.by.j] = 0;
69865   assert( pOp->p5<db->nDb );
69866   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69867   u.by.z = sqlcipher3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.by.aRoot, u.by.nRoot,
69868                                  (int)u.by.pnErr->u.i, &u.by.nErr);
69869   sqlcipher3DbFree(db, u.by.aRoot);
69870   u.by.pnErr->u.i -= u.by.nErr;
69871   sqlcipher3VdbeMemSetNull(pIn1);
69872   if( u.by.nErr==0 ){
69873     assert( u.by.z==0 );
69874   }else if( u.by.z==0 ){
69875     goto no_mem;
69876   }else{
69877     sqlcipher3VdbeMemSetStr(pIn1, u.by.z, -1, SQLCIPHER_UTF8, sqlcipher3_free);
69878   }
69879   UPDATE_MAX_BLOBSIZE(pIn1);
69880   sqlcipher3VdbeChangeEncoding(pIn1, encoding);
69881   break;
69882 }
69883 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
69884
69885 /* Opcode: RowSetAdd P1 P2 * * *
69886 **
69887 ** Insert the integer value held by register P2 into a boolean index
69888 ** held in register P1.
69889 **
69890 ** An assertion fails if P2 is not an integer.
69891 */
69892 case OP_RowSetAdd: {       /* in1, in2 */
69893   pIn1 = &aMem[pOp->p1];
69894   pIn2 = &aMem[pOp->p2];
69895   assert( (pIn2->flags & MEM_Int)!=0 );
69896   if( (pIn1->flags & MEM_RowSet)==0 ){
69897     sqlcipher3VdbeMemSetRowSet(pIn1);
69898     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69899   }
69900   sqlcipher3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69901   break;
69902 }
69903
69904 /* Opcode: RowSetRead P1 P2 P3 * *
69905 **
69906 ** Extract the smallest value from boolean index P1 and put that value into
69907 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
69908 ** unchanged and jump to instruction P2.
69909 */
69910 case OP_RowSetRead: {       /* jump, in1, out3 */
69911 #if 0  /* local variables moved into u.bz */
69912   i64 val;
69913 #endif /* local variables moved into u.bz */
69914   CHECK_FOR_INTERRUPT;
69915   pIn1 = &aMem[pOp->p1];
69916   if( (pIn1->flags & MEM_RowSet)==0
69917    || sqlcipher3RowSetNext(pIn1->u.pRowSet, &u.bz.val)==0
69918   ){
69919     /* The boolean index is empty */
69920     sqlcipher3VdbeMemSetNull(pIn1);
69921     pc = pOp->p2 - 1;
69922   }else{
69923     /* A value was pulled from the index */
69924     sqlcipher3VdbeMemSetInt64(&aMem[pOp->p3], u.bz.val);
69925   }
69926   break;
69927 }
69928
69929 /* Opcode: RowSetTest P1 P2 P3 P4
69930 **
69931 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
69932 ** contains a RowSet object and that RowSet object contains
69933 ** the value held in P3, jump to register P2. Otherwise, insert the
69934 ** integer in P3 into the RowSet and continue on to the
69935 ** next opcode.
69936 **
69937 ** The RowSet object is optimized for the case where successive sets
69938 ** of integers, where each set contains no duplicates. Each set
69939 ** of values is identified by a unique P4 value. The first set
69940 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69941 ** non-negative.  For non-negative values of P4 only the lower 4
69942 ** bits are significant.
69943 **
69944 ** This allows optimizations: (a) when P4==0 there is no need to test
69945 ** the rowset object for P3, as it is guaranteed not to contain it,
69946 ** (b) when P4==-1 there is no need to insert the value, as it will
69947 ** never be tested for, and (c) when a value that is part of set X is
69948 ** inserted, there is no need to search to see if the same value was
69949 ** previously inserted as part of set X (only if it was previously
69950 ** inserted as part of some other set).
69951 */
69952 case OP_RowSetTest: {                     /* jump, in1, in3 */
69953 #if 0  /* local variables moved into u.ca */
69954   int iSet;
69955   int exists;
69956 #endif /* local variables moved into u.ca */
69957
69958   pIn1 = &aMem[pOp->p1];
69959   pIn3 = &aMem[pOp->p3];
69960   u.ca.iSet = pOp->p4.i;
69961   assert( pIn3->flags&MEM_Int );
69962
69963   /* If there is anything other than a rowset object in memory cell P1,
69964   ** delete it now and initialize P1 with an empty rowset
69965   */
69966   if( (pIn1->flags & MEM_RowSet)==0 ){
69967     sqlcipher3VdbeMemSetRowSet(pIn1);
69968     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69969   }
69970
69971   assert( pOp->p4type==P4_INT32 );
69972   assert( u.ca.iSet==-1 || u.ca.iSet>=0 );
69973   if( u.ca.iSet ){
69974     u.ca.exists = sqlcipher3RowSetTest(pIn1->u.pRowSet,
69975                                (u8)(u.ca.iSet>=0 ? u.ca.iSet & 0xf : 0xff),
69976                                pIn3->u.i);
69977     if( u.ca.exists ){
69978       pc = pOp->p2 - 1;
69979       break;
69980     }
69981   }
69982   if( u.ca.iSet>=0 ){
69983     sqlcipher3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
69984   }
69985   break;
69986 }
69987
69988
69989 #ifndef SQLCIPHER_OMIT_TRIGGER
69990
69991 /* Opcode: Program P1 P2 P3 P4 *
69992 **
69993 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
69994 **
69995 ** P1 contains the address of the memory cell that contains the first memory 
69996 ** cell in an array of values used as arguments to the sub-program. P2 
69997 ** contains the address to jump to if the sub-program throws an IGNORE 
69998 ** exception using the RAISE() function. Register P3 contains the address 
69999 ** of a memory cell in this (the parent) VM that is used to allocate the 
70000 ** memory required by the sub-vdbe at runtime.
70001 **
70002 ** P4 is a pointer to the VM containing the trigger program.
70003 */
70004 case OP_Program: {        /* jump */
70005 #if 0  /* local variables moved into u.cb */
70006   int nMem;               /* Number of memory registers for sub-program */
70007   int nByte;              /* Bytes of runtime space required for sub-program */
70008   Mem *pRt;               /* Register to allocate runtime space */
70009   Mem *pMem;              /* Used to iterate through memory cells */
70010   Mem *pEnd;              /* Last memory cell in new array */
70011   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70012   SubProgram *pProgram;   /* Sub-program to execute */
70013   void *t;                /* Token identifying trigger */
70014 #endif /* local variables moved into u.cb */
70015
70016   u.cb.pProgram = pOp->p4.pProgram;
70017   u.cb.pRt = &aMem[pOp->p3];
70018   assert( memIsValid(u.cb.pRt) );
70019   assert( u.cb.pProgram->nOp>0 );
70020
70021   /* If the p5 flag is clear, then recursive invocation of triggers is
70022   ** disabled for backwards compatibility (p5 is set if this sub-program
70023   ** is really a trigger, not a foreign key action, and the flag set
70024   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70025   **
70026   ** It is recursive invocation of triggers, at the SQL level, that is
70027   ** disabled. In some cases a single trigger may generate more than one
70028   ** SubProgram (if the trigger may be executed with more than one different
70029   ** ON CONFLICT algorithm). SubProgram structures associated with a
70030   ** single trigger all have the same value for the SubProgram.token
70031   ** variable.  */
70032   if( pOp->p5 ){
70033     u.cb.t = u.cb.pProgram->token;
70034     for(u.cb.pFrame=p->pFrame; u.cb.pFrame && u.cb.pFrame->token!=u.cb.t; u.cb.pFrame=u.cb.pFrame->pParent);
70035     if( u.cb.pFrame ) break;
70036   }
70037
70038   if( p->nFrame>=db->aLimit[SQLCIPHER_LIMIT_TRIGGER_DEPTH] ){
70039     rc = SQLCIPHER_ERROR;
70040     sqlcipher3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70041     break;
70042   }
70043
70044   /* Register u.cb.pRt is used to store the memory required to save the state
70045   ** of the current program, and the memory required at runtime to execute
70046   ** the trigger program. If this trigger has been fired before, then u.cb.pRt
70047   ** is already allocated. Otherwise, it must be initialized.  */
70048   if( (u.cb.pRt->flags&MEM_Frame)==0 ){
70049     /* SubProgram.nMem is set to the number of memory cells used by the
70050     ** program stored in SubProgram.aOp. As well as these, one memory
70051     ** cell is required for each cursor used by the program. Set local
70052     ** variable u.cb.nMem (and later, VdbeFrame.nChildMem) to this value.
70053     */
70054     u.cb.nMem = u.cb.pProgram->nMem + u.cb.pProgram->nCsr;
70055     u.cb.nByte = ROUND8(sizeof(VdbeFrame))
70056               + u.cb.nMem * sizeof(Mem)
70057               + u.cb.pProgram->nCsr * sizeof(VdbeCursor *);
70058     u.cb.pFrame = sqlcipher3DbMallocZero(db, u.cb.nByte);
70059     if( !u.cb.pFrame ){
70060       goto no_mem;
70061     }
70062     sqlcipher3VdbeMemRelease(u.cb.pRt);
70063     u.cb.pRt->flags = MEM_Frame;
70064     u.cb.pRt->u.pFrame = u.cb.pFrame;
70065
70066     u.cb.pFrame->v = p;
70067     u.cb.pFrame->nChildMem = u.cb.nMem;
70068     u.cb.pFrame->nChildCsr = u.cb.pProgram->nCsr;
70069     u.cb.pFrame->pc = pc;
70070     u.cb.pFrame->aMem = p->aMem;
70071     u.cb.pFrame->nMem = p->nMem;
70072     u.cb.pFrame->apCsr = p->apCsr;
70073     u.cb.pFrame->nCursor = p->nCursor;
70074     u.cb.pFrame->aOp = p->aOp;
70075     u.cb.pFrame->nOp = p->nOp;
70076     u.cb.pFrame->token = u.cb.pProgram->token;
70077
70078     u.cb.pEnd = &VdbeFrameMem(u.cb.pFrame)[u.cb.pFrame->nChildMem];
70079     for(u.cb.pMem=VdbeFrameMem(u.cb.pFrame); u.cb.pMem!=u.cb.pEnd; u.cb.pMem++){
70080       u.cb.pMem->flags = MEM_Null;
70081       u.cb.pMem->db = db;
70082     }
70083   }else{
70084     u.cb.pFrame = u.cb.pRt->u.pFrame;
70085     assert( u.cb.pProgram->nMem+u.cb.pProgram->nCsr==u.cb.pFrame->nChildMem );
70086     assert( u.cb.pProgram->nCsr==u.cb.pFrame->nChildCsr );
70087     assert( pc==u.cb.pFrame->pc );
70088   }
70089
70090   p->nFrame++;
70091   u.cb.pFrame->pParent = p->pFrame;
70092   u.cb.pFrame->lastRowid = lastRowid;
70093   u.cb.pFrame->nChange = p->nChange;
70094   p->nChange = 0;
70095   p->pFrame = u.cb.pFrame;
70096   p->aMem = aMem = &VdbeFrameMem(u.cb.pFrame)[-1];
70097   p->nMem = u.cb.pFrame->nChildMem;
70098   p->nCursor = (u16)u.cb.pFrame->nChildCsr;
70099   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70100   p->aOp = aOp = u.cb.pProgram->aOp;
70101   p->nOp = u.cb.pProgram->nOp;
70102   pc = -1;
70103
70104   break;
70105 }
70106
70107 /* Opcode: Param P1 P2 * * *
70108 **
70109 ** This opcode is only ever present in sub-programs called via the 
70110 ** OP_Program instruction. Copy a value currently stored in a memory 
70111 ** cell of the calling (parent) frame to cell P2 in the current frames 
70112 ** address space. This is used by trigger programs to access the new.* 
70113 ** and old.* values.
70114 **
70115 ** The address of the cell in the parent frame is determined by adding
70116 ** the value of the P1 argument to the value of the P1 argument to the
70117 ** calling OP_Program instruction.
70118 */
70119 case OP_Param: {           /* out2-prerelease */
70120 #if 0  /* local variables moved into u.cc */
70121   VdbeFrame *pFrame;
70122   Mem *pIn;
70123 #endif /* local variables moved into u.cc */
70124   u.cc.pFrame = p->pFrame;
70125   u.cc.pIn = &u.cc.pFrame->aMem[pOp->p1 + u.cc.pFrame->aOp[u.cc.pFrame->pc].p1];
70126   sqlcipher3VdbeMemShallowCopy(pOut, u.cc.pIn, MEM_Ephem);
70127   break;
70128 }
70129
70130 #endif /* #ifndef SQLCIPHER_OMIT_TRIGGER */
70131
70132 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
70133 /* Opcode: FkCounter P1 P2 * * *
70134 **
70135 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70136 ** If P1 is non-zero, the database constraint counter is incremented 
70137 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
70138 ** statement counter is incremented (immediate foreign key constraints).
70139 */
70140 case OP_FkCounter: {
70141   if( pOp->p1 ){
70142     db->nDeferredCons += pOp->p2;
70143   }else{
70144     p->nFkConstraint += pOp->p2;
70145   }
70146   break;
70147 }
70148
70149 /* Opcode: FkIfZero P1 P2 * * *
70150 **
70151 ** This opcode tests if a foreign key constraint-counter is currently zero.
70152 ** If so, jump to instruction P2. Otherwise, fall through to the next 
70153 ** instruction.
70154 **
70155 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
70156 ** is zero (the one that counts deferred constraint violations). If P1 is
70157 ** zero, the jump is taken if the statement constraint-counter is zero
70158 ** (immediate foreign key constraint violations).
70159 */
70160 case OP_FkIfZero: {         /* jump */
70161   if( pOp->p1 ){
70162     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
70163   }else{
70164     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
70165   }
70166   break;
70167 }
70168 #endif /* #ifndef SQLCIPHER_OMIT_FOREIGN_KEY */
70169
70170 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
70171 /* Opcode: MemMax P1 P2 * * *
70172 **
70173 ** P1 is a register in the root frame of this VM (the root frame is
70174 ** different from the current frame if this instruction is being executed
70175 ** within a sub-program). Set the value of register P1 to the maximum of 
70176 ** its current value and the value in register P2.
70177 **
70178 ** This instruction throws an error if the memory cell is not initially
70179 ** an integer.
70180 */
70181 case OP_MemMax: {        /* in2 */
70182 #if 0  /* local variables moved into u.cd */
70183   Mem *pIn1;
70184   VdbeFrame *pFrame;
70185 #endif /* local variables moved into u.cd */
70186   if( p->pFrame ){
70187     for(u.cd.pFrame=p->pFrame; u.cd.pFrame->pParent; u.cd.pFrame=u.cd.pFrame->pParent);
70188     u.cd.pIn1 = &u.cd.pFrame->aMem[pOp->p1];
70189   }else{
70190     u.cd.pIn1 = &aMem[pOp->p1];
70191   }
70192   assert( memIsValid(u.cd.pIn1) );
70193   sqlcipher3VdbeMemIntegerify(u.cd.pIn1);
70194   pIn2 = &aMem[pOp->p2];
70195   sqlcipher3VdbeMemIntegerify(pIn2);
70196   if( u.cd.pIn1->u.i<pIn2->u.i){
70197     u.cd.pIn1->u.i = pIn2->u.i;
70198   }
70199   break;
70200 }
70201 #endif /* SQLCIPHER_OMIT_AUTOINCREMENT */
70202
70203 /* Opcode: IfPos P1 P2 * * *
70204 **
70205 ** If the value of register P1 is 1 or greater, jump to P2.
70206 **
70207 ** It is illegal to use this instruction on a register that does
70208 ** not contain an integer.  An assertion fault will result if you try.
70209 */
70210 case OP_IfPos: {        /* jump, in1 */
70211   pIn1 = &aMem[pOp->p1];
70212   assert( pIn1->flags&MEM_Int );
70213   if( pIn1->u.i>0 ){
70214      pc = pOp->p2 - 1;
70215   }
70216   break;
70217 }
70218
70219 /* Opcode: IfNeg P1 P2 * * *
70220 **
70221 ** If the value of register P1 is less than zero, jump to P2. 
70222 **
70223 ** It is illegal to use this instruction on a register that does
70224 ** not contain an integer.  An assertion fault will result if you try.
70225 */
70226 case OP_IfNeg: {        /* jump, in1 */
70227   pIn1 = &aMem[pOp->p1];
70228   assert( pIn1->flags&MEM_Int );
70229   if( pIn1->u.i<0 ){
70230      pc = pOp->p2 - 1;
70231   }
70232   break;
70233 }
70234
70235 /* Opcode: IfZero P1 P2 P3 * *
70236 **
70237 ** The register P1 must contain an integer.  Add literal P3 to the
70238 ** value in register P1.  If the result is exactly 0, jump to P2. 
70239 **
70240 ** It is illegal to use this instruction on a register that does
70241 ** not contain an integer.  An assertion fault will result if you try.
70242 */
70243 case OP_IfZero: {        /* jump, in1 */
70244   pIn1 = &aMem[pOp->p1];
70245   assert( pIn1->flags&MEM_Int );
70246   pIn1->u.i += pOp->p3;
70247   if( pIn1->u.i==0 ){
70248      pc = pOp->p2 - 1;
70249   }
70250   break;
70251 }
70252
70253 /* Opcode: AggStep * P2 P3 P4 P5
70254 **
70255 ** Execute the step function for an aggregate.  The
70256 ** function has P5 arguments.   P4 is a pointer to the FuncDef
70257 ** structure that specifies the function.  Use register
70258 ** P3 as the accumulator.
70259 **
70260 ** The P5 arguments are taken from register P2 and its
70261 ** successors.
70262 */
70263 case OP_AggStep: {
70264 #if 0  /* local variables moved into u.ce */
70265   int n;
70266   int i;
70267   Mem *pMem;
70268   Mem *pRec;
70269   sqlcipher3_context ctx;
70270   sqlcipher3_value **apVal;
70271 #endif /* local variables moved into u.ce */
70272
70273   u.ce.n = pOp->p5;
70274   assert( u.ce.n>=0 );
70275   u.ce.pRec = &aMem[pOp->p2];
70276   u.ce.apVal = p->apArg;
70277   assert( u.ce.apVal || u.ce.n==0 );
70278   for(u.ce.i=0; u.ce.i<u.ce.n; u.ce.i++, u.ce.pRec++){
70279     assert( memIsValid(u.ce.pRec) );
70280     u.ce.apVal[u.ce.i] = u.ce.pRec;
70281     memAboutToChange(p, u.ce.pRec);
70282     sqlcipher3VdbeMemStoreType(u.ce.pRec);
70283   }
70284   u.ce.ctx.pFunc = pOp->p4.pFunc;
70285   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70286   u.ce.ctx.pMem = u.ce.pMem = &aMem[pOp->p3];
70287   u.ce.pMem->n++;
70288   u.ce.ctx.s.flags = MEM_Null;
70289   u.ce.ctx.s.z = 0;
70290   u.ce.ctx.s.zMalloc = 0;
70291   u.ce.ctx.s.xDel = 0;
70292   u.ce.ctx.s.db = db;
70293   u.ce.ctx.isError = 0;
70294   u.ce.ctx.pColl = 0;
70295   if( u.ce.ctx.pFunc->flags & SQLCIPHER_FUNC_NEEDCOLL ){
70296     assert( pOp>p->aOp );
70297     assert( pOp[-1].p4type==P4_COLLSEQ );
70298     assert( pOp[-1].opcode==OP_CollSeq );
70299     u.ce.ctx.pColl = pOp[-1].p4.pColl;
70300   }
70301   (u.ce.ctx.pFunc->xStep)(&u.ce.ctx, u.ce.n, u.ce.apVal); /* IMP: R-24505-23230 */
70302   if( u.ce.ctx.isError ){
70303     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3_value_text(&u.ce.ctx.s));
70304     rc = u.ce.ctx.isError;
70305   }
70306
70307   sqlcipher3VdbeMemRelease(&u.ce.ctx.s);
70308
70309   break;
70310 }
70311
70312 /* Opcode: AggFinal P1 P2 * P4 *
70313 **
70314 ** Execute the finalizer function for an aggregate.  P1 is
70315 ** the memory location that is the accumulator for the aggregate.
70316 **
70317 ** P2 is the number of arguments that the step function takes and
70318 ** P4 is a pointer to the FuncDef for this function.  The P2
70319 ** argument is not used by this opcode.  It is only there to disambiguate
70320 ** functions that can take varying numbers of arguments.  The
70321 ** P4 argument is only needed for the degenerate case where
70322 ** the step function was not previously called.
70323 */
70324 case OP_AggFinal: {
70325 #if 0  /* local variables moved into u.cf */
70326   Mem *pMem;
70327 #endif /* local variables moved into u.cf */
70328   assert( pOp->p1>0 && pOp->p1<=p->nMem );
70329   u.cf.pMem = &aMem[pOp->p1];
70330   assert( (u.cf.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
70331   rc = sqlcipher3VdbeMemFinalize(u.cf.pMem, pOp->p4.pFunc);
70332   if( rc ){
70333     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3_value_text(u.cf.pMem));
70334   }
70335   sqlcipher3VdbeChangeEncoding(u.cf.pMem, encoding);
70336   UPDATE_MAX_BLOBSIZE(u.cf.pMem);
70337   if( sqlcipher3VdbeMemTooBig(u.cf.pMem) ){
70338     goto too_big;
70339   }
70340   break;
70341 }
70342
70343 #ifndef SQLCIPHER_OMIT_WAL
70344 /* Opcode: Checkpoint P1 P2 P3 * *
70345 **
70346 ** Checkpoint database P1. This is a no-op if P1 is not currently in
70347 ** WAL mode. Parameter P2 is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL
70348 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
70349 ** SQLCIPHER_BUSY or not, respectively.  Write the number of pages in the
70350 ** WAL after the checkpoint into mem[P3+1] and the number of pages
70351 ** in the WAL that have been checkpointed after the checkpoint
70352 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
70353 ** mem[P3+2] are initialized to -1.
70354 */
70355 case OP_Checkpoint: {
70356 #if 0  /* local variables moved into u.cg */
70357   int i;                          /* Loop counter */
70358   int aRes[3];                    /* Results */
70359   Mem *pMem;                      /* Write results here */
70360 #endif /* local variables moved into u.cg */
70361
70362   u.cg.aRes[0] = 0;
70363   u.cg.aRes[1] = u.cg.aRes[2] = -1;
70364   assert( pOp->p2==SQLCIPHER_CHECKPOINT_PASSIVE
70365        || pOp->p2==SQLCIPHER_CHECKPOINT_FULL
70366        || pOp->p2==SQLCIPHER_CHECKPOINT_RESTART
70367   );
70368   rc = sqlcipher3Checkpoint(db, pOp->p1, pOp->p2, &u.cg.aRes[1], &u.cg.aRes[2]);
70369   if( rc==SQLCIPHER_BUSY ){
70370     rc = SQLCIPHER_OK;
70371     u.cg.aRes[0] = 1;
70372   }
70373   for(u.cg.i=0, u.cg.pMem = &aMem[pOp->p3]; u.cg.i<3; u.cg.i++, u.cg.pMem++){
70374     sqlcipher3VdbeMemSetInt64(u.cg.pMem, (i64)u.cg.aRes[u.cg.i]);
70375   }
70376   break;
70377 };  
70378 #endif
70379
70380 #ifndef SQLCIPHER_OMIT_PRAGMA
70381 /* Opcode: JournalMode P1 P2 P3 * P5
70382 **
70383 ** Change the journal mode of database P1 to P3. P3 must be one of the
70384 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
70385 ** modes (delete, truncate, persist, off and memory), this is a simple
70386 ** operation. No IO is required.
70387 **
70388 ** If changing into or out of WAL mode the procedure is more complicated.
70389 **
70390 ** Write a string containing the final journal-mode to register P2.
70391 */
70392 case OP_JournalMode: {    /* out2-prerelease */
70393 #if 0  /* local variables moved into u.ch */
70394   Btree *pBt;                     /* Btree to change journal mode of */
70395   Pager *pPager;                  /* Pager associated with pBt */
70396   int eNew;                       /* New journal mode */
70397   int eOld;                       /* The old journal mode */
70398   const char *zFilename;          /* Name of database file for pPager */
70399 #endif /* local variables moved into u.ch */
70400
70401   u.ch.eNew = pOp->p3;
70402   assert( u.ch.eNew==PAGER_JOURNALMODE_DELETE
70403        || u.ch.eNew==PAGER_JOURNALMODE_TRUNCATE
70404        || u.ch.eNew==PAGER_JOURNALMODE_PERSIST
70405        || u.ch.eNew==PAGER_JOURNALMODE_OFF
70406        || u.ch.eNew==PAGER_JOURNALMODE_MEMORY
70407        || u.ch.eNew==PAGER_JOURNALMODE_WAL
70408        || u.ch.eNew==PAGER_JOURNALMODE_QUERY
70409   );
70410   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70411
70412   u.ch.pBt = db->aDb[pOp->p1].pBt;
70413   u.ch.pPager = sqlcipher3BtreePager(u.ch.pBt);
70414   u.ch.eOld = sqlcipher3PagerGetJournalMode(u.ch.pPager);
70415   if( u.ch.eNew==PAGER_JOURNALMODE_QUERY ) u.ch.eNew = u.ch.eOld;
70416   if( !sqlcipher3PagerOkToChangeJournalMode(u.ch.pPager) ) u.ch.eNew = u.ch.eOld;
70417
70418 #ifndef SQLCIPHER_OMIT_WAL
70419   u.ch.zFilename = sqlcipher3PagerFilename(u.ch.pPager);
70420
70421   /* Do not allow a transition to journal_mode=WAL for a database
70422   ** in temporary storage or if the VFS does not support shared memory
70423   */
70424   if( u.ch.eNew==PAGER_JOURNALMODE_WAL
70425    && (sqlcipher3Strlen30(u.ch.zFilename)==0           /* Temp file */
70426        || !sqlcipher3PagerWalSupported(u.ch.pPager))   /* No shared-memory support */
70427   ){
70428     u.ch.eNew = u.ch.eOld;
70429   }
70430
70431   if( (u.ch.eNew!=u.ch.eOld)
70432    && (u.ch.eOld==PAGER_JOURNALMODE_WAL || u.ch.eNew==PAGER_JOURNALMODE_WAL)
70433   ){
70434     if( !db->autoCommit || db->activeVdbeCnt>1 ){
70435       rc = SQLCIPHER_ERROR;
70436       sqlcipher3SetString(&p->zErrMsg, db,
70437           "cannot change %s wal mode from within a transaction",
70438           (u.ch.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
70439       );
70440       break;
70441     }else{
70442
70443       if( u.ch.eOld==PAGER_JOURNALMODE_WAL ){
70444         /* If leaving WAL mode, close the log file. If successful, the call
70445         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
70446         ** file. An EXCLUSIVE lock may still be held on the database file
70447         ** after a successful return.
70448         */
70449         rc = sqlcipher3PagerCloseWal(u.ch.pPager);
70450         if( rc==SQLCIPHER_OK ){
70451           sqlcipher3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
70452         }
70453       }else if( u.ch.eOld==PAGER_JOURNALMODE_MEMORY ){
70454         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
70455         ** as an intermediate */
70456         sqlcipher3PagerSetJournalMode(u.ch.pPager, PAGER_JOURNALMODE_OFF);
70457       }
70458
70459       /* Open a transaction on the database file. Regardless of the journal
70460       ** mode, this transaction always uses a rollback journal.
70461       */
70462       assert( sqlcipher3BtreeIsInTrans(u.ch.pBt)==0 );
70463       if( rc==SQLCIPHER_OK ){
70464         rc = sqlcipher3BtreeSetVersion(u.ch.pBt, (u.ch.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
70465       }
70466     }
70467   }
70468 #endif /* ifndef SQLCIPHER_OMIT_WAL */
70469
70470   if( rc ){
70471     u.ch.eNew = u.ch.eOld;
70472   }
70473   u.ch.eNew = sqlcipher3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
70474
70475   pOut = &aMem[pOp->p2];
70476   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70477   pOut->z = (char *)sqlcipher3JournalModename(u.ch.eNew);
70478   pOut->n = sqlcipher3Strlen30(pOut->z);
70479   pOut->enc = SQLCIPHER_UTF8;
70480   sqlcipher3VdbeChangeEncoding(pOut, encoding);
70481   break;
70482 };
70483 #endif /* SQLCIPHER_OMIT_PRAGMA */
70484
70485 #if !defined(SQLCIPHER_OMIT_VACUUM) && !defined(SQLCIPHER_OMIT_ATTACH)
70486 /* Opcode: Vacuum * * * * *
70487 **
70488 ** Vacuum the entire database.  This opcode will cause other virtual
70489 ** machines to be created and run.  It may not be called from within
70490 ** a transaction.
70491 */
70492 case OP_Vacuum: {
70493   rc = sqlcipher3RunVacuum(&p->zErrMsg, db);
70494   break;
70495 }
70496 #endif
70497
70498 #if !defined(SQLCIPHER_OMIT_AUTOVACUUM)
70499 /* Opcode: IncrVacuum P1 P2 * * *
70500 **
70501 ** Perform a single step of the incremental vacuum procedure on
70502 ** the P1 database. If the vacuum has finished, jump to instruction
70503 ** P2. Otherwise, fall through to the next instruction.
70504 */
70505 case OP_IncrVacuum: {        /* jump */
70506 #if 0  /* local variables moved into u.ci */
70507   Btree *pBt;
70508 #endif /* local variables moved into u.ci */
70509
70510   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70511   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70512   u.ci.pBt = db->aDb[pOp->p1].pBt;
70513   rc = sqlcipher3BtreeIncrVacuum(u.ci.pBt);
70514   if( rc==SQLCIPHER_DONE ){
70515     pc = pOp->p2 - 1;
70516     rc = SQLCIPHER_OK;
70517   }
70518   break;
70519 }
70520 #endif
70521
70522 /* Opcode: Expire P1 * * * *
70523 **
70524 ** Cause precompiled statements to become expired. An expired statement
70525 ** fails with an error code of SQLCIPHER_SCHEMA if it is ever executed 
70526 ** (via sqlcipher3_step()).
70527 ** 
70528 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
70529 ** then only the currently executing statement is affected. 
70530 */
70531 case OP_Expire: {
70532   if( !pOp->p1 ){
70533     sqlcipher3ExpirePreparedStatements(db);
70534   }else{
70535     p->expired = 1;
70536   }
70537   break;
70538 }
70539
70540 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
70541 /* Opcode: TableLock P1 P2 P3 P4 *
70542 **
70543 ** Obtain a lock on a particular table. This instruction is only used when
70544 ** the shared-cache feature is enabled. 
70545 **
70546 ** P1 is the index of the database in sqlcipher3.aDb[] of the database
70547 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
70548 ** a write lock if P3==1.
70549 **
70550 ** P2 contains the root-page of the table to lock.
70551 **
70552 ** P4 contains a pointer to the name of the table being locked. This is only
70553 ** used to generate an error message if the lock cannot be obtained.
70554 */
70555 case OP_TableLock: {
70556   u8 isWriteLock = (u8)pOp->p3;
70557   if( isWriteLock || 0==(db->flags&SQLCIPHER_ReadUncommitted) ){
70558     int p1 = pOp->p1; 
70559     assert( p1>=0 && p1<db->nDb );
70560     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
70561     assert( isWriteLock==0 || isWriteLock==1 );
70562     rc = sqlcipher3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
70563     if( (rc&0xFF)==SQLCIPHER_LOCKED ){
70564       const char *z = pOp->p4.z;
70565       sqlcipher3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
70566     }
70567   }
70568   break;
70569 }
70570 #endif /* SQLCIPHER_OMIT_SHARED_CACHE */
70571
70572 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70573 /* Opcode: VBegin * * * P4 *
70574 **
70575 ** P4 may be a pointer to an sqlcipher3_vtab structure. If so, call the 
70576 ** xBegin method for that table.
70577 **
70578 ** Also, whether or not P4 is set, check that this is not being called from
70579 ** within a callback to a virtual table xSync() method. If it is, the error
70580 ** code will be set to SQLCIPHER_LOCKED.
70581 */
70582 case OP_VBegin: {
70583 #if 0  /* local variables moved into u.cj */
70584   VTable *pVTab;
70585 #endif /* local variables moved into u.cj */
70586   u.cj.pVTab = pOp->p4.pVtab;
70587   rc = sqlcipher3VtabBegin(db, u.cj.pVTab);
70588   if( u.cj.pVTab ) importVtabErrMsg(p, u.cj.pVTab->pVtab);
70589   break;
70590 }
70591 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70592
70593 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70594 /* Opcode: VCreate P1 * * P4 *
70595 **
70596 ** P4 is the name of a virtual table in database P1. Call the xCreate method
70597 ** for that table.
70598 */
70599 case OP_VCreate: {
70600   rc = sqlcipher3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
70601   break;
70602 }
70603 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70604
70605 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70606 /* Opcode: VDestroy P1 * * P4 *
70607 **
70608 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
70609 ** of that table.
70610 */
70611 case OP_VDestroy: {
70612   p->inVtabMethod = 2;
70613   rc = sqlcipher3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
70614   p->inVtabMethod = 0;
70615   break;
70616 }
70617 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70618
70619 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70620 /* Opcode: VOpen P1 * * P4 *
70621 **
70622 ** P4 is a pointer to a virtual table object, an sqlcipher3_vtab structure.
70623 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
70624 ** table and stores that cursor in P1.
70625 */
70626 case OP_VOpen: {
70627 #if 0  /* local variables moved into u.ck */
70628   VdbeCursor *pCur;
70629   sqlcipher3_vtab_cursor *pVtabCursor;
70630   sqlcipher3_vtab *pVtab;
70631   sqlcipher3_module *pModule;
70632 #endif /* local variables moved into u.ck */
70633
70634   u.ck.pCur = 0;
70635   u.ck.pVtabCursor = 0;
70636   u.ck.pVtab = pOp->p4.pVtab->pVtab;
70637   u.ck.pModule = (sqlcipher3_module *)u.ck.pVtab->pModule;
70638   assert(u.ck.pVtab && u.ck.pModule);
70639   rc = u.ck.pModule->xOpen(u.ck.pVtab, &u.ck.pVtabCursor);
70640   importVtabErrMsg(p, u.ck.pVtab);
70641   if( SQLCIPHER_OK==rc ){
70642     /* Initialize sqlcipher3_vtab_cursor base class */
70643     u.ck.pVtabCursor->pVtab = u.ck.pVtab;
70644
70645     /* Initialise vdbe cursor object */
70646     u.ck.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
70647     if( u.ck.pCur ){
70648       u.ck.pCur->pVtabCursor = u.ck.pVtabCursor;
70649       u.ck.pCur->pModule = u.ck.pVtabCursor->pVtab->pModule;
70650     }else{
70651       db->mallocFailed = 1;
70652       u.ck.pModule->xClose(u.ck.pVtabCursor);
70653     }
70654   }
70655   break;
70656 }
70657 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70658
70659 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70660 /* Opcode: VFilter P1 P2 P3 P4 *
70661 **
70662 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
70663 ** the filtered result set is empty.
70664 **
70665 ** P4 is either NULL or a string that was generated by the xBestIndex
70666 ** method of the module.  The interpretation of the P4 string is left
70667 ** to the module implementation.
70668 **
70669 ** This opcode invokes the xFilter method on the virtual table specified
70670 ** by P1.  The integer query plan parameter to xFilter is stored in register
70671 ** P3. Register P3+1 stores the argc parameter to be passed to the
70672 ** xFilter method. Registers P3+2..P3+1+argc are the argc
70673 ** additional parameters which are passed to
70674 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
70675 **
70676 ** A jump is made to P2 if the result set after filtering would be empty.
70677 */
70678 case OP_VFilter: {   /* jump */
70679 #if 0  /* local variables moved into u.cl */
70680   int nArg;
70681   int iQuery;
70682   const sqlcipher3_module *pModule;
70683   Mem *pQuery;
70684   Mem *pArgc;
70685   sqlcipher3_vtab_cursor *pVtabCursor;
70686   sqlcipher3_vtab *pVtab;
70687   VdbeCursor *pCur;
70688   int res;
70689   int i;
70690   Mem **apArg;
70691 #endif /* local variables moved into u.cl */
70692
70693   u.cl.pQuery = &aMem[pOp->p3];
70694   u.cl.pArgc = &u.cl.pQuery[1];
70695   u.cl.pCur = p->apCsr[pOp->p1];
70696   assert( memIsValid(u.cl.pQuery) );
70697   REGISTER_TRACE(pOp->p3, u.cl.pQuery);
70698   assert( u.cl.pCur->pVtabCursor );
70699   u.cl.pVtabCursor = u.cl.pCur->pVtabCursor;
70700   u.cl.pVtab = u.cl.pVtabCursor->pVtab;
70701   u.cl.pModule = u.cl.pVtab->pModule;
70702
70703   /* Grab the index number and argc parameters */
70704   assert( (u.cl.pQuery->flags&MEM_Int)!=0 && u.cl.pArgc->flags==MEM_Int );
70705   u.cl.nArg = (int)u.cl.pArgc->u.i;
70706   u.cl.iQuery = (int)u.cl.pQuery->u.i;
70707
70708   /* Invoke the xFilter method */
70709   {
70710     u.cl.res = 0;
70711     u.cl.apArg = p->apArg;
70712     for(u.cl.i = 0; u.cl.i<u.cl.nArg; u.cl.i++){
70713       u.cl.apArg[u.cl.i] = &u.cl.pArgc[u.cl.i+1];
70714       sqlcipher3VdbeMemStoreType(u.cl.apArg[u.cl.i]);
70715     }
70716
70717     p->inVtabMethod = 1;
70718     rc = u.cl.pModule->xFilter(u.cl.pVtabCursor, u.cl.iQuery, pOp->p4.z, u.cl.nArg, u.cl.apArg);
70719     p->inVtabMethod = 0;
70720     importVtabErrMsg(p, u.cl.pVtab);
70721     if( rc==SQLCIPHER_OK ){
70722       u.cl.res = u.cl.pModule->xEof(u.cl.pVtabCursor);
70723     }
70724
70725     if( u.cl.res ){
70726       pc = pOp->p2 - 1;
70727     }
70728   }
70729   u.cl.pCur->nullRow = 0;
70730
70731   break;
70732 }
70733 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70734
70735 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70736 /* Opcode: VColumn P1 P2 P3 * *
70737 **
70738 ** Store the value of the P2-th column of
70739 ** the row of the virtual-table that the 
70740 ** P1 cursor is pointing to into register P3.
70741 */
70742 case OP_VColumn: {
70743 #if 0  /* local variables moved into u.cm */
70744   sqlcipher3_vtab *pVtab;
70745   const sqlcipher3_module *pModule;
70746   Mem *pDest;
70747   sqlcipher3_context sContext;
70748 #endif /* local variables moved into u.cm */
70749
70750   VdbeCursor *pCur = p->apCsr[pOp->p1];
70751   assert( pCur->pVtabCursor );
70752   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70753   u.cm.pDest = &aMem[pOp->p3];
70754   memAboutToChange(p, u.cm.pDest);
70755   if( pCur->nullRow ){
70756     sqlcipher3VdbeMemSetNull(u.cm.pDest);
70757     break;
70758   }
70759   u.cm.pVtab = pCur->pVtabCursor->pVtab;
70760   u.cm.pModule = u.cm.pVtab->pModule;
70761   assert( u.cm.pModule->xColumn );
70762   memset(&u.cm.sContext, 0, sizeof(u.cm.sContext));
70763
70764   /* The output cell may already have a buffer allocated. Move
70765   ** the current contents to u.cm.sContext.s so in case the user-function
70766   ** can use the already allocated buffer instead of allocating a
70767   ** new one.
70768   */
70769   sqlcipher3VdbeMemMove(&u.cm.sContext.s, u.cm.pDest);
70770   MemSetTypeFlag(&u.cm.sContext.s, MEM_Null);
70771
70772   rc = u.cm.pModule->xColumn(pCur->pVtabCursor, &u.cm.sContext, pOp->p2);
70773   importVtabErrMsg(p, u.cm.pVtab);
70774   if( u.cm.sContext.isError ){
70775     rc = u.cm.sContext.isError;
70776   }
70777
70778   /* Copy the result of the function to the P3 register. We
70779   ** do this regardless of whether or not an error occurred to ensure any
70780   ** dynamic allocation in u.cm.sContext.s (a Mem struct) is  released.
70781   */
70782   sqlcipher3VdbeChangeEncoding(&u.cm.sContext.s, encoding);
70783   sqlcipher3VdbeMemMove(u.cm.pDest, &u.cm.sContext.s);
70784   REGISTER_TRACE(pOp->p3, u.cm.pDest);
70785   UPDATE_MAX_BLOBSIZE(u.cm.pDest);
70786
70787   if( sqlcipher3VdbeMemTooBig(u.cm.pDest) ){
70788     goto too_big;
70789   }
70790   break;
70791 }
70792 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70793
70794 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70795 /* Opcode: VNext P1 P2 * * *
70796 **
70797 ** Advance virtual table P1 to the next row in its result set and
70798 ** jump to instruction P2.  Or, if the virtual table has reached
70799 ** the end of its result set, then fall through to the next instruction.
70800 */
70801 case OP_VNext: {   /* jump */
70802 #if 0  /* local variables moved into u.cn */
70803   sqlcipher3_vtab *pVtab;
70804   const sqlcipher3_module *pModule;
70805   int res;
70806   VdbeCursor *pCur;
70807 #endif /* local variables moved into u.cn */
70808
70809   u.cn.res = 0;
70810   u.cn.pCur = p->apCsr[pOp->p1];
70811   assert( u.cn.pCur->pVtabCursor );
70812   if( u.cn.pCur->nullRow ){
70813     break;
70814   }
70815   u.cn.pVtab = u.cn.pCur->pVtabCursor->pVtab;
70816   u.cn.pModule = u.cn.pVtab->pModule;
70817   assert( u.cn.pModule->xNext );
70818
70819   /* Invoke the xNext() method of the module. There is no way for the
70820   ** underlying implementation to return an error if one occurs during
70821   ** xNext(). Instead, if an error occurs, true is returned (indicating that
70822   ** data is available) and the error code returned when xColumn or
70823   ** some other method is next invoked on the save virtual table cursor.
70824   */
70825   p->inVtabMethod = 1;
70826   rc = u.cn.pModule->xNext(u.cn.pCur->pVtabCursor);
70827   p->inVtabMethod = 0;
70828   importVtabErrMsg(p, u.cn.pVtab);
70829   if( rc==SQLCIPHER_OK ){
70830     u.cn.res = u.cn.pModule->xEof(u.cn.pCur->pVtabCursor);
70831   }
70832
70833   if( !u.cn.res ){
70834     /* If there is data, jump to P2 */
70835     pc = pOp->p2 - 1;
70836   }
70837   break;
70838 }
70839 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70840
70841 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70842 /* Opcode: VRename P1 * * P4 *
70843 **
70844 ** P4 is a pointer to a virtual table object, an sqlcipher3_vtab structure.
70845 ** This opcode invokes the corresponding xRename method. The value
70846 ** in register P1 is passed as the zName argument to the xRename method.
70847 */
70848 case OP_VRename: {
70849 #if 0  /* local variables moved into u.co */
70850   sqlcipher3_vtab *pVtab;
70851   Mem *pName;
70852 #endif /* local variables moved into u.co */
70853
70854   u.co.pVtab = pOp->p4.pVtab->pVtab;
70855   u.co.pName = &aMem[pOp->p1];
70856   assert( u.co.pVtab->pModule->xRename );
70857   assert( memIsValid(u.co.pName) );
70858   REGISTER_TRACE(pOp->p1, u.co.pName);
70859   assert( u.co.pName->flags & MEM_Str );
70860   testcase( u.co.pName->enc==SQLCIPHER_UTF8 );
70861   testcase( u.co.pName->enc==SQLCIPHER_UTF16BE );
70862   testcase( u.co.pName->enc==SQLCIPHER_UTF16LE );
70863   rc = sqlcipher3VdbeChangeEncoding(u.co.pName, SQLCIPHER_UTF8);
70864   if( rc==SQLCIPHER_OK ){
70865     rc = u.co.pVtab->pModule->xRename(u.co.pVtab, u.co.pName->z);
70866     importVtabErrMsg(p, u.co.pVtab);
70867     p->expired = 0;
70868   }
70869   break;
70870 }
70871 #endif
70872
70873 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
70874 /* Opcode: VUpdate P1 P2 P3 P4 *
70875 **
70876 ** P4 is a pointer to a virtual table object, an sqlcipher3_vtab structure.
70877 ** This opcode invokes the corresponding xUpdate method. P2 values
70878 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
70879 ** invocation. The value in register (P3+P2-1) corresponds to the 
70880 ** p2th element of the argv array passed to xUpdate.
70881 **
70882 ** The xUpdate method will do a DELETE or an INSERT or both.
70883 ** The argv[0] element (which corresponds to memory cell P3)
70884 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
70885 ** deletion occurs.  The argv[1] element is the rowid of the new 
70886 ** row.  This can be NULL to have the virtual table select the new 
70887 ** rowid for itself.  The subsequent elements in the array are 
70888 ** the values of columns in the new row.
70889 **
70890 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
70891 ** a row to delete.
70892 **
70893 ** P1 is a boolean flag. If it is set to true and the xUpdate call
70894 ** is successful, then the value returned by sqlcipher3_last_insert_rowid() 
70895 ** is set to the value of the rowid for the row just inserted.
70896 */
70897 case OP_VUpdate: {
70898 #if 0  /* local variables moved into u.cp */
70899   sqlcipher3_vtab *pVtab;
70900   sqlcipher3_module *pModule;
70901   int nArg;
70902   int i;
70903   sqlcipher_int64 rowid;
70904   Mem **apArg;
70905   Mem *pX;
70906 #endif /* local variables moved into u.cp */
70907
70908   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70909        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70910   );
70911   u.cp.pVtab = pOp->p4.pVtab->pVtab;
70912   u.cp.pModule = (sqlcipher3_module *)u.cp.pVtab->pModule;
70913   u.cp.nArg = pOp->p2;
70914   assert( pOp->p4type==P4_VTAB );
70915   if( ALWAYS(u.cp.pModule->xUpdate) ){
70916     u8 vtabOnConflict = db->vtabOnConflict;
70917     u.cp.apArg = p->apArg;
70918     u.cp.pX = &aMem[pOp->p3];
70919     for(u.cp.i=0; u.cp.i<u.cp.nArg; u.cp.i++){
70920       assert( memIsValid(u.cp.pX) );
70921       memAboutToChange(p, u.cp.pX);
70922       sqlcipher3VdbeMemStoreType(u.cp.pX);
70923       u.cp.apArg[u.cp.i] = u.cp.pX;
70924       u.cp.pX++;
70925     }
70926     db->vtabOnConflict = pOp->p5;
70927     rc = u.cp.pModule->xUpdate(u.cp.pVtab, u.cp.nArg, u.cp.apArg, &u.cp.rowid);
70928     db->vtabOnConflict = vtabOnConflict;
70929     importVtabErrMsg(p, u.cp.pVtab);
70930     if( rc==SQLCIPHER_OK && pOp->p1 ){
70931       assert( u.cp.nArg>1 && u.cp.apArg[0] && (u.cp.apArg[0]->flags&MEM_Null) );
70932       db->lastRowid = lastRowid = u.cp.rowid;
70933     }
70934     if( rc==SQLCIPHER_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70935       if( pOp->p5==OE_Ignore ){
70936         rc = SQLCIPHER_OK;
70937       }else{
70938         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70939       }
70940     }else{
70941       p->nChange++;
70942     }
70943   }
70944   break;
70945 }
70946 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
70947
70948 #ifndef  SQLCIPHER_OMIT_PAGER_PRAGMAS
70949 /* Opcode: Pagecount P1 P2 * * *
70950 **
70951 ** Write the current number of pages in database P1 to memory cell P2.
70952 */
70953 case OP_Pagecount: {            /* out2-prerelease */
70954   pOut->u.i = sqlcipher3BtreeLastPage(db->aDb[pOp->p1].pBt);
70955   break;
70956 }
70957 #endif
70958
70959
70960 #ifndef  SQLCIPHER_OMIT_PAGER_PRAGMAS
70961 /* Opcode: MaxPgcnt P1 P2 P3 * *
70962 **
70963 ** Try to set the maximum page count for database P1 to the value in P3.
70964 ** Do not let the maximum page count fall below the current page count and
70965 ** do not change the maximum page count value if P3==0.
70966 **
70967 ** Store the maximum page count after the change in register P2.
70968 */
70969 case OP_MaxPgcnt: {            /* out2-prerelease */
70970   unsigned int newMax;
70971   Btree *pBt;
70972
70973   pBt = db->aDb[pOp->p1].pBt;
70974   newMax = 0;
70975   if( pOp->p3 ){
70976     newMax = sqlcipher3BtreeLastPage(pBt);
70977     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
70978   }
70979   pOut->u.i = sqlcipher3BtreeMaxPageCount(pBt, newMax);
70980   break;
70981 }
70982 #endif
70983
70984
70985 #ifndef SQLCIPHER_OMIT_TRACE
70986 /* Opcode: Trace * * * P4 *
70987 **
70988 ** If tracing is enabled (by the sqlcipher3_trace()) interface, then
70989 ** the UTF-8 string contained in P4 is emitted on the trace callback.
70990 */
70991 case OP_Trace: {
70992 #if 0  /* local variables moved into u.cq */
70993   char *zTrace;
70994   char *z;
70995 #endif /* local variables moved into u.cq */
70996
70997   if( db->xTrace && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
70998     u.cq.z = sqlcipher3VdbeExpandSql(p, u.cq.zTrace);
70999     db->xTrace(db->pTraceArg, u.cq.z);
71000     sqlcipher3DbFree(db, u.cq.z);
71001   }
71002 #ifdef SQLCIPHER_DEBUG
71003   if( (db->flags & SQLCIPHER_SqlTrace)!=0
71004    && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71005   ){
71006     sqlcipher3DebugPrintf("SQL-trace: %s\n", u.cq.zTrace);
71007   }
71008 #endif /* SQLCIPHER_DEBUG */
71009   break;
71010 }
71011 #endif
71012
71013
71014 /* Opcode: Noop * * * * *
71015 **
71016 ** Do nothing.  This instruction is often useful as a jump
71017 ** destination.
71018 */
71019 /*
71020 ** The magic Explain opcode are only inserted when explain==2 (which
71021 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71022 ** This opcode records information from the optimizer.  It is the
71023 ** the same as a no-op.  This opcodesnever appears in a real VM program.
71024 */
71025 default: {          /* This is really OP_Noop and OP_Explain */
71026   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71027   break;
71028 }
71029
71030 /*****************************************************************************
71031 ** The cases of the switch statement above this line should all be indented
71032 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71033 ** readability.  From this point on down, the normal indentation rules are
71034 ** restored.
71035 *****************************************************************************/
71036     }
71037
71038 #ifdef VDBE_PROFILE
71039     {
71040       u64 elapsed = sqlcipher3Hwtime() - start;
71041       pOp->cycles += elapsed;
71042       pOp->cnt++;
71043 #if 0
71044         fprintf(stdout, "%10llu ", elapsed);
71045         sqlcipher3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71046 #endif
71047     }
71048 #endif
71049
71050     /* The following code adds nothing to the actual functionality
71051     ** of the program.  It is only here for testing and debugging.
71052     ** On the other hand, it does burn CPU cycles every time through
71053     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71054     */
71055 #ifndef NDEBUG
71056     assert( pc>=-1 && pc<p->nOp );
71057
71058 #ifdef SQLCIPHER_DEBUG
71059     if( p->trace ){
71060       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71061       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71062         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71063       }
71064       if( pOp->opflags & OPFLG_OUT3 ){
71065         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71066       }
71067     }
71068 #endif  /* SQLCIPHER_DEBUG */
71069 #endif  /* NDEBUG */
71070   }  /* The end of the for(;;) loop the loops through opcodes */
71071
71072   /* If we reach this point, it means that execution is finished with
71073   ** an error of some kind.
71074   */
71075 vdbe_error_halt:
71076   assert( rc );
71077   p->rc = rc;
71078   testcase( sqlcipher3GlobalConfig.xLog!=0 );
71079   sqlcipher3_log(rc, "statement aborts at %d: [%s] %s", 
71080                    pc, p->zSql, p->zErrMsg);
71081   sqlcipher3VdbeHalt(p);
71082   if( rc==SQLCIPHER_IOERR_NOMEM ) db->mallocFailed = 1;
71083   rc = SQLCIPHER_ERROR;
71084   if( resetSchemaOnFault>0 ){
71085     sqlcipher3ResetInternalSchema(db, resetSchemaOnFault-1);
71086   }
71087
71088   /* This is the only way out of this procedure.  We have to
71089   ** release the mutexes on btrees that were acquired at the
71090   ** top. */
71091 vdbe_return:
71092   db->lastRowid = lastRowid;
71093   sqlcipher3VdbeLeave(p);
71094   return rc;
71095
71096   /* Jump to here if a string or blob larger than SQLCIPHER_MAX_LENGTH
71097   ** is encountered.
71098   */
71099 too_big:
71100   sqlcipher3SetString(&p->zErrMsg, db, "string or blob too big");
71101   rc = SQLCIPHER_TOOBIG;
71102   goto vdbe_error_halt;
71103
71104   /* Jump to here if a malloc() fails.
71105   */
71106 no_mem:
71107   db->mallocFailed = 1;
71108   sqlcipher3SetString(&p->zErrMsg, db, "out of memory");
71109   rc = SQLCIPHER_NOMEM;
71110   goto vdbe_error_halt;
71111
71112   /* Jump to here for any other kind of fatal error.  The "rc" variable
71113   ** should hold the error number.
71114   */
71115 abort_due_to_error:
71116   assert( p->zErrMsg==0 );
71117   if( db->mallocFailed ) rc = SQLCIPHER_NOMEM;
71118   if( rc!=SQLCIPHER_IOERR_NOMEM ){
71119     sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3ErrStr(rc));
71120   }
71121   goto vdbe_error_halt;
71122
71123   /* Jump to here if the sqlcipher3_interrupt() API sets the interrupt
71124   ** flag.
71125   */
71126 abort_due_to_interrupt:
71127   assert( db->u1.isInterrupted );
71128   rc = SQLCIPHER_INTERRUPT;
71129   p->rc = rc;
71130   sqlcipher3SetString(&p->zErrMsg, db, "%s", sqlcipher3ErrStr(rc));
71131   goto vdbe_error_halt;
71132 }
71133
71134 /************** End of vdbe.c ************************************************/
71135 /************** Begin file vdbeblob.c ****************************************/
71136 /*
71137 ** 2007 May 1
71138 **
71139 ** The author disclaims copyright to this source code.  In place of
71140 ** a legal notice, here is a blessing:
71141 **
71142 **    May you do good and not evil.
71143 **    May you find forgiveness for yourself and forgive others.
71144 **    May you share freely, never taking more than you give.
71145 **
71146 *************************************************************************
71147 **
71148 ** This file contains code used to implement incremental BLOB I/O.
71149 */
71150
71151
71152 #ifndef SQLCIPHER_OMIT_INCRBLOB
71153
71154 /*
71155 ** Valid sqlcipher3_blob* handles point to Incrblob structures.
71156 */
71157 typedef struct Incrblob Incrblob;
71158 struct Incrblob {
71159   int flags;              /* Copy of "flags" passed to sqlcipher3_blob_open() */
71160   int nByte;              /* Size of open blob, in bytes */
71161   int iOffset;            /* Byte offset of blob in cursor data */
71162   int iCol;               /* Table column this handle is open on */
71163   BtCursor *pCsr;         /* Cursor pointing at blob row */
71164   sqlcipher3_stmt *pStmt;    /* Statement holding cursor open */
71165   sqlcipher3 *db;            /* The associated database */
71166 };
71167
71168
71169 /*
71170 ** This function is used by both blob_open() and blob_reopen(). It seeks
71171 ** the b-tree cursor associated with blob handle p to point to row iRow.
71172 ** If successful, SQLCIPHER_OK is returned and subsequent calls to
71173 ** sqlcipher3_blob_read() or sqlcipher3_blob_write() access the specified row.
71174 **
71175 ** If an error occurs, or if the specified row does not exist or does not
71176 ** contain a value of type TEXT or BLOB in the column nominated when the
71177 ** blob handle was opened, then an error code is returned and *pzErr may
71178 ** be set to point to a buffer containing an error message. It is the
71179 ** responsibility of the caller to free the error message buffer using
71180 ** sqlcipher3DbFree().
71181 **
71182 ** If an error does occur, then the b-tree cursor is closed. All subsequent
71183 ** calls to sqlcipher3_blob_read(), blob_write() or blob_reopen() will 
71184 ** immediately return SQLCIPHER_ABORT.
71185 */
71186 static int blobSeekToRow(Incrblob *p, sqlcipher3_int64 iRow, char **pzErr){
71187   int rc;                         /* Error code */
71188   char *zErr = 0;                 /* Error message */
71189   Vdbe *v = (Vdbe *)p->pStmt;
71190
71191   /* Set the value of the SQL statements only variable to integer iRow. 
71192   ** This is done directly instead of using sqlcipher3_bind_int64() to avoid 
71193   ** triggering asserts related to mutexes.
71194   */
71195   assert( v->aVar[0].flags&MEM_Int );
71196   v->aVar[0].u.i = iRow;
71197
71198   rc = sqlcipher3_step(p->pStmt);
71199   if( rc==SQLCIPHER_ROW ){
71200     u32 type = v->apCsr[0]->aType[p->iCol];
71201     if( type<12 ){
71202       zErr = sqlcipher3MPrintf(p->db, "cannot open value of type %s",
71203           type==0?"null": type==7?"real": "integer"
71204       );
71205       rc = SQLCIPHER_ERROR;
71206       sqlcipher3_finalize(p->pStmt);
71207       p->pStmt = 0;
71208     }else{
71209       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71210       p->nByte = sqlcipher3VdbeSerialTypeLen(type);
71211       p->pCsr =  v->apCsr[0]->pCursor;
71212       sqlcipher3BtreeEnterCursor(p->pCsr);
71213       sqlcipher3BtreeCacheOverflow(p->pCsr);
71214       sqlcipher3BtreeLeaveCursor(p->pCsr);
71215     }
71216   }
71217
71218   if( rc==SQLCIPHER_ROW ){
71219     rc = SQLCIPHER_OK;
71220   }else if( p->pStmt ){
71221     rc = sqlcipher3_finalize(p->pStmt);
71222     p->pStmt = 0;
71223     if( rc==SQLCIPHER_OK ){
71224       zErr = sqlcipher3MPrintf(p->db, "no such rowid: %lld", iRow);
71225       rc = SQLCIPHER_ERROR;
71226     }else{
71227       zErr = sqlcipher3MPrintf(p->db, "%s", sqlcipher3_errmsg(p->db));
71228     }
71229   }
71230
71231   assert( rc!=SQLCIPHER_OK || zErr==0 );
71232   assert( rc!=SQLCIPHER_ROW && rc!=SQLCIPHER_DONE );
71233
71234   *pzErr = zErr;
71235   return rc;
71236 }
71237
71238 /*
71239 ** Open a blob handle.
71240 */
71241 SQLCIPHER_API int sqlcipher3_blob_open(
71242   sqlcipher3* db,            /* The database connection */
71243   const char *zDb,        /* The attached database containing the blob */
71244   const char *zTable,     /* The table containing the blob */
71245   const char *zColumn,    /* The column containing the blob */
71246   sqlcipher_int64 iRow,      /* The row containing the glob */
71247   int flags,              /* True -> read/write access, false -> read-only */
71248   sqlcipher3_blob **ppBlob   /* Handle for accessing the blob returned here */
71249 ){
71250   int nAttempt = 0;
71251   int iCol;               /* Index of zColumn in row-record */
71252
71253   /* This VDBE program seeks a btree cursor to the identified 
71254   ** db/table/row entry. The reason for using a vdbe program instead
71255   ** of writing code to use the b-tree layer directly is that the
71256   ** vdbe program will take advantage of the various transaction,
71257   ** locking and error handling infrastructure built into the vdbe.
71258   **
71259   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71260   ** Code external to the Vdbe then "borrows" the b-tree cursor and
71261   ** uses it to implement the blob_read(), blob_write() and 
71262   ** blob_bytes() functions.
71263   **
71264   ** The sqlcipher3_blob_close() function finalizes the vdbe program,
71265   ** which closes the b-tree cursor and (possibly) commits the 
71266   ** transaction.
71267   */
71268   static const VdbeOpList openBlob[] = {
71269     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
71270     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
71271     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
71272
71273     /* One of the following two instructions is replaced by an OP_Noop. */
71274     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
71275     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
71276
71277     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
71278     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
71279     {OP_Column, 0, 0, 1},          /* 7  */
71280     {OP_ResultRow, 1, 0, 0},       /* 8  */
71281     {OP_Goto, 0, 5, 0},            /* 9  */
71282     {OP_Close, 0, 0, 0},           /* 10 */
71283     {OP_Halt, 0, 0, 0},            /* 11 */
71284   };
71285
71286   int rc = SQLCIPHER_OK;
71287   char *zErr = 0;
71288   Table *pTab;
71289   Parse *pParse = 0;
71290   Incrblob *pBlob = 0;
71291
71292   flags = !!flags;                /* flags = (flags ? 1 : 0); */
71293   *ppBlob = 0;
71294
71295   sqlcipher3_mutex_enter(db->mutex);
71296
71297   pBlob = (Incrblob *)sqlcipher3DbMallocZero(db, sizeof(Incrblob));
71298   if( !pBlob ) goto blob_open_out;
71299   pParse = sqlcipher3StackAllocRaw(db, sizeof(*pParse));
71300   if( !pParse ) goto blob_open_out;
71301
71302   do {
71303     memset(pParse, 0, sizeof(Parse));
71304     pParse->db = db;
71305     sqlcipher3DbFree(db, zErr);
71306     zErr = 0;
71307
71308     sqlcipher3BtreeEnterAll(db);
71309     pTab = sqlcipher3LocateTable(pParse, 0, zTable, zDb);
71310     if( pTab && IsVirtual(pTab) ){
71311       pTab = 0;
71312       sqlcipher3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
71313     }
71314 #ifndef SQLCIPHER_OMIT_VIEW
71315     if( pTab && pTab->pSelect ){
71316       pTab = 0;
71317       sqlcipher3ErrorMsg(pParse, "cannot open view: %s", zTable);
71318     }
71319 #endif
71320     if( !pTab ){
71321       if( pParse->zErrMsg ){
71322         sqlcipher3DbFree(db, zErr);
71323         zErr = pParse->zErrMsg;
71324         pParse->zErrMsg = 0;
71325       }
71326       rc = SQLCIPHER_ERROR;
71327       sqlcipher3BtreeLeaveAll(db);
71328       goto blob_open_out;
71329     }
71330
71331     /* Now search pTab for the exact column. */
71332     for(iCol=0; iCol<pTab->nCol; iCol++) {
71333       if( sqlcipher3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
71334         break;
71335       }
71336     }
71337     if( iCol==pTab->nCol ){
71338       sqlcipher3DbFree(db, zErr);
71339       zErr = sqlcipher3MPrintf(db, "no such column: \"%s\"", zColumn);
71340       rc = SQLCIPHER_ERROR;
71341       sqlcipher3BtreeLeaveAll(db);
71342       goto blob_open_out;
71343     }
71344
71345     /* If the value is being opened for writing, check that the
71346     ** column is not indexed, and that it is not part of a foreign key. 
71347     ** It is against the rules to open a column to which either of these
71348     ** descriptions applies for writing.  */
71349     if( flags ){
71350       const char *zFault = 0;
71351       Index *pIdx;
71352 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
71353       if( db->flags&SQLCIPHER_ForeignKeys ){
71354         /* Check that the column is not part of an FK child key definition. It
71355         ** is not necessary to check if it is part of a parent key, as parent
71356         ** key columns must be indexed. The check below will pick up this 
71357         ** case.  */
71358         FKey *pFKey;
71359         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
71360           int j;
71361           for(j=0; j<pFKey->nCol; j++){
71362             if( pFKey->aCol[j].iFrom==iCol ){
71363               zFault = "foreign key";
71364             }
71365           }
71366         }
71367       }
71368 #endif
71369       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71370         int j;
71371         for(j=0; j<pIdx->nColumn; j++){
71372           if( pIdx->aiColumn[j]==iCol ){
71373             zFault = "indexed";
71374           }
71375         }
71376       }
71377       if( zFault ){
71378         sqlcipher3DbFree(db, zErr);
71379         zErr = sqlcipher3MPrintf(db, "cannot open %s column for writing", zFault);
71380         rc = SQLCIPHER_ERROR;
71381         sqlcipher3BtreeLeaveAll(db);
71382         goto blob_open_out;
71383       }
71384     }
71385
71386     pBlob->pStmt = (sqlcipher3_stmt *)sqlcipher3VdbeCreate(db);
71387     assert( pBlob->pStmt || db->mallocFailed );
71388     if( pBlob->pStmt ){
71389       Vdbe *v = (Vdbe *)pBlob->pStmt;
71390       int iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
71391
71392       sqlcipher3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
71393
71394
71395       /* Configure the OP_Transaction */
71396       sqlcipher3VdbeChangeP1(v, 0, iDb);
71397       sqlcipher3VdbeChangeP2(v, 0, flags);
71398
71399       /* Configure the OP_VerifyCookie */
71400       sqlcipher3VdbeChangeP1(v, 1, iDb);
71401       sqlcipher3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
71402       sqlcipher3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
71403
71404       /* Make sure a mutex is held on the table to be accessed */
71405       sqlcipher3VdbeUsesBtree(v, iDb); 
71406
71407       /* Configure the OP_TableLock instruction */
71408 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
71409       sqlcipher3VdbeChangeToNoop(v, 2);
71410 #else
71411       sqlcipher3VdbeChangeP1(v, 2, iDb);
71412       sqlcipher3VdbeChangeP2(v, 2, pTab->tnum);
71413       sqlcipher3VdbeChangeP3(v, 2, flags);
71414       sqlcipher3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
71415 #endif
71416
71417       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
71418       ** parameter of the other to pTab->tnum.  */
71419       sqlcipher3VdbeChangeToNoop(v, 4 - flags);
71420       sqlcipher3VdbeChangeP2(v, 3 + flags, pTab->tnum);
71421       sqlcipher3VdbeChangeP3(v, 3 + flags, iDb);
71422
71423       /* Configure the number of columns. Configure the cursor to
71424       ** think that the table has one more column than it really
71425       ** does. An OP_Column to retrieve this imaginary column will
71426       ** always return an SQL NULL. This is useful because it means
71427       ** we can invoke OP_Column to fill in the vdbe cursors type 
71428       ** and offset cache without causing any IO.
71429       */
71430       sqlcipher3VdbeChangeP4(v, 3+flags, SQLCIPHER_INT_TO_PTR(pTab->nCol+1),P4_INT32);
71431       sqlcipher3VdbeChangeP2(v, 7, pTab->nCol);
71432       if( !db->mallocFailed ){
71433         pParse->nVar = 1;
71434         pParse->nMem = 1;
71435         pParse->nTab = 1;
71436         sqlcipher3VdbeMakeReady(v, pParse);
71437       }
71438     }
71439    
71440     pBlob->flags = flags;
71441     pBlob->iCol = iCol;
71442     pBlob->db = db;
71443     sqlcipher3BtreeLeaveAll(db);
71444     if( db->mallocFailed ){
71445       goto blob_open_out;
71446     }
71447     sqlcipher3_bind_int64(pBlob->pStmt, 1, iRow);
71448     rc = blobSeekToRow(pBlob, iRow, &zErr);
71449   } while( (++nAttempt)<5 && rc==SQLCIPHER_SCHEMA );
71450
71451 blob_open_out:
71452   if( rc==SQLCIPHER_OK && db->mallocFailed==0 ){
71453     *ppBlob = (sqlcipher3_blob *)pBlob;
71454   }else{
71455     if( pBlob && pBlob->pStmt ) sqlcipher3VdbeFinalize((Vdbe *)pBlob->pStmt);
71456     sqlcipher3DbFree(db, pBlob);
71457   }
71458   sqlcipher3Error(db, rc, (zErr ? "%s" : 0), zErr);
71459   sqlcipher3DbFree(db, zErr);
71460   sqlcipher3StackFree(db, pParse);
71461   rc = sqlcipher3ApiExit(db, rc);
71462   sqlcipher3_mutex_leave(db->mutex);
71463   return rc;
71464 }
71465
71466 /*
71467 ** Close a blob handle that was previously created using
71468 ** sqlcipher3_blob_open().
71469 */
71470 SQLCIPHER_API int sqlcipher3_blob_close(sqlcipher3_blob *pBlob){
71471   Incrblob *p = (Incrblob *)pBlob;
71472   int rc;
71473   sqlcipher3 *db;
71474
71475   if( p ){
71476     db = p->db;
71477     sqlcipher3_mutex_enter(db->mutex);
71478     rc = sqlcipher3_finalize(p->pStmt);
71479     sqlcipher3DbFree(db, p);
71480     sqlcipher3_mutex_leave(db->mutex);
71481   }else{
71482     rc = SQLCIPHER_OK;
71483   }
71484   return rc;
71485 }
71486
71487 /*
71488 ** Perform a read or write operation on a blob
71489 */
71490 static int blobReadWrite(
71491   sqlcipher3_blob *pBlob, 
71492   void *z, 
71493   int n, 
71494   int iOffset, 
71495   int (*xCall)(BtCursor*, u32, u32, void*)
71496 ){
71497   int rc;
71498   Incrblob *p = (Incrblob *)pBlob;
71499   Vdbe *v;
71500   sqlcipher3 *db;
71501
71502   if( p==0 ) return SQLCIPHER_MISUSE_BKPT;
71503   db = p->db;
71504   sqlcipher3_mutex_enter(db->mutex);
71505   v = (Vdbe*)p->pStmt;
71506
71507   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
71508     /* Request is out of range. Return a transient error. */
71509     rc = SQLCIPHER_ERROR;
71510     sqlcipher3Error(db, SQLCIPHER_ERROR, 0);
71511   }else if( v==0 ){
71512     /* If there is no statement handle, then the blob-handle has
71513     ** already been invalidated. Return SQLCIPHER_ABORT in this case.
71514     */
71515     rc = SQLCIPHER_ABORT;
71516   }else{
71517     /* Call either BtreeData() or BtreePutData(). If SQLCIPHER_ABORT is
71518     ** returned, clean-up the statement handle.
71519     */
71520     assert( db == v->db );
71521     sqlcipher3BtreeEnterCursor(p->pCsr);
71522     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
71523     sqlcipher3BtreeLeaveCursor(p->pCsr);
71524     if( rc==SQLCIPHER_ABORT ){
71525       sqlcipher3VdbeFinalize(v);
71526       p->pStmt = 0;
71527     }else{
71528       db->errCode = rc;
71529       v->rc = rc;
71530     }
71531   }
71532   rc = sqlcipher3ApiExit(db, rc);
71533   sqlcipher3_mutex_leave(db->mutex);
71534   return rc;
71535 }
71536
71537 /*
71538 ** Read data from a blob handle.
71539 */
71540 SQLCIPHER_API int sqlcipher3_blob_read(sqlcipher3_blob *pBlob, void *z, int n, int iOffset){
71541   return blobReadWrite(pBlob, z, n, iOffset, sqlcipher3BtreeData);
71542 }
71543
71544 /*
71545 ** Write data to a blob handle.
71546 */
71547 SQLCIPHER_API int sqlcipher3_blob_write(sqlcipher3_blob *pBlob, const void *z, int n, int iOffset){
71548   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlcipher3BtreePutData);
71549 }
71550
71551 /*
71552 ** Query a blob handle for the size of the data.
71553 **
71554 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
71555 ** so no mutex is required for access.
71556 */
71557 SQLCIPHER_API int sqlcipher3_blob_bytes(sqlcipher3_blob *pBlob){
71558   Incrblob *p = (Incrblob *)pBlob;
71559   return (p && p->pStmt) ? p->nByte : 0;
71560 }
71561
71562 /*
71563 ** Move an existing blob handle to point to a different row of the same
71564 ** database table.
71565 **
71566 ** If an error occurs, or if the specified row does not exist or does not
71567 ** contain a blob or text value, then an error code is returned and the
71568 ** database handle error code and message set. If this happens, then all 
71569 ** subsequent calls to sqlcipher3_blob_xxx() functions (except blob_close()) 
71570 ** immediately return SQLCIPHER_ABORT.
71571 */
71572 SQLCIPHER_API int sqlcipher3_blob_reopen(sqlcipher3_blob *pBlob, sqlcipher3_int64 iRow){
71573   int rc;
71574   Incrblob *p = (Incrblob *)pBlob;
71575   sqlcipher3 *db;
71576
71577   if( p==0 ) return SQLCIPHER_MISUSE_BKPT;
71578   db = p->db;
71579   sqlcipher3_mutex_enter(db->mutex);
71580
71581   if( p->pStmt==0 ){
71582     /* If there is no statement handle, then the blob-handle has
71583     ** already been invalidated. Return SQLCIPHER_ABORT in this case.
71584     */
71585     rc = SQLCIPHER_ABORT;
71586   }else{
71587     char *zErr;
71588     rc = blobSeekToRow(p, iRow, &zErr);
71589     if( rc!=SQLCIPHER_OK ){
71590       sqlcipher3Error(db, rc, (zErr ? "%s" : 0), zErr);
71591       sqlcipher3DbFree(db, zErr);
71592     }
71593     assert( rc!=SQLCIPHER_SCHEMA );
71594   }
71595
71596   rc = sqlcipher3ApiExit(db, rc);
71597   assert( rc==SQLCIPHER_OK || p->pStmt==0 );
71598   sqlcipher3_mutex_leave(db->mutex);
71599   return rc;
71600 }
71601
71602 #endif /* #ifndef SQLCIPHER_OMIT_INCRBLOB */
71603
71604 /************** End of vdbeblob.c ********************************************/
71605 /************** Begin file vdbesort.c ****************************************/
71606 /*
71607 ** 2011 July 9
71608 **
71609 ** The author disclaims copyright to this source code.  In place of
71610 ** a legal notice, here is a blessing:
71611 **
71612 **    May you do good and not evil.
71613 **    May you find forgiveness for yourself and forgive others.
71614 **    May you share freely, never taking more than you give.
71615 **
71616 *************************************************************************
71617 ** This file contains code for the VdbeSorter object, used in concert with
71618 ** a VdbeCursor to sort large numbers of keys (as may be required, for
71619 ** example, by CREATE INDEX statements on tables too large to fit in main
71620 ** memory).
71621 */
71622
71623
71624 #ifndef SQLCIPHER_OMIT_MERGE_SORT
71625
71626 typedef struct VdbeSorterIter VdbeSorterIter;
71627 typedef struct SorterRecord SorterRecord;
71628
71629 /*
71630 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
71631 **
71632 ** As keys are added to the sorter, they are written to disk in a series
71633 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
71634 ** the same as the cache-size allowed for temporary databases. In order
71635 ** to allow the caller to extract keys from the sorter in sorted order,
71636 ** all PMAs currently stored on disk must be merged together. This comment
71637 ** describes the data structure used to do so. The structure supports 
71638 ** merging any number of arrays in a single pass with no redundant comparison 
71639 ** operations.
71640 **
71641 ** The aIter[] array contains an iterator for each of the PMAs being merged.
71642 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
71643 ** the purposes of the paragraphs below, we assume that the array is actually 
71644 ** N elements in size, where N is the smallest power of 2 greater to or equal 
71645 ** to the number of iterators being merged. The extra aIter[] elements are 
71646 ** treated as if they are empty (always at EOF).
71647 **
71648 ** The aTree[] array is also N elements in size. The value of N is stored in
71649 ** the VdbeSorter.nTree variable.
71650 **
71651 ** The final (N/2) elements of aTree[] contain the results of comparing
71652 ** pairs of iterator keys together. Element i contains the result of 
71653 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
71654 ** aTree element is set to the index of it. 
71655 **
71656 ** For the purposes of this comparison, EOF is considered greater than any
71657 ** other key value. If the keys are equal (only possible with two EOF
71658 ** values), it doesn't matter which index is stored.
71659 **
71660 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
71661 ** above contains the index of the smallest of each block of 4 iterators.
71662 ** And so on. So that aTree[1] contains the index of the iterator that 
71663 ** currently points to the smallest key value. aTree[0] is unused.
71664 **
71665 ** Example:
71666 **
71667 **     aIter[0] -> Banana
71668 **     aIter[1] -> Feijoa
71669 **     aIter[2] -> Elderberry
71670 **     aIter[3] -> Currant
71671 **     aIter[4] -> Grapefruit
71672 **     aIter[5] -> Apple
71673 **     aIter[6] -> Durian
71674 **     aIter[7] -> EOF
71675 **
71676 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
71677 **
71678 ** The current element is "Apple" (the value of the key indicated by 
71679 ** iterator 5). When the Next() operation is invoked, iterator 5 will
71680 ** be advanced to the next key in its segment. Say the next key is
71681 ** "Eggplant":
71682 **
71683 **     aIter[5] -> Eggplant
71684 **
71685 ** The contents of aTree[] are updated first by comparing the new iterator
71686 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
71687 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
71688 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
71689 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
71690 ** so the value written into element 1 of the array is 0. As follows:
71691 **
71692 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
71693 **
71694 ** In other words, each time we advance to the next sorter element, log2(N)
71695 ** key comparison operations are required, where N is the number of segments
71696 ** being merged (rounded up to the next power of 2).
71697 */
71698 struct VdbeSorter {
71699   int nInMemory;                  /* Current size of pRecord list as PMA */
71700   int nTree;                      /* Used size of aTree/aIter (power of 2) */
71701   VdbeSorterIter *aIter;          /* Array of iterators to merge */
71702   int *aTree;                     /* Current state of incremental merge */
71703   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
71704   i64 iReadOff;                   /* Current read offset within file pTemp1 */
71705   sqlcipher3_file *pTemp1;           /* PMA file 1 */
71706   int nPMA;                       /* Number of PMAs stored in pTemp1 */
71707   SorterRecord *pRecord;          /* Head of in-memory record list */
71708   int mnPmaSize;                  /* Minimum PMA size, in bytes */
71709   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
71710   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
71711 };
71712
71713 /*
71714 ** The following type is an iterator for a PMA. It caches the current key in 
71715 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
71716 */
71717 struct VdbeSorterIter {
71718   i64 iReadOff;                   /* Current read offset */
71719   i64 iEof;                       /* 1 byte past EOF for this iterator */
71720   sqlcipher3_file *pFile;            /* File iterator is reading from */
71721   int nAlloc;                     /* Bytes of space at aAlloc */
71722   u8 *aAlloc;                     /* Allocated space */
71723   int nKey;                       /* Number of bytes in key */
71724   u8 *aKey;                       /* Pointer to current key */
71725 };
71726
71727 /*
71728 ** A structure to store a single record. All in-memory records are connected
71729 ** together into a linked list headed at VdbeSorter.pRecord using the 
71730 ** SorterRecord.pNext pointer.
71731 */
71732 struct SorterRecord {
71733   void *pVal;
71734   int nVal;
71735   SorterRecord *pNext;
71736 };
71737
71738 /* Minimum allowable value for the VdbeSorter.nWorking variable */
71739 #define SORTER_MIN_WORKING 10
71740
71741 /* Maximum number of segments to merge in a single pass. */
71742 #define SORTER_MAX_MERGE_COUNT 16
71743
71744 /*
71745 ** Free all memory belonging to the VdbeSorterIter object passed as the second
71746 ** argument. All structure fields are set to zero before returning.
71747 */
71748 static void vdbeSorterIterZero(sqlcipher3 *db, VdbeSorterIter *pIter){
71749   sqlcipher3DbFree(db, pIter->aAlloc);
71750   memset(pIter, 0, sizeof(VdbeSorterIter));
71751 }
71752
71753 /*
71754 ** Advance iterator pIter to the next key in its PMA. Return SQLCIPHER_OK if
71755 ** no error occurs, or an SQLite error code if one does.
71756 */
71757 static int vdbeSorterIterNext(
71758   sqlcipher3 *db,                    /* Database handle (for sqlcipher3DbMalloc() ) */
71759   VdbeSorterIter *pIter           /* Iterator to advance */
71760 ){
71761   int rc;                         /* Return Code */
71762   int nRead;                      /* Number of bytes read */
71763   int nRec = 0;                   /* Size of record in bytes */
71764   int iOff = 0;                   /* Size of serialized size varint in bytes */
71765
71766   assert( pIter->iEof>=pIter->iReadOff );
71767   if( pIter->iEof-pIter->iReadOff>5 ){
71768     nRead = 5;
71769   }else{
71770     nRead = (int)(pIter->iEof - pIter->iReadOff);
71771   }
71772   if( nRead<=0 ){
71773     /* This is an EOF condition */
71774     vdbeSorterIterZero(db, pIter);
71775     return SQLCIPHER_OK;
71776   }
71777
71778   rc = sqlcipher3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
71779   if( rc==SQLCIPHER_OK ){
71780     iOff = getVarint32(pIter->aAlloc, nRec);
71781     if( (iOff+nRec)>nRead ){
71782       int nRead2;                   /* Number of extra bytes to read */
71783       if( (iOff+nRec)>pIter->nAlloc ){
71784         int nNew = pIter->nAlloc*2;
71785         while( (iOff+nRec)>nNew ) nNew = nNew*2;
71786         pIter->aAlloc = sqlcipher3DbReallocOrFree(db, pIter->aAlloc, nNew);
71787         if( !pIter->aAlloc ) return SQLCIPHER_NOMEM;
71788         pIter->nAlloc = nNew;
71789       }
71790   
71791       nRead2 = iOff + nRec - nRead;
71792       rc = sqlcipher3OsRead(
71793           pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
71794       );
71795     }
71796   }
71797
71798   assert( rc!=SQLCIPHER_OK || nRec>0 );
71799   pIter->iReadOff += iOff+nRec;
71800   pIter->nKey = nRec;
71801   pIter->aKey = &pIter->aAlloc[iOff];
71802   return rc;
71803 }
71804
71805 /*
71806 ** Write a single varint, value iVal, to file-descriptor pFile. Return
71807 ** SQLCIPHER_OK if successful, or an SQLite error code if some error occurs.
71808 **
71809 ** The value of *piOffset when this function is called is used as the byte
71810 ** offset in file pFile to write to. Before returning, *piOffset is 
71811 ** incremented by the number of bytes written.
71812 */
71813 static int vdbeSorterWriteVarint(
71814   sqlcipher3_file *pFile,            /* File to write to */
71815   i64 iVal,                       /* Value to write as a varint */
71816   i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
71817 ){
71818   u8 aVarint[9];                  /* Buffer large enough for a varint */
71819   int nVarint;                    /* Number of used bytes in varint */
71820   int rc;                         /* Result of write() call */
71821
71822   nVarint = sqlcipher3PutVarint(aVarint, iVal);
71823   rc = sqlcipher3OsWrite(pFile, aVarint, nVarint, *piOffset);
71824   *piOffset += nVarint;
71825
71826   return rc;
71827 }
71828
71829 /*
71830 ** Read a single varint from file-descriptor pFile. Return SQLCIPHER_OK if
71831 ** successful, or an SQLite error code if some error occurs.
71832 **
71833 ** The value of *piOffset when this function is called is used as the
71834 ** byte offset in file pFile from whence to read the varint. If successful
71835 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
71836 ** the first byte past the end of the varint before returning. *piVal is
71837 ** set to the integer value read. If an error occurs, the final values of
71838 ** both *piOffset and *piVal are undefined.
71839 */
71840 static int vdbeSorterReadVarint(
71841   sqlcipher3_file *pFile,            /* File to read from */
71842   i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
71843   i64 *piVal                      /* OUT: Value read from file */
71844 ){
71845   u8 aVarint[9];                  /* Buffer large enough for a varint */
71846   i64 iOff = *piOffset;           /* Offset in file to read from */
71847   int rc;                         /* Return code */
71848
71849   rc = sqlcipher3OsRead(pFile, aVarint, 9, iOff);
71850   if( rc==SQLCIPHER_OK ){
71851     *piOffset += getVarint(aVarint, (u64 *)piVal);
71852   }
71853
71854   return rc;
71855 }
71856
71857 /*
71858 ** Initialize iterator pIter to scan through the PMA stored in file pFile
71859 ** starting at offset iStart and ending at offset iEof-1. This function 
71860 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
71861 ** PMA is empty).
71862 */
71863 static int vdbeSorterIterInit(
71864   sqlcipher3 *db,                    /* Database handle */
71865   VdbeSorter *pSorter,            /* Sorter object */
71866   i64 iStart,                     /* Start offset in pFile */
71867   VdbeSorterIter *pIter,          /* Iterator to populate */
71868   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71869 ){
71870   int rc;
71871
71872   assert( pSorter->iWriteOff>iStart );
71873   assert( pIter->aAlloc==0 );
71874   pIter->pFile = pSorter->pTemp1;
71875   pIter->iReadOff = iStart;
71876   pIter->nAlloc = 128;
71877   pIter->aAlloc = (u8 *)sqlcipher3DbMallocRaw(db, pIter->nAlloc);
71878   if( !pIter->aAlloc ){
71879     rc = SQLCIPHER_NOMEM;
71880   }else{
71881     i64 nByte;                         /* Total size of PMA in bytes */
71882     rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
71883     *pnByte += nByte;
71884     pIter->iEof = pIter->iReadOff + nByte;
71885   }
71886   if( rc==SQLCIPHER_OK ){
71887     rc = vdbeSorterIterNext(db, pIter);
71888   }
71889   return rc;
71890 }
71891
71892
71893 /*
71894 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
71895 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71896 ** used by the comparison. If an error occurs, return an SQLite error code.
71897 ** Otherwise, return SQLCIPHER_OK and set *pRes to a negative, zero or positive
71898 ** value, depending on whether key1 is smaller, equal to or larger than key2.
71899 **
71900 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71901 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71902 ** is true and key1 contains even a single NULL value, it is considered to
71903 ** be less than key2. Even if key2 also contains NULL values.
71904 **
71905 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71906 ** has been allocated and contains an unpacked record that is used as key2.
71907 */
71908 static void vdbeSorterCompare(
71909   VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
71910   int bOmitRowid,                 /* Ignore rowid field at end of keys */
71911   void *pKey1, int nKey1,         /* Left side of comparison */
71912   void *pKey2, int nKey2,         /* Right side of comparison */
71913   int *pRes                       /* OUT: Result of comparison */
71914 ){
71915   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71916   VdbeSorter *pSorter = pCsr->pSorter;
71917   UnpackedRecord *r2 = pSorter->pUnpacked;
71918   int i;
71919
71920   if( pKey2 ){
71921     sqlcipher3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71922   }
71923
71924   if( bOmitRowid ){
71925     r2->nField = pKeyInfo->nField;
71926     assert( r2->nField>0 );
71927     for(i=0; i<r2->nField; i++){
71928       if( r2->aMem[i].flags & MEM_Null ){
71929         *pRes = -1;
71930         return;
71931       }
71932     }
71933     r2->flags |= UNPACKED_PREFIX_MATCH;
71934   }
71935
71936   *pRes = sqlcipher3VdbeRecordCompare(nKey1, pKey1, r2);
71937 }
71938
71939 /*
71940 ** This function is called to compare two iterator keys when merging 
71941 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
71942 ** value to recalculate.
71943 */
71944 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
71945   VdbeSorter *pSorter = pCsr->pSorter;
71946   int i1;
71947   int i2;
71948   int iRes;
71949   VdbeSorterIter *p1;
71950   VdbeSorterIter *p2;
71951
71952   assert( iOut<pSorter->nTree && iOut>0 );
71953
71954   if( iOut>=(pSorter->nTree/2) ){
71955     i1 = (iOut - pSorter->nTree/2) * 2;
71956     i2 = i1 + 1;
71957   }else{
71958     i1 = pSorter->aTree[iOut*2];
71959     i2 = pSorter->aTree[iOut*2+1];
71960   }
71961
71962   p1 = &pSorter->aIter[i1];
71963   p2 = &pSorter->aIter[i2];
71964
71965   if( p1->pFile==0 ){
71966     iRes = i2;
71967   }else if( p2->pFile==0 ){
71968     iRes = i1;
71969   }else{
71970     int res;
71971     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
71972     vdbeSorterCompare(
71973         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
71974     );
71975     if( res<=0 ){
71976       iRes = i1;
71977     }else{
71978       iRes = i2;
71979     }
71980   }
71981
71982   pSorter->aTree[iOut] = iRes;
71983   return SQLCIPHER_OK;
71984 }
71985
71986 /*
71987 ** Initialize the temporary index cursor just opened as a sorter cursor.
71988 */
71989 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterInit(sqlcipher3 *db, VdbeCursor *pCsr){
71990   int pgsz;                       /* Page size of main database */
71991   int mxCache;                    /* Cache size */
71992   VdbeSorter *pSorter;            /* The new sorter */
71993   char *d;                        /* Dummy */
71994
71995   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
71996   pCsr->pSorter = pSorter = sqlcipher3DbMallocZero(db, sizeof(VdbeSorter));
71997   if( pSorter==0 ){
71998     return SQLCIPHER_NOMEM;
71999   }
72000   
72001   pSorter->pUnpacked = sqlcipher3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72002   if( pSorter->pUnpacked==0 ) return SQLCIPHER_NOMEM;
72003   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72004
72005   if( !sqlcipher3TempInMemory(db) ){
72006     pgsz = sqlcipher3BtreeGetPageSize(db->aDb[0].pBt);
72007     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72008     mxCache = db->aDb[0].pSchema->cache_size;
72009     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72010     pSorter->mxPmaSize = mxCache * pgsz;
72011   }
72012
72013   return SQLCIPHER_OK;
72014 }
72015
72016 /*
72017 ** Free the list of sorted records starting at pRecord.
72018 */
72019 static void vdbeSorterRecordFree(sqlcipher3 *db, SorterRecord *pRecord){
72020   SorterRecord *p;
72021   SorterRecord *pNext;
72022   for(p=pRecord; p; p=pNext){
72023     pNext = p->pNext;
72024     sqlcipher3DbFree(db, p);
72025   }
72026 }
72027
72028 /*
72029 ** Free any cursor components allocated by sqlcipher3VdbeSorterXXX routines.
72030 */
72031 SQLCIPHER_PRIVATE void sqlcipher3VdbeSorterClose(sqlcipher3 *db, VdbeCursor *pCsr){
72032   VdbeSorter *pSorter = pCsr->pSorter;
72033   if( pSorter ){
72034     if( pSorter->aIter ){
72035       int i;
72036       for(i=0; i<pSorter->nTree; i++){
72037         vdbeSorterIterZero(db, &pSorter->aIter[i]);
72038       }
72039       sqlcipher3DbFree(db, pSorter->aIter);
72040     }
72041     if( pSorter->pTemp1 ){
72042       sqlcipher3OsCloseFree(pSorter->pTemp1);
72043     }
72044     vdbeSorterRecordFree(db, pSorter->pRecord);
72045     sqlcipher3DbFree(db, pSorter->pUnpacked);
72046     sqlcipher3DbFree(db, pSorter);
72047     pCsr->pSorter = 0;
72048   }
72049 }
72050
72051 /*
72052 ** Allocate space for a file-handle and open a temporary file. If successful,
72053 ** set *ppFile to point to the malloc'd file-handle and return SQLCIPHER_OK.
72054 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
72055 */
72056 static int vdbeSorterOpenTempFile(sqlcipher3 *db, sqlcipher3_file **ppFile){
72057   int dummy;
72058   return sqlcipher3OsOpenMalloc(db->pVfs, 0, ppFile,
72059       SQLCIPHER_OPEN_TEMP_JOURNAL |
72060       SQLCIPHER_OPEN_READWRITE    | SQLCIPHER_OPEN_CREATE |
72061       SQLCIPHER_OPEN_EXCLUSIVE    | SQLCIPHER_OPEN_DELETEONCLOSE, &dummy
72062   );
72063 }
72064
72065 /*
72066 ** Merge the two sorted lists p1 and p2 into a single list.
72067 ** Set *ppOut to the head of the new list.
72068 */
72069 static void vdbeSorterMerge(
72070   VdbeCursor *pCsr,               /* For pKeyInfo */
72071   SorterRecord *p1,               /* First list to merge */
72072   SorterRecord *p2,               /* Second list to merge */
72073   SorterRecord **ppOut            /* OUT: Head of merged list */
72074 ){
72075   SorterRecord *pFinal = 0;
72076   SorterRecord **pp = &pFinal;
72077   void *pVal2 = p2 ? p2->pVal : 0;
72078
72079   while( p1 && p2 ){
72080     int res;
72081     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72082     if( res<=0 ){
72083       *pp = p1;
72084       pp = &p1->pNext;
72085       p1 = p1->pNext;
72086       pVal2 = 0;
72087     }else{
72088       *pp = p2;
72089        pp = &p2->pNext;
72090       p2 = p2->pNext;
72091       if( p2==0 ) break;
72092       pVal2 = p2->pVal;
72093     }
72094   }
72095   *pp = p1 ? p1 : p2;
72096   *ppOut = pFinal;
72097 }
72098
72099 /*
72100 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLCIPHER_OK
72101 ** if successful, or an SQLite error code (i.e. SQLCIPHER_NOMEM) if an error
72102 ** occurs.
72103 */
72104 static int vdbeSorterSort(VdbeCursor *pCsr){
72105   int i;
72106   SorterRecord **aSlot;
72107   SorterRecord *p;
72108   VdbeSorter *pSorter = pCsr->pSorter;
72109
72110   aSlot = (SorterRecord **)sqlcipher3MallocZero(64 * sizeof(SorterRecord *));
72111   if( !aSlot ){
72112     return SQLCIPHER_NOMEM;
72113   }
72114
72115   p = pSorter->pRecord;
72116   while( p ){
72117     SorterRecord *pNext = p->pNext;
72118     p->pNext = 0;
72119     for(i=0; aSlot[i]; i++){
72120       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72121       aSlot[i] = 0;
72122     }
72123     aSlot[i] = p;
72124     p = pNext;
72125   }
72126
72127   p = 0;
72128   for(i=0; i<64; i++){
72129     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72130   }
72131   pSorter->pRecord = p;
72132
72133   sqlcipher3_free(aSlot);
72134   return SQLCIPHER_OK;
72135 }
72136
72137
72138 /*
72139 ** Write the current contents of the in-memory linked-list to a PMA. Return
72140 ** SQLCIPHER_OK if successful, or an SQLite error code otherwise.
72141 **
72142 ** The format of a PMA is:
72143 **
72144 **     * A varint. This varint contains the total number of bytes of content
72145 **       in the PMA (not including the varint itself).
72146 **
72147 **     * One or more records packed end-to-end in order of ascending keys. 
72148 **       Each record consists of a varint followed by a blob of data (the 
72149 **       key). The varint is the number of bytes in the blob of data.
72150 */
72151 static int vdbeSorterListToPMA(sqlcipher3 *db, VdbeCursor *pCsr){
72152   int rc = SQLCIPHER_OK;             /* Return code */
72153   VdbeSorter *pSorter = pCsr->pSorter;
72154
72155   if( pSorter->nInMemory==0 ){
72156     assert( pSorter->pRecord==0 );
72157     return rc;
72158   }
72159
72160   rc = vdbeSorterSort(pCsr);
72161
72162   /* If the first temporary PMA file has not been opened, open it now. */
72163   if( rc==SQLCIPHER_OK && pSorter->pTemp1==0 ){
72164     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
72165     assert( rc!=SQLCIPHER_OK || pSorter->pTemp1 );
72166     assert( pSorter->iWriteOff==0 );
72167     assert( pSorter->nPMA==0 );
72168   }
72169
72170   if( rc==SQLCIPHER_OK ){
72171     i64 iOff = pSorter->iWriteOff;
72172     SorterRecord *p;
72173     SorterRecord *pNext = 0;
72174     static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
72175
72176     pSorter->nPMA++;
72177     rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
72178     for(p=pSorter->pRecord; rc==SQLCIPHER_OK && p; p=pNext){
72179       pNext = p->pNext;
72180       rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
72181
72182       if( rc==SQLCIPHER_OK ){
72183         rc = sqlcipher3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
72184         iOff += p->nVal;
72185       }
72186
72187       sqlcipher3DbFree(db, p);
72188     }
72189
72190     /* This assert verifies that unless an error has occurred, the size of 
72191     ** the PMA on disk is the same as the expected size stored in
72192     ** pSorter->nInMemory. */ 
72193     assert( rc!=SQLCIPHER_OK || pSorter->nInMemory==(
72194           iOff-pSorter->iWriteOff-sqlcipher3VarintLen(pSorter->nInMemory)
72195     ));
72196
72197     pSorter->iWriteOff = iOff;
72198     if( rc==SQLCIPHER_OK ){
72199       /* Terminate each file with 8 extra bytes so that from any offset
72200       ** in the file we can always read 9 bytes without a SHORT_READ error */
72201       rc = sqlcipher3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
72202     }
72203     pSorter->pRecord = p;
72204   }
72205
72206   return rc;
72207 }
72208
72209 /*
72210 ** Add a record to the sorter.
72211 */
72212 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterWrite(
72213   sqlcipher3 *db,                    /* Database handle */
72214   VdbeCursor *pCsr,               /* Sorter cursor */
72215   Mem *pVal                       /* Memory cell containing record */
72216 ){
72217   VdbeSorter *pSorter = pCsr->pSorter;
72218   int rc = SQLCIPHER_OK;             /* Return Code */
72219   SorterRecord *pNew;             /* New list element */
72220
72221   assert( pSorter );
72222   pSorter->nInMemory += sqlcipher3VarintLen(pVal->n) + pVal->n;
72223
72224   pNew = (SorterRecord *)sqlcipher3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
72225   if( pNew==0 ){
72226     rc = SQLCIPHER_NOMEM;
72227   }else{
72228     pNew->pVal = (void *)&pNew[1];
72229     memcpy(pNew->pVal, pVal->z, pVal->n);
72230     pNew->nVal = pVal->n;
72231     pNew->pNext = pSorter->pRecord;
72232     pSorter->pRecord = pNew;
72233   }
72234
72235   /* See if the contents of the sorter should now be written out. They
72236   ** are written out when either of the following are true:
72237   **
72238   **   * The total memory allocated for the in-memory list is greater 
72239   **     than (page-size * cache-size), or
72240   **
72241   **   * The total memory allocated for the in-memory list is greater 
72242   **     than (page-size * 10) and sqlcipher3HeapNearlyFull() returns true.
72243   */
72244   if( rc==SQLCIPHER_OK && pSorter->mxPmaSize>0 && (
72245         (pSorter->nInMemory>pSorter->mxPmaSize)
72246      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlcipher3HeapNearlyFull())
72247   )){
72248     rc = vdbeSorterListToPMA(db, pCsr);
72249     pSorter->nInMemory = 0;
72250   }
72251
72252   return rc;
72253 }
72254
72255 /*
72256 ** Helper function for sqlcipher3VdbeSorterRewind(). 
72257 */
72258 static int vdbeSorterInitMerge(
72259   sqlcipher3 *db,                    /* Database handle */
72260   VdbeCursor *pCsr,               /* Cursor handle for this sorter */
72261   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
72262 ){
72263   VdbeSorter *pSorter = pCsr->pSorter;
72264   int rc = SQLCIPHER_OK;             /* Return code */
72265   int i;                          /* Used to iterator through aIter[] */
72266   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
72267
72268   /* Initialize the iterators. */
72269   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
72270     VdbeSorterIter *pIter = &pSorter->aIter[i];
72271     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
72272     pSorter->iReadOff = pIter->iEof;
72273     assert( rc!=SQLCIPHER_OK || pSorter->iReadOff<=pSorter->iWriteOff );
72274     if( rc!=SQLCIPHER_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
72275   }
72276
72277   /* Initialize the aTree[] array. */
72278   for(i=pSorter->nTree-1; rc==SQLCIPHER_OK && i>0; i--){
72279     rc = vdbeSorterDoCompare(pCsr, i);
72280   }
72281
72282   *pnByte = nByte;
72283   return rc;
72284 }
72285
72286 /*
72287 ** Once the sorter has been populated, this function is called to prepare
72288 ** for iterating through its contents in sorted order.
72289 */
72290 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRewind(sqlcipher3 *db, VdbeCursor *pCsr, int *pbEof){
72291   VdbeSorter *pSorter = pCsr->pSorter;
72292   int rc;                         /* Return code */
72293   sqlcipher3_file *pTemp2 = 0;       /* Second temp file to use */
72294   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
72295   int nIter;                      /* Number of iterators used */
72296   int nByte;                      /* Bytes of space required for aIter/aTree */
72297   int N = 2;                      /* Power of 2 >= nIter */
72298
72299   assert( pSorter );
72300
72301   /* If no data has been written to disk, then do not do so now. Instead,
72302   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
72303   ** from the in-memory list.  */
72304   if( pSorter->nPMA==0 ){
72305     *pbEof = !pSorter->pRecord;
72306     assert( pSorter->aTree==0 );
72307     return vdbeSorterSort(pCsr);
72308   }
72309
72310   /* Write the current b-tree to a PMA. Close the b-tree cursor. */
72311   rc = vdbeSorterListToPMA(db, pCsr);
72312   if( rc!=SQLCIPHER_OK ) return rc;
72313
72314   /* Allocate space for aIter[] and aTree[]. */
72315   nIter = pSorter->nPMA;
72316   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
72317   assert( nIter>0 );
72318   while( N<nIter ) N += N;
72319   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
72320   pSorter->aIter = (VdbeSorterIter *)sqlcipher3DbMallocZero(db, nByte);
72321   if( !pSorter->aIter ) return SQLCIPHER_NOMEM;
72322   pSorter->aTree = (int *)&pSorter->aIter[N];
72323   pSorter->nTree = N;
72324
72325   do {
72326     int iNew;                     /* Index of new, merged, PMA */
72327
72328     for(iNew=0; 
72329         rc==SQLCIPHER_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
72330         iNew++
72331     ){
72332       i64 nWrite;                 /* Number of bytes in new PMA */
72333
72334       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
72335       ** initialize an iterator for each of them and break out of the loop.
72336       ** These iterators will be incrementally merged as the VDBE layer calls
72337       ** sqlcipher3VdbeSorterNext().
72338       **
72339       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
72340       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
72341       ** are merged into a single PMA that is written to file pTemp2.
72342       */
72343       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
72344       assert( rc!=SQLCIPHER_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
72345       if( rc!=SQLCIPHER_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72346         break;
72347       }
72348
72349       /* Open the second temp file, if it is not already open. */
72350       if( pTemp2==0 ){
72351         assert( iWrite2==0 );
72352         rc = vdbeSorterOpenTempFile(db, &pTemp2);
72353       }
72354
72355       if( rc==SQLCIPHER_OK ){
72356         rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
72357       }
72358
72359       if( rc==SQLCIPHER_OK ){
72360         int bEof = 0;
72361         while( rc==SQLCIPHER_OK && bEof==0 ){
72362           int nToWrite;
72363           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72364           assert( pIter->pFile );
72365           nToWrite = pIter->nKey + sqlcipher3VarintLen(pIter->nKey);
72366           rc = sqlcipher3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
72367           iWrite2 += nToWrite;
72368           if( rc==SQLCIPHER_OK ){
72369             rc = sqlcipher3VdbeSorterNext(db, pCsr, &bEof);
72370           }
72371         }
72372       }
72373     }
72374
72375     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72376       break;
72377     }else{
72378       sqlcipher3_file *pTmp = pSorter->pTemp1;
72379       pSorter->nPMA = iNew;
72380       pSorter->pTemp1 = pTemp2;
72381       pTemp2 = pTmp;
72382       pSorter->iWriteOff = iWrite2;
72383       pSorter->iReadOff = 0;
72384       iWrite2 = 0;
72385     }
72386   }while( rc==SQLCIPHER_OK );
72387
72388   if( pTemp2 ){
72389     sqlcipher3OsCloseFree(pTemp2);
72390   }
72391   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72392   return rc;
72393 }
72394
72395 /*
72396 ** Advance to the next element in the sorter.
72397 */
72398 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterNext(sqlcipher3 *db, VdbeCursor *pCsr, int *pbEof){
72399   VdbeSorter *pSorter = pCsr->pSorter;
72400   int rc;                         /* Return code */
72401
72402   if( pSorter->aTree ){
72403     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
72404     int i;                        /* Index of aTree[] to recalculate */
72405
72406     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
72407     for(i=(pSorter->nTree+iPrev)/2; rc==SQLCIPHER_OK && i>0; i=i/2){
72408       rc = vdbeSorterDoCompare(pCsr, i);
72409     }
72410
72411     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72412   }else{
72413     SorterRecord *pFree = pSorter->pRecord;
72414     pSorter->pRecord = pFree->pNext;
72415     pFree->pNext = 0;
72416     vdbeSorterRecordFree(db, pFree);
72417     *pbEof = !pSorter->pRecord;
72418     rc = SQLCIPHER_OK;
72419   }
72420   return rc;
72421 }
72422
72423 /*
72424 ** Return a pointer to a buffer owned by the sorter that contains the 
72425 ** current key.
72426 */
72427 static void *vdbeSorterRowkey(
72428   VdbeSorter *pSorter,            /* Sorter object */
72429   int *pnKey                      /* OUT: Size of current key in bytes */
72430 ){
72431   void *pKey;
72432   if( pSorter->aTree ){
72433     VdbeSorterIter *pIter;
72434     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72435     *pnKey = pIter->nKey;
72436     pKey = pIter->aKey;
72437   }else{
72438     *pnKey = pSorter->pRecord->nVal;
72439     pKey = pSorter->pRecord->pVal;
72440   }
72441   return pKey;
72442 }
72443
72444 /*
72445 ** Copy the current sorter key into the memory cell pOut.
72446 */
72447 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
72448   VdbeSorter *pSorter = pCsr->pSorter;
72449   void *pKey; int nKey;           /* Sorter key to copy into pOut */
72450
72451   pKey = vdbeSorterRowkey(pSorter, &nKey);
72452   if( sqlcipher3VdbeMemGrow(pOut, nKey, 0) ){
72453     return SQLCIPHER_NOMEM;
72454   }
72455   pOut->n = nKey;
72456   MemSetTypeFlag(pOut, MEM_Blob);
72457   memcpy(pOut->z, pKey, nKey);
72458
72459   return SQLCIPHER_OK;
72460 }
72461
72462 /*
72463 ** Compare the key in memory cell pVal with the key that the sorter cursor
72464 ** passed as the first argument currently points to. For the purposes of
72465 ** the comparison, ignore the rowid field at the end of each record.
72466 **
72467 ** If an error occurs, return an SQLite error code (i.e. SQLCIPHER_NOMEM).
72468 ** Otherwise, set *pRes to a negative, zero or positive value if the
72469 ** key in pVal is smaller than, equal to or larger than the current sorter
72470 ** key.
72471 */
72472 SQLCIPHER_PRIVATE int sqlcipher3VdbeSorterCompare(
72473   VdbeCursor *pCsr,               /* Sorter cursor */
72474   Mem *pVal,                      /* Value to compare to current sorter key */
72475   int *pRes                       /* OUT: Result of comparison */
72476 ){
72477   VdbeSorter *pSorter = pCsr->pSorter;
72478   void *pKey; int nKey;           /* Sorter key to compare pVal with */
72479
72480   pKey = vdbeSorterRowkey(pSorter, &nKey);
72481   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
72482   return SQLCIPHER_OK;
72483 }
72484
72485 #endif /* #ifndef SQLCIPHER_OMIT_MERGE_SORT */
72486
72487 /************** End of vdbesort.c ********************************************/
72488 /************** Begin file journal.c *****************************************/
72489 /*
72490 ** 2007 August 22
72491 **
72492 ** The author disclaims copyright to this source code.  In place of
72493 ** a legal notice, here is a blessing:
72494 **
72495 **    May you do good and not evil.
72496 **    May you find forgiveness for yourself and forgive others.
72497 **    May you share freely, never taking more than you give.
72498 **
72499 *************************************************************************
72500 **
72501 ** This file implements a special kind of sqlcipher3_file object used
72502 ** by SQLite to create journal files if the atomic-write optimization
72503 ** is enabled.
72504 **
72505 ** The distinctive characteristic of this sqlcipher3_file is that the
72506 ** actual on disk file is created lazily. When the file is created,
72507 ** the caller specifies a buffer size for an in-memory buffer to
72508 ** be used to service read() and write() requests. The actual file
72509 ** on disk is not created or populated until either:
72510 **
72511 **   1) The in-memory representation grows too large for the allocated 
72512 **      buffer, or
72513 **   2) The sqlcipher3JournalCreate() function is called.
72514 */
72515 #ifdef SQLCIPHER_ENABLE_ATOMIC_WRITE
72516
72517
72518 /*
72519 ** A JournalFile object is a subclass of sqlcipher3_file used by
72520 ** as an open file handle for journal files.
72521 */
72522 struct JournalFile {
72523   sqlcipher3_io_methods *pMethod;    /* I/O methods on journal files */
72524   int nBuf;                       /* Size of zBuf[] in bytes */
72525   char *zBuf;                     /* Space to buffer journal writes */
72526   int iSize;                      /* Amount of zBuf[] currently used */
72527   int flags;                      /* xOpen flags */
72528   sqlcipher3_vfs *pVfs;              /* The "real" underlying VFS */
72529   sqlcipher3_file *pReal;            /* The "real" underlying file descriptor */
72530   const char *zJournal;           /* Name of the journal file */
72531 };
72532 typedef struct JournalFile JournalFile;
72533
72534 /*
72535 ** If it does not already exists, create and populate the on-disk file 
72536 ** for JournalFile p.
72537 */
72538 static int createFile(JournalFile *p){
72539   int rc = SQLCIPHER_OK;
72540   if( !p->pReal ){
72541     sqlcipher3_file *pReal = (sqlcipher3_file *)&p[1];
72542     rc = sqlcipher3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
72543     if( rc==SQLCIPHER_OK ){
72544       p->pReal = pReal;
72545       if( p->iSize>0 ){
72546         assert(p->iSize<=p->nBuf);
72547         rc = sqlcipher3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
72548       }
72549     }
72550   }
72551   return rc;
72552 }
72553
72554 /*
72555 ** Close the file.
72556 */
72557 static int jrnlClose(sqlcipher3_file *pJfd){
72558   JournalFile *p = (JournalFile *)pJfd;
72559   if( p->pReal ){
72560     sqlcipher3OsClose(p->pReal);
72561   }
72562   sqlcipher3_free(p->zBuf);
72563   return SQLCIPHER_OK;
72564 }
72565
72566 /*
72567 ** Read data from the file.
72568 */
72569 static int jrnlRead(
72570   sqlcipher3_file *pJfd,    /* The journal file from which to read */
72571   void *zBuf,            /* Put the results here */
72572   int iAmt,              /* Number of bytes to read */
72573   sqlcipher_int64 iOfst     /* Begin reading at this offset */
72574 ){
72575   int rc = SQLCIPHER_OK;
72576   JournalFile *p = (JournalFile *)pJfd;
72577   if( p->pReal ){
72578     rc = sqlcipher3OsRead(p->pReal, zBuf, iAmt, iOfst);
72579   }else if( (iAmt+iOfst)>p->iSize ){
72580     rc = SQLCIPHER_IOERR_SHORT_READ;
72581   }else{
72582     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
72583   }
72584   return rc;
72585 }
72586
72587 /*
72588 ** Write data to the file.
72589 */
72590 static int jrnlWrite(
72591   sqlcipher3_file *pJfd,    /* The journal file into which to write */
72592   const void *zBuf,      /* Take data to be written from here */
72593   int iAmt,              /* Number of bytes to write */
72594   sqlcipher_int64 iOfst     /* Begin writing at this offset into the file */
72595 ){
72596   int rc = SQLCIPHER_OK;
72597   JournalFile *p = (JournalFile *)pJfd;
72598   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
72599     rc = createFile(p);
72600   }
72601   if( rc==SQLCIPHER_OK ){
72602     if( p->pReal ){
72603       rc = sqlcipher3OsWrite(p->pReal, zBuf, iAmt, iOfst);
72604     }else{
72605       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
72606       if( p->iSize<(iOfst+iAmt) ){
72607         p->iSize = (iOfst+iAmt);
72608       }
72609     }
72610   }
72611   return rc;
72612 }
72613
72614 /*
72615 ** Truncate the file.
72616 */
72617 static int jrnlTruncate(sqlcipher3_file *pJfd, sqlcipher_int64 size){
72618   int rc = SQLCIPHER_OK;
72619   JournalFile *p = (JournalFile *)pJfd;
72620   if( p->pReal ){
72621     rc = sqlcipher3OsTruncate(p->pReal, size);
72622   }else if( size<p->iSize ){
72623     p->iSize = size;
72624   }
72625   return rc;
72626 }
72627
72628 /*
72629 ** Sync the file.
72630 */
72631 static int jrnlSync(sqlcipher3_file *pJfd, int flags){
72632   int rc;
72633   JournalFile *p = (JournalFile *)pJfd;
72634   if( p->pReal ){
72635     rc = sqlcipher3OsSync(p->pReal, flags);
72636   }else{
72637     rc = SQLCIPHER_OK;
72638   }
72639   return rc;
72640 }
72641
72642 /*
72643 ** Query the size of the file in bytes.
72644 */
72645 static int jrnlFileSize(sqlcipher3_file *pJfd, sqlcipher_int64 *pSize){
72646   int rc = SQLCIPHER_OK;
72647   JournalFile *p = (JournalFile *)pJfd;
72648   if( p->pReal ){
72649     rc = sqlcipher3OsFileSize(p->pReal, pSize);
72650   }else{
72651     *pSize = (sqlcipher_int64) p->iSize;
72652   }
72653   return rc;
72654 }
72655
72656 /*
72657 ** Table of methods for JournalFile sqlcipher3_file object.
72658 */
72659 static struct sqlcipher3_io_methods JournalFileMethods = {
72660   1,             /* iVersion */
72661   jrnlClose,     /* xClose */
72662   jrnlRead,      /* xRead */
72663   jrnlWrite,     /* xWrite */
72664   jrnlTruncate,  /* xTruncate */
72665   jrnlSync,      /* xSync */
72666   jrnlFileSize,  /* xFileSize */
72667   0,             /* xLock */
72668   0,             /* xUnlock */
72669   0,             /* xCheckReservedLock */
72670   0,             /* xFileControl */
72671   0,             /* xSectorSize */
72672   0,             /* xDeviceCharacteristics */
72673   0,             /* xShmMap */
72674   0,             /* xShmLock */
72675   0,             /* xShmBarrier */
72676   0              /* xShmUnmap */
72677 };
72678
72679 /* 
72680 ** Open a journal file.
72681 */
72682 SQLCIPHER_PRIVATE int sqlcipher3JournalOpen(
72683   sqlcipher3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72684   const char *zName,         /* Name of the journal file */
72685   sqlcipher3_file *pJfd,        /* Preallocated, blank file handle */
72686   int flags,                 /* Opening flags */
72687   int nBuf                   /* Bytes buffered before opening the file */
72688 ){
72689   JournalFile *p = (JournalFile *)pJfd;
72690   memset(p, 0, sqlcipher3JournalSize(pVfs));
72691   if( nBuf>0 ){
72692     p->zBuf = sqlcipher3MallocZero(nBuf);
72693     if( !p->zBuf ){
72694       return SQLCIPHER_NOMEM;
72695     }
72696   }else{
72697     return sqlcipher3OsOpen(pVfs, zName, pJfd, flags, 0);
72698   }
72699   p->pMethod = &JournalFileMethods;
72700   p->nBuf = nBuf;
72701   p->flags = flags;
72702   p->zJournal = zName;
72703   p->pVfs = pVfs;
72704   return SQLCIPHER_OK;
72705 }
72706
72707 /*
72708 ** If the argument p points to a JournalFile structure, and the underlying
72709 ** file has not yet been created, create it now.
72710 */
72711 SQLCIPHER_PRIVATE int sqlcipher3JournalCreate(sqlcipher3_file *p){
72712   if( p->pMethods!=&JournalFileMethods ){
72713     return SQLCIPHER_OK;
72714   }
72715   return createFile((JournalFile *)p);
72716 }
72717
72718 /* 
72719 ** Return the number of bytes required to store a JournalFile that uses vfs
72720 ** pVfs to create the underlying on-disk files.
72721 */
72722 SQLCIPHER_PRIVATE int sqlcipher3JournalSize(sqlcipher3_vfs *pVfs){
72723   return (pVfs->szOsFile+sizeof(JournalFile));
72724 }
72725 #endif
72726
72727 /************** End of journal.c *********************************************/
72728 /************** Begin file memjournal.c **************************************/
72729 /*
72730 ** 2008 October 7
72731 **
72732 ** The author disclaims copyright to this source code.  In place of
72733 ** a legal notice, here is a blessing:
72734 **
72735 **    May you do good and not evil.
72736 **    May you find forgiveness for yourself and forgive others.
72737 **    May you share freely, never taking more than you give.
72738 **
72739 *************************************************************************
72740 **
72741 ** This file contains code use to implement an in-memory rollback journal.
72742 ** The in-memory rollback journal is used to journal transactions for
72743 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72744 */
72745
72746 /* Forward references to internal structures */
72747 typedef struct MemJournal MemJournal;
72748 typedef struct FilePoint FilePoint;
72749 typedef struct FileChunk FileChunk;
72750
72751 /* Space to hold the rollback journal is allocated in increments of
72752 ** this many bytes.
72753 **
72754 ** The size chosen is a little less than a power of two.  That way,
72755 ** the FileChunk object will have a size that almost exactly fills
72756 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72757 ** memory allocators.
72758 */
72759 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72760
72761 /* Macro to find the minimum of two numeric values.
72762 */
72763 #ifndef MIN
72764 # define MIN(x,y) ((x)<(y)?(x):(y))
72765 #endif
72766
72767 /*
72768 ** The rollback journal is composed of a linked list of these structures.
72769 */
72770 struct FileChunk {
72771   FileChunk *pNext;               /* Next chunk in the journal */
72772   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72773 };
72774
72775 /*
72776 ** An instance of this object serves as a cursor into the rollback journal.
72777 ** The cursor can be either for reading or writing.
72778 */
72779 struct FilePoint {
72780   sqlcipher3_int64 iOffset;          /* Offset from the beginning of the file */
72781   FileChunk *pChunk;              /* Specific chunk into which cursor points */
72782 };
72783
72784 /*
72785 ** This subclass is a subclass of sqlcipher3_file.  Each open memory-journal
72786 ** is an instance of this class.
72787 */
72788 struct MemJournal {
72789   sqlcipher3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72790   FileChunk *pFirst;              /* Head of in-memory chunk-list */
72791   FilePoint endpoint;             /* Pointer to the end of the file */
72792   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72793 };
72794
72795 /*
72796 ** Read data from the in-memory journal file.  This is the implementation
72797 ** of the sqlcipher3_vfs.xRead method.
72798 */
72799 static int memjrnlRead(
72800   sqlcipher3_file *pJfd,    /* The journal file from which to read */
72801   void *zBuf,            /* Put the results here */
72802   int iAmt,              /* Number of bytes to read */
72803   sqlcipher_int64 iOfst     /* Begin reading at this offset */
72804 ){
72805   MemJournal *p = (MemJournal *)pJfd;
72806   u8 *zOut = zBuf;
72807   int nRead = iAmt;
72808   int iChunkOffset;
72809   FileChunk *pChunk;
72810
72811   /* SQLite never tries to read past the end of a rollback journal file */
72812   assert( iOfst+iAmt<=p->endpoint.iOffset );
72813
72814   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72815     sqlcipher3_int64 iOff = 0;
72816     for(pChunk=p->pFirst; 
72817         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72818         pChunk=pChunk->pNext
72819     ){
72820       iOff += JOURNAL_CHUNKSIZE;
72821     }
72822   }else{
72823     pChunk = p->readpoint.pChunk;
72824   }
72825
72826   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72827   do {
72828     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72829     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72830     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72831     zOut += nCopy;
72832     nRead -= iSpace;
72833     iChunkOffset = 0;
72834   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72835   p->readpoint.iOffset = iOfst+iAmt;
72836   p->readpoint.pChunk = pChunk;
72837
72838   return SQLCIPHER_OK;
72839 }
72840
72841 /*
72842 ** Write data to the file.
72843 */
72844 static int memjrnlWrite(
72845   sqlcipher3_file *pJfd,    /* The journal file into which to write */
72846   const void *zBuf,      /* Take data to be written from here */
72847   int iAmt,              /* Number of bytes to write */
72848   sqlcipher_int64 iOfst     /* Begin writing at this offset into the file */
72849 ){
72850   MemJournal *p = (MemJournal *)pJfd;
72851   int nWrite = iAmt;
72852   u8 *zWrite = (u8 *)zBuf;
72853
72854   /* An in-memory journal file should only ever be appended to. Random
72855   ** access writes are not required by sqlcipher.
72856   */
72857   assert( iOfst==p->endpoint.iOffset );
72858   UNUSED_PARAMETER(iOfst);
72859
72860   while( nWrite>0 ){
72861     FileChunk *pChunk = p->endpoint.pChunk;
72862     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72863     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72864
72865     if( iChunkOffset==0 ){
72866       /* New chunk is required to extend the file. */
72867       FileChunk *pNew = sqlcipher3_malloc(sizeof(FileChunk));
72868       if( !pNew ){
72869         return SQLCIPHER_IOERR_NOMEM;
72870       }
72871       pNew->pNext = 0;
72872       if( pChunk ){
72873         assert( p->pFirst );
72874         pChunk->pNext = pNew;
72875       }else{
72876         assert( !p->pFirst );
72877         p->pFirst = pNew;
72878       }
72879       p->endpoint.pChunk = pNew;
72880     }
72881
72882     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72883     zWrite += iSpace;
72884     nWrite -= iSpace;
72885     p->endpoint.iOffset += iSpace;
72886   }
72887
72888   return SQLCIPHER_OK;
72889 }
72890
72891 /*
72892 ** Truncate the file.
72893 */
72894 static int memjrnlTruncate(sqlcipher3_file *pJfd, sqlcipher_int64 size){
72895   MemJournal *p = (MemJournal *)pJfd;
72896   FileChunk *pChunk;
72897   assert(size==0);
72898   UNUSED_PARAMETER(size);
72899   pChunk = p->pFirst;
72900   while( pChunk ){
72901     FileChunk *pTmp = pChunk;
72902     pChunk = pChunk->pNext;
72903     sqlcipher3_free(pTmp);
72904   }
72905   sqlcipher3MemJournalOpen(pJfd);
72906   return SQLCIPHER_OK;
72907 }
72908
72909 /*
72910 ** Close the file.
72911 */
72912 static int memjrnlClose(sqlcipher3_file *pJfd){
72913   memjrnlTruncate(pJfd, 0);
72914   return SQLCIPHER_OK;
72915 }
72916
72917
72918 /*
72919 ** Sync the file.
72920 **
72921 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72922 ** is never called in a working implementation.  This implementation
72923 ** exists purely as a contingency, in case some malfunction in some other
72924 ** part of SQLite causes Sync to be called by mistake.
72925 */
72926 static int memjrnlSync(sqlcipher3_file *NotUsed, int NotUsed2){
72927   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72928   return SQLCIPHER_OK;
72929 }
72930
72931 /*
72932 ** Query the size of the file in bytes.
72933 */
72934 static int memjrnlFileSize(sqlcipher3_file *pJfd, sqlcipher_int64 *pSize){
72935   MemJournal *p = (MemJournal *)pJfd;
72936   *pSize = (sqlcipher_int64) p->endpoint.iOffset;
72937   return SQLCIPHER_OK;
72938 }
72939
72940 /*
72941 ** Table of methods for MemJournal sqlcipher3_file object.
72942 */
72943 static const struct sqlcipher3_io_methods MemJournalMethods = {
72944   1,                /* iVersion */
72945   memjrnlClose,     /* xClose */
72946   memjrnlRead,      /* xRead */
72947   memjrnlWrite,     /* xWrite */
72948   memjrnlTruncate,  /* xTruncate */
72949   memjrnlSync,      /* xSync */
72950   memjrnlFileSize,  /* xFileSize */
72951   0,                /* xLock */
72952   0,                /* xUnlock */
72953   0,                /* xCheckReservedLock */
72954   0,                /* xFileControl */
72955   0,                /* xSectorSize */
72956   0,                /* xDeviceCharacteristics */
72957   0,                /* xShmMap */
72958   0,                /* xShmLock */
72959   0,                /* xShmBarrier */
72960   0                 /* xShmUnlock */
72961 };
72962
72963 /* 
72964 ** Open a journal file.
72965 */
72966 SQLCIPHER_PRIVATE void sqlcipher3MemJournalOpen(sqlcipher3_file *pJfd){
72967   MemJournal *p = (MemJournal *)pJfd;
72968   assert( EIGHT_BYTE_ALIGNMENT(p) );
72969   memset(p, 0, sqlcipher3MemJournalSize());
72970   p->pMethod = (sqlcipher3_io_methods*)&MemJournalMethods;
72971 }
72972
72973 /*
72974 ** Return true if the file-handle passed as an argument is 
72975 ** an in-memory journal 
72976 */
72977 SQLCIPHER_PRIVATE int sqlcipher3IsMemJournal(sqlcipher3_file *pJfd){
72978   return pJfd->pMethods==&MemJournalMethods;
72979 }
72980
72981 /* 
72982 ** Return the number of bytes required to store a MemJournal file descriptor.
72983 */
72984 SQLCIPHER_PRIVATE int sqlcipher3MemJournalSize(void){
72985   return sizeof(MemJournal);
72986 }
72987
72988 /************** End of memjournal.c ******************************************/
72989 /************** Begin file walker.c ******************************************/
72990 /*
72991 ** 2008 August 16
72992 **
72993 ** The author disclaims copyright to this source code.  In place of
72994 ** a legal notice, here is a blessing:
72995 **
72996 **    May you do good and not evil.
72997 **    May you find forgiveness for yourself and forgive others.
72998 **    May you share freely, never taking more than you give.
72999 **
73000 *************************************************************************
73001 ** This file contains routines used for walking the parser tree for
73002 ** an SQL statement.
73003 */
73004 /* #include <stdlib.h> */
73005 /* #include <string.h> */
73006
73007
73008 /*
73009 ** Walk an expression tree.  Invoke the callback once for each node
73010 ** of the expression, while decending.  (In other words, the callback
73011 ** is invoked before visiting children.)
73012 **
73013 ** The return value from the callback should be one of the WRC_*
73014 ** constants to specify how to proceed with the walk.
73015 **
73016 **    WRC_Continue      Continue descending down the tree.
73017 **
73018 **    WRC_Prune         Do not descend into child nodes.  But allow
73019 **                      the walk to continue with sibling nodes.
73020 **
73021 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
73022 **                      return the top-level walk call.
73023 **
73024 ** The return value from this routine is WRC_Abort to abandon the tree walk
73025 ** and WRC_Continue to continue.
73026 */
73027 SQLCIPHER_PRIVATE int sqlcipher3WalkExpr(Walker *pWalker, Expr *pExpr){
73028   int rc;
73029   if( pExpr==0 ) return WRC_Continue;
73030   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73031   testcase( ExprHasProperty(pExpr, EP_Reduced) );
73032   rc = pWalker->xExprCallback(pWalker, pExpr);
73033   if( rc==WRC_Continue
73034               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73035     if( sqlcipher3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73036     if( sqlcipher3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73037     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73038       if( sqlcipher3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73039     }else{
73040       if( sqlcipher3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73041     }
73042   }
73043   return rc & WRC_Abort;
73044 }
73045
73046 /*
73047 ** Call sqlcipher3WalkExpr() for every expression in list p or until
73048 ** an abort request is seen.
73049 */
73050 SQLCIPHER_PRIVATE int sqlcipher3WalkExprList(Walker *pWalker, ExprList *p){
73051   int i;
73052   struct ExprList_item *pItem;
73053   if( p ){
73054     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73055       if( sqlcipher3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73056     }
73057   }
73058   return WRC_Continue;
73059 }
73060
73061 /*
73062 ** Walk all expressions associated with SELECT statement p.  Do
73063 ** not invoke the SELECT callback on p, but do (of course) invoke
73064 ** any expr callbacks and SELECT callbacks that come from subqueries.
73065 ** Return WRC_Abort or WRC_Continue.
73066 */
73067 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectExpr(Walker *pWalker, Select *p){
73068   if( sqlcipher3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73069   if( sqlcipher3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73070   if( sqlcipher3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73071   if( sqlcipher3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73072   if( sqlcipher3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73073   if( sqlcipher3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73074   if( sqlcipher3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73075   return WRC_Continue;
73076 }
73077
73078 /*
73079 ** Walk the parse trees associated with all subqueries in the
73080 ** FROM clause of SELECT statement p.  Do not invoke the select
73081 ** callback on p, but do invoke it on each FROM clause subquery
73082 ** and on any subqueries further down in the tree.  Return 
73083 ** WRC_Abort or WRC_Continue;
73084 */
73085 SQLCIPHER_PRIVATE int sqlcipher3WalkSelectFrom(Walker *pWalker, Select *p){
73086   SrcList *pSrc;
73087   int i;
73088   struct SrcList_item *pItem;
73089
73090   pSrc = p->pSrc;
73091   if( ALWAYS(pSrc) ){
73092     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73093       if( sqlcipher3WalkSelect(pWalker, pItem->pSelect) ){
73094         return WRC_Abort;
73095       }
73096     }
73097   }
73098   return WRC_Continue;
73099
73100
73101 /*
73102 ** Call sqlcipher3WalkExpr() for every expression in Select statement p.
73103 ** Invoke sqlcipher3WalkSelect() for subqueries in the FROM clause and
73104 ** on the compound select chain, p->pPrior.
73105 **
73106 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
73107 ** there is an abort request.
73108 **
73109 ** If the Walker does not have an xSelectCallback() then this routine
73110 ** is a no-op returning WRC_Continue.
73111 */
73112 SQLCIPHER_PRIVATE int sqlcipher3WalkSelect(Walker *pWalker, Select *p){
73113   int rc;
73114   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
73115   rc = WRC_Continue;
73116   while( p  ){
73117     rc = pWalker->xSelectCallback(pWalker, p);
73118     if( rc ) break;
73119     if( sqlcipher3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
73120     if( sqlcipher3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
73121     p = p->pPrior;
73122   }
73123   return rc & WRC_Abort;
73124 }
73125
73126 /************** End of walker.c **********************************************/
73127 /************** Begin file resolve.c *****************************************/
73128 /*
73129 ** 2008 August 18
73130 **
73131 ** The author disclaims copyright to this source code.  In place of
73132 ** a legal notice, here is a blessing:
73133 **
73134 **    May you do good and not evil.
73135 **    May you find forgiveness for yourself and forgive others.
73136 **    May you share freely, never taking more than you give.
73137 **
73138 *************************************************************************
73139 **
73140 ** This file contains routines used for walking the parser tree and
73141 ** resolve all identifiers by associating them with a particular
73142 ** table and column.
73143 */
73144 /* #include <stdlib.h> */
73145 /* #include <string.h> */
73146
73147 /*
73148 ** Turn the pExpr expression into an alias for the iCol-th column of the
73149 ** result set in pEList.
73150 **
73151 ** If the result set column is a simple column reference, then this routine
73152 ** makes an exact copy.  But for any other kind of expression, this
73153 ** routine make a copy of the result set column as the argument to the
73154 ** TK_AS operator.  The TK_AS operator causes the expression to be
73155 ** evaluated just once and then reused for each alias.
73156 **
73157 ** The reason for suppressing the TK_AS term when the expression is a simple
73158 ** column reference is so that the column reference will be recognized as
73159 ** usable by indices within the WHERE clause processing logic. 
73160 **
73161 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
73162 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
73163 **
73164 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
73165 **
73166 ** Is equivalent to:
73167 **
73168 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
73169 **
73170 ** The result of random()%5 in the GROUP BY clause is probably different
73171 ** from the result in the result-set.  We might fix this someday.  Or
73172 ** then again, we might not...
73173 */
73174 static void resolveAlias(
73175   Parse *pParse,         /* Parsing context */
73176   ExprList *pEList,      /* A result set */
73177   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
73178   Expr *pExpr,           /* Transform this into an alias to the result set */
73179   const char *zType      /* "GROUP" or "ORDER" or "" */
73180 ){
73181   Expr *pOrig;           /* The iCol-th column of the result set */
73182   Expr *pDup;            /* Copy of pOrig */
73183   sqlcipher3 *db;           /* The database connection */
73184
73185   assert( iCol>=0 && iCol<pEList->nExpr );
73186   pOrig = pEList->a[iCol].pExpr;
73187   assert( pOrig!=0 );
73188   assert( pOrig->flags & EP_Resolved );
73189   db = pParse->db;
73190   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
73191     pDup = sqlcipher3ExprDup(db, pOrig, 0);
73192     pDup = sqlcipher3PExpr(pParse, TK_AS, pDup, 0, 0);
73193     if( pDup==0 ) return;
73194     if( pEList->a[iCol].iAlias==0 ){
73195       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
73196     }
73197     pDup->iTable = pEList->a[iCol].iAlias;
73198   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
73199     pDup = sqlcipher3ExprDup(db, pOrig, 0);
73200     if( pDup==0 ) return;
73201   }else{
73202     char *zToken = pOrig->u.zToken;
73203     assert( zToken!=0 );
73204     pOrig->u.zToken = 0;
73205     pDup = sqlcipher3ExprDup(db, pOrig, 0);
73206     pOrig->u.zToken = zToken;
73207     if( pDup==0 ) return;
73208     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
73209     pDup->flags2 |= EP2_MallocedToken;
73210     pDup->u.zToken = sqlcipher3DbStrDup(db, zToken);
73211   }
73212   if( pExpr->flags & EP_ExpCollate ){
73213     pDup->pColl = pExpr->pColl;
73214     pDup->flags |= EP_ExpCollate;
73215   }
73216
73217   /* Before calling sqlcipher3ExprDelete(), set the EP_Static flag. This 
73218   ** prevents ExprDelete() from deleting the Expr structure itself,
73219   ** allowing it to be repopulated by the memcpy() on the following line.
73220   */
73221   ExprSetProperty(pExpr, EP_Static);
73222   sqlcipher3ExprDelete(db, pExpr);
73223   memcpy(pExpr, pDup, sizeof(*pExpr));
73224   sqlcipher3DbFree(db, pDup);
73225 }
73226
73227
73228 /*
73229 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
73230 **
73231 ** Return FALSE if the USING clause is NULL or if it does not contain
73232 ** zCol.
73233 */
73234 static int nameInUsingClause(IdList *pUsing, const char *zCol){
73235   if( pUsing ){
73236     int k;
73237     for(k=0; k<pUsing->nId; k++){
73238       if( sqlcipher3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
73239     }
73240   }
73241   return 0;
73242 }
73243
73244
73245 /*
73246 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
73247 ** that name in the set of source tables in pSrcList and make the pExpr 
73248 ** expression node refer back to that source column.  The following changes
73249 ** are made to pExpr:
73250 **
73251 **    pExpr->iDb           Set the index in db->aDb[] of the database X
73252 **                         (even if X is implied).
73253 **    pExpr->iTable        Set to the cursor number for the table obtained
73254 **                         from pSrcList.
73255 **    pExpr->pTab          Points to the Table structure of X.Y (even if
73256 **                         X and/or Y are implied.)
73257 **    pExpr->iColumn       Set to the column number within the table.
73258 **    pExpr->op            Set to TK_COLUMN.
73259 **    pExpr->pLeft         Any expression this points to is deleted
73260 **    pExpr->pRight        Any expression this points to is deleted.
73261 **
73262 ** The zDb variable is the name of the database (the "X").  This value may be
73263 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
73264 ** can be used.  The zTable variable is the name of the table (the "Y").  This
73265 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
73266 ** means that the form of the name is Z and that columns from any table
73267 ** can be used.
73268 **
73269 ** If the name cannot be resolved unambiguously, leave an error message
73270 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
73271 */
73272 static int lookupName(
73273   Parse *pParse,       /* The parsing context */
73274   const char *zDb,     /* Name of the database containing table, or NULL */
73275   const char *zTab,    /* Name of table containing column, or NULL */
73276   const char *zCol,    /* Name of the column. */
73277   NameContext *pNC,    /* The name context used to resolve the name */
73278   Expr *pExpr          /* Make this EXPR node point to the selected column */
73279 ){
73280   int i, j;            /* Loop counters */
73281   int cnt = 0;                      /* Number of matching column names */
73282   int cntTab = 0;                   /* Number of matching table names */
73283   sqlcipher3 *db = pParse->db;         /* The database connection */
73284   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
73285   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
73286   NameContext *pTopNC = pNC;        /* First namecontext in the list */
73287   Schema *pSchema = 0;              /* Schema of the expression */
73288   int isTrigger = 0;
73289
73290   assert( pNC );     /* the name context cannot be NULL. */
73291   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
73292   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
73293
73294   /* Initialize the node to no-match */
73295   pExpr->iTable = -1;
73296   pExpr->pTab = 0;
73297   ExprSetIrreducible(pExpr);
73298
73299   /* Start at the inner-most context and move outward until a match is found */
73300   while( pNC && cnt==0 ){
73301     ExprList *pEList;
73302     SrcList *pSrcList = pNC->pSrcList;
73303
73304     if( pSrcList ){
73305       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
73306         Table *pTab;
73307         int iDb;
73308         Column *pCol;
73309   
73310         pTab = pItem->pTab;
73311         assert( pTab!=0 && pTab->zName!=0 );
73312         iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
73313         assert( pTab->nCol>0 );
73314         if( zTab ){
73315           if( pItem->zAlias ){
73316             char *zTabName = pItem->zAlias;
73317             if( sqlcipher3StrICmp(zTabName, zTab)!=0 ) continue;
73318           }else{
73319             char *zTabName = pTab->zName;
73320             if( NEVER(zTabName==0) || sqlcipher3StrICmp(zTabName, zTab)!=0 ){
73321               continue;
73322             }
73323             if( zDb!=0 && sqlcipher3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
73324               continue;
73325             }
73326           }
73327         }
73328         if( 0==(cntTab++) ){
73329           pExpr->iTable = pItem->iCursor;
73330           pExpr->pTab = pTab;
73331           pSchema = pTab->pSchema;
73332           pMatch = pItem;
73333         }
73334         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
73335           if( sqlcipher3StrICmp(pCol->zName, zCol)==0 ){
73336             /* If there has been exactly one prior match and this match
73337             ** is for the right-hand table of a NATURAL JOIN or is in a 
73338             ** USING clause, then skip this match.
73339             */
73340             if( cnt==1 ){
73341               if( pItem->jointype & JT_NATURAL ) continue;
73342               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
73343             }
73344             cnt++;
73345             pExpr->iTable = pItem->iCursor;
73346             pExpr->pTab = pTab;
73347             pMatch = pItem;
73348             pSchema = pTab->pSchema;
73349             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
73350             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
73351             break;
73352           }
73353         }
73354       }
73355     }
73356
73357 #ifndef SQLCIPHER_OMIT_TRIGGER
73358     /* If we have not already resolved the name, then maybe 
73359     ** it is a new.* or old.* trigger argument reference
73360     */
73361     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
73362       int op = pParse->eTriggerOp;
73363       Table *pTab = 0;
73364       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
73365       if( op!=TK_DELETE && sqlcipher3StrICmp("new",zTab) == 0 ){
73366         pExpr->iTable = 1;
73367         pTab = pParse->pTriggerTab;
73368       }else if( op!=TK_INSERT && sqlcipher3StrICmp("old",zTab)==0 ){
73369         pExpr->iTable = 0;
73370         pTab = pParse->pTriggerTab;
73371       }
73372
73373       if( pTab ){ 
73374         int iCol;
73375         pSchema = pTab->pSchema;
73376         cntTab++;
73377         for(iCol=0; iCol<pTab->nCol; iCol++){
73378           Column *pCol = &pTab->aCol[iCol];
73379           if( sqlcipher3StrICmp(pCol->zName, zCol)==0 ){
73380             if( iCol==pTab->iPKey ){
73381               iCol = -1;
73382             }
73383             break;
73384           }
73385         }
73386         if( iCol>=pTab->nCol && sqlcipher3IsRowid(zCol) ){
73387           iCol = -1;        /* IMP: R-44911-55124 */
73388         }
73389         if( iCol<pTab->nCol ){
73390           cnt++;
73391           if( iCol<0 ){
73392             pExpr->affinity = SQLCIPHER_AFF_INTEGER;
73393           }else if( pExpr->iTable==0 ){
73394             testcase( iCol==31 );
73395             testcase( iCol==32 );
73396             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73397           }else{
73398             testcase( iCol==31 );
73399             testcase( iCol==32 );
73400             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73401           }
73402           pExpr->iColumn = (i16)iCol;
73403           pExpr->pTab = pTab;
73404           isTrigger = 1;
73405         }
73406       }
73407     }
73408 #endif /* !defined(SQLCIPHER_OMIT_TRIGGER) */
73409
73410     /*
73411     ** Perhaps the name is a reference to the ROWID
73412     */
73413     if( cnt==0 && cntTab==1 && sqlcipher3IsRowid(zCol) ){
73414       cnt = 1;
73415       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
73416       pExpr->affinity = SQLCIPHER_AFF_INTEGER;
73417     }
73418
73419     /*
73420     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
73421     ** might refer to an result-set alias.  This happens, for example, when
73422     ** we are resolving names in the WHERE clause of the following command:
73423     **
73424     **     SELECT a+b AS x FROM table WHERE x<10;
73425     **
73426     ** In cases like this, replace pExpr with a copy of the expression that
73427     ** forms the result set entry ("a+b" in the example) and return immediately.
73428     ** Note that the expression in the result set should have already been
73429     ** resolved by the time the WHERE clause is resolved.
73430     */
73431     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
73432       for(j=0; j<pEList->nExpr; j++){
73433         char *zAs = pEList->a[j].zName;
73434         if( zAs!=0 && sqlcipher3StrICmp(zAs, zCol)==0 ){
73435           Expr *pOrig;
73436           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
73437           assert( pExpr->x.pList==0 );
73438           assert( pExpr->x.pSelect==0 );
73439           pOrig = pEList->a[j].pExpr;
73440           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
73441             sqlcipher3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
73442             return WRC_Abort;
73443           }
73444           resolveAlias(pParse, pEList, j, pExpr, "");
73445           cnt = 1;
73446           pMatch = 0;
73447           assert( zTab==0 && zDb==0 );
73448           goto lookupname_end;
73449         }
73450       } 
73451     }
73452
73453     /* Advance to the next name context.  The loop will exit when either
73454     ** we have a match (cnt>0) or when we run out of name contexts.
73455     */
73456     if( cnt==0 ){
73457       pNC = pNC->pNext;
73458     }
73459   }
73460
73461   /*
73462   ** If X and Y are NULL (in other words if only the column name Z is
73463   ** supplied) and the value of Z is enclosed in double-quotes, then
73464   ** Z is a string literal if it doesn't match any column names.  In that
73465   ** case, we need to return right away and not make any changes to
73466   ** pExpr.
73467   **
73468   ** Because no reference was made to outer contexts, the pNC->nRef
73469   ** fields are not changed in any context.
73470   */
73471   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
73472     pExpr->op = TK_STRING;
73473     pExpr->pTab = 0;
73474     return WRC_Prune;
73475   }
73476
73477   /*
73478   ** cnt==0 means there was not match.  cnt>1 means there were two or
73479   ** more matches.  Either way, we have an error.
73480   */
73481   if( cnt!=1 ){
73482     const char *zErr;
73483     zErr = cnt==0 ? "no such column" : "ambiguous column name";
73484     if( zDb ){
73485       sqlcipher3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
73486     }else if( zTab ){
73487       sqlcipher3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
73488     }else{
73489       sqlcipher3ErrorMsg(pParse, "%s: %s", zErr, zCol);
73490     }
73491     pParse->checkSchema = 1;
73492     pTopNC->nErr++;
73493   }
73494
73495   /* If a column from a table in pSrcList is referenced, then record
73496   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
73497   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
73498   ** column number is greater than the number of bits in the bitmask
73499   ** then set the high-order bit of the bitmask.
73500   */
73501   if( pExpr->iColumn>=0 && pMatch!=0 ){
73502     int n = pExpr->iColumn;
73503     testcase( n==BMS-1 );
73504     if( n>=BMS ){
73505       n = BMS-1;
73506     }
73507     assert( pMatch->iCursor==pExpr->iTable );
73508     pMatch->colUsed |= ((Bitmask)1)<<n;
73509   }
73510
73511   /* Clean up and return
73512   */
73513   sqlcipher3ExprDelete(db, pExpr->pLeft);
73514   pExpr->pLeft = 0;
73515   sqlcipher3ExprDelete(db, pExpr->pRight);
73516   pExpr->pRight = 0;
73517   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
73518 lookupname_end:
73519   if( cnt==1 ){
73520     assert( pNC!=0 );
73521     sqlcipher3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
73522     /* Increment the nRef value on all name contexts from TopNC up to
73523     ** the point where the name matched. */
73524     for(;;){
73525       assert( pTopNC!=0 );
73526       pTopNC->nRef++;
73527       if( pTopNC==pNC ) break;
73528       pTopNC = pTopNC->pNext;
73529     }
73530     return WRC_Prune;
73531   } else {
73532     return WRC_Abort;
73533   }
73534 }
73535
73536 /*
73537 ** Allocate and return a pointer to an expression to load the column iCol
73538 ** from datasource iSrc in SrcList pSrc.
73539 */
73540 SQLCIPHER_PRIVATE Expr *sqlcipher3CreateColumnExpr(sqlcipher3 *db, SrcList *pSrc, int iSrc, int iCol){
73541   Expr *p = sqlcipher3ExprAlloc(db, TK_COLUMN, 0, 0);
73542   if( p ){
73543     struct SrcList_item *pItem = &pSrc->a[iSrc];
73544     p->pTab = pItem->pTab;
73545     p->iTable = pItem->iCursor;
73546     if( p->pTab->iPKey==iCol ){
73547       p->iColumn = -1;
73548     }else{
73549       p->iColumn = (ynVar)iCol;
73550       testcase( iCol==BMS );
73551       testcase( iCol==BMS-1 );
73552       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
73553     }
73554     ExprSetProperty(p, EP_Resolved);
73555   }
73556   return p;
73557 }
73558
73559 /*
73560 ** This routine is callback for sqlcipher3WalkExpr().
73561 **
73562 ** Resolve symbolic names into TK_COLUMN operators for the current
73563 ** node in the expression tree.  Return 0 to continue the search down
73564 ** the tree or 2 to abort the tree walk.
73565 **
73566 ** This routine also does error checking and name resolution for
73567 ** function names.  The operator for aggregate functions is changed
73568 ** to TK_AGG_FUNCTION.
73569 */
73570 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
73571   NameContext *pNC;
73572   Parse *pParse;
73573
73574   pNC = pWalker->u.pNC;
73575   assert( pNC!=0 );
73576   pParse = pNC->pParse;
73577   assert( pParse==pWalker->pParse );
73578
73579   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
73580   ExprSetProperty(pExpr, EP_Resolved);
73581 #ifndef NDEBUG
73582   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
73583     SrcList *pSrcList = pNC->pSrcList;
73584     int i;
73585     for(i=0; i<pNC->pSrcList->nSrc; i++){
73586       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
73587     }
73588   }
73589 #endif
73590   switch( pExpr->op ){
73591
73592 #if defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY)
73593     /* The special operator TK_ROW means use the rowid for the first
73594     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
73595     ** clause processing on UPDATE and DELETE statements.
73596     */
73597     case TK_ROW: {
73598       SrcList *pSrcList = pNC->pSrcList;
73599       struct SrcList_item *pItem;
73600       assert( pSrcList && pSrcList->nSrc==1 );
73601       pItem = pSrcList->a; 
73602       pExpr->op = TK_COLUMN;
73603       pExpr->pTab = pItem->pTab;
73604       pExpr->iTable = pItem->iCursor;
73605       pExpr->iColumn = -1;
73606       pExpr->affinity = SQLCIPHER_AFF_INTEGER;
73607       break;
73608     }
73609 #endif /* defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY) */
73610
73611     /* A lone identifier is the name of a column.
73612     */
73613     case TK_ID: {
73614       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73615     }
73616   
73617     /* A table name and column name:     ID.ID
73618     ** Or a database, table and column:  ID.ID.ID
73619     */
73620     case TK_DOT: {
73621       const char *zColumn;
73622       const char *zTable;
73623       const char *zDb;
73624       Expr *pRight;
73625
73626       /* if( pSrcList==0 ) break; */
73627       pRight = pExpr->pRight;
73628       if( pRight->op==TK_ID ){
73629         zDb = 0;
73630         zTable = pExpr->pLeft->u.zToken;
73631         zColumn = pRight->u.zToken;
73632       }else{
73633         assert( pRight->op==TK_DOT );
73634         zDb = pExpr->pLeft->u.zToken;
73635         zTable = pRight->pLeft->u.zToken;
73636         zColumn = pRight->pRight->u.zToken;
73637       }
73638       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73639     }
73640
73641     /* Resolve function names
73642     */
73643     case TK_CONST_FUNC:
73644     case TK_FUNCTION: {
73645       ExprList *pList = pExpr->x.pList;    /* The argument list */
73646       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73647       int no_such_func = 0;       /* True if no such function exists */
73648       int wrong_num_args = 0;     /* True if wrong number of arguments */
73649       int is_agg = 0;             /* True if is an aggregate function */
73650       int auth;                   /* Authorization to use the function */
73651       int nId;                    /* Number of characters in function name */
73652       const char *zId;            /* The function name. */
73653       FuncDef *pDef;              /* Information about the function */
73654       u8 enc = ENC(pParse->db);   /* The database encoding */
73655
73656       testcase( pExpr->op==TK_CONST_FUNC );
73657       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73658       zId = pExpr->u.zToken;
73659       nId = sqlcipher3Strlen30(zId);
73660       pDef = sqlcipher3FindFunction(pParse->db, zId, nId, n, enc, 0);
73661       if( pDef==0 ){
73662         pDef = sqlcipher3FindFunction(pParse->db, zId, nId, -1, enc, 0);
73663         if( pDef==0 ){
73664           no_such_func = 1;
73665         }else{
73666           wrong_num_args = 1;
73667         }
73668       }else{
73669         is_agg = pDef->xFunc==0;
73670       }
73671 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
73672       if( pDef ){
73673         auth = sqlcipher3AuthCheck(pParse, SQLCIPHER_FUNCTION, 0, pDef->zName, 0);
73674         if( auth!=SQLCIPHER_OK ){
73675           if( auth==SQLCIPHER_DENY ){
73676             sqlcipher3ErrorMsg(pParse, "not authorized to use function: %s",
73677                                     pDef->zName);
73678             pNC->nErr++;
73679           }
73680           pExpr->op = TK_NULL;
73681           return WRC_Prune;
73682         }
73683       }
73684 #endif
73685       if( is_agg && !pNC->allowAgg ){
73686         sqlcipher3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73687         pNC->nErr++;
73688         is_agg = 0;
73689       }else if( no_such_func ){
73690         sqlcipher3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73691         pNC->nErr++;
73692       }else if( wrong_num_args ){
73693         sqlcipher3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73694              nId, zId);
73695         pNC->nErr++;
73696       }
73697       if( is_agg ){
73698         pExpr->op = TK_AGG_FUNCTION;
73699         pNC->hasAgg = 1;
73700       }
73701       if( is_agg ) pNC->allowAgg = 0;
73702       sqlcipher3WalkExprList(pWalker, pList);
73703       if( is_agg ) pNC->allowAgg = 1;
73704       /* FIX ME:  Compute pExpr->affinity based on the expected return
73705       ** type of the function 
73706       */
73707       return WRC_Prune;
73708     }
73709 #ifndef SQLCIPHER_OMIT_SUBQUERY
73710     case TK_SELECT:
73711     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73712 #endif
73713     case TK_IN: {
73714       testcase( pExpr->op==TK_IN );
73715       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73716         int nRef = pNC->nRef;
73717 #ifndef SQLCIPHER_OMIT_CHECK
73718         if( pNC->isCheck ){
73719           sqlcipher3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73720         }
73721 #endif
73722         sqlcipher3WalkSelect(pWalker, pExpr->x.pSelect);
73723         assert( pNC->nRef>=nRef );
73724         if( nRef!=pNC->nRef ){
73725           ExprSetProperty(pExpr, EP_VarSelect);
73726         }
73727       }
73728       break;
73729     }
73730 #ifndef SQLCIPHER_OMIT_CHECK
73731     case TK_VARIABLE: {
73732       if( pNC->isCheck ){
73733         sqlcipher3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73734       }
73735       break;
73736     }
73737 #endif
73738   }
73739   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73740 }
73741
73742 /*
73743 ** pEList is a list of expressions which are really the result set of the
73744 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73745 ** This routine checks to see if pE is a simple identifier which corresponds
73746 ** to the AS-name of one of the terms of the expression list.  If it is,
73747 ** this routine return an integer between 1 and N where N is the number of
73748 ** elements in pEList, corresponding to the matching entry.  If there is
73749 ** no match, or if pE is not a simple identifier, then this routine
73750 ** return 0.
73751 **
73752 ** pEList has been resolved.  pE has not.
73753 */
73754 static int resolveAsName(
73755   Parse *pParse,     /* Parsing context for error messages */
73756   ExprList *pEList,  /* List of expressions to scan */
73757   Expr *pE           /* Expression we are trying to match */
73758 ){
73759   int i;             /* Loop counter */
73760
73761   UNUSED_PARAMETER(pParse);
73762
73763   if( pE->op==TK_ID ){
73764     char *zCol = pE->u.zToken;
73765     for(i=0; i<pEList->nExpr; i++){
73766       char *zAs = pEList->a[i].zName;
73767       if( zAs!=0 && sqlcipher3StrICmp(zAs, zCol)==0 ){
73768         return i+1;
73769       }
73770     }
73771   }
73772   return 0;
73773 }
73774
73775 /*
73776 ** pE is a pointer to an expression which is a single term in the
73777 ** ORDER BY of a compound SELECT.  The expression has not been
73778 ** name resolved.
73779 **
73780 ** At the point this routine is called, we already know that the
73781 ** ORDER BY term is not an integer index into the result set.  That
73782 ** case is handled by the calling routine.
73783 **
73784 ** Attempt to match pE against result set columns in the left-most
73785 ** SELECT statement.  Return the index i of the matching column,
73786 ** as an indication to the caller that it should sort by the i-th column.
73787 ** The left-most column is 1.  In other words, the value returned is the
73788 ** same integer value that would be used in the SQL statement to indicate
73789 ** the column.
73790 **
73791 ** If there is no match, return 0.  Return -1 if an error occurs.
73792 */
73793 static int resolveOrderByTermToExprList(
73794   Parse *pParse,     /* Parsing context for error messages */
73795   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73796   Expr *pE           /* The specific ORDER BY term */
73797 ){
73798   int i;             /* Loop counter */
73799   ExprList *pEList;  /* The columns of the result set */
73800   NameContext nc;    /* Name context for resolving pE */
73801   sqlcipher3 *db;       /* Database connection */
73802   int rc;            /* Return code from subprocedures */
73803   u8 savedSuppErr;   /* Saved value of db->suppressErr */
73804
73805   assert( sqlcipher3ExprIsInteger(pE, &i)==0 );
73806   pEList = pSelect->pEList;
73807
73808   /* Resolve all names in the ORDER BY term expression
73809   */
73810   memset(&nc, 0, sizeof(nc));
73811   nc.pParse = pParse;
73812   nc.pSrcList = pSelect->pSrc;
73813   nc.pEList = pEList;
73814   nc.allowAgg = 1;
73815   nc.nErr = 0;
73816   db = pParse->db;
73817   savedSuppErr = db->suppressErr;
73818   db->suppressErr = 1;
73819   rc = sqlcipher3ResolveExprNames(&nc, pE);
73820   db->suppressErr = savedSuppErr;
73821   if( rc ) return 0;
73822
73823   /* Try to match the ORDER BY expression against an expression
73824   ** in the result set.  Return an 1-based index of the matching
73825   ** result-set entry.
73826   */
73827   for(i=0; i<pEList->nExpr; i++){
73828     if( sqlcipher3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73829       return i+1;
73830     }
73831   }
73832
73833   /* If no match, return 0. */
73834   return 0;
73835 }
73836
73837 /*
73838 ** Generate an ORDER BY or GROUP BY term out-of-range error.
73839 */
73840 static void resolveOutOfRangeError(
73841   Parse *pParse,         /* The error context into which to write the error */
73842   const char *zType,     /* "ORDER" or "GROUP" */
73843   int i,                 /* The index (1-based) of the term out of range */
73844   int mx                 /* Largest permissible value of i */
73845 ){
73846   sqlcipher3ErrorMsg(pParse, 
73847     "%r %s BY term out of range - should be "
73848     "between 1 and %d", i, zType, mx);
73849 }
73850
73851 /*
73852 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73853 ** each term of the ORDER BY clause is a constant integer between 1
73854 ** and N where N is the number of columns in the compound SELECT.
73855 **
73856 ** ORDER BY terms that are already an integer between 1 and N are
73857 ** unmodified.  ORDER BY terms that are integers outside the range of
73858 ** 1 through N generate an error.  ORDER BY terms that are expressions
73859 ** are matched against result set expressions of compound SELECT
73860 ** beginning with the left-most SELECT and working toward the right.
73861 ** At the first match, the ORDER BY expression is transformed into
73862 ** the integer column number.
73863 **
73864 ** Return the number of errors seen.
73865 */
73866 static int resolveCompoundOrderBy(
73867   Parse *pParse,        /* Parsing context.  Leave error messages here */
73868   Select *pSelect       /* The SELECT statement containing the ORDER BY */
73869 ){
73870   int i;
73871   ExprList *pOrderBy;
73872   ExprList *pEList;
73873   sqlcipher3 *db;
73874   int moreToDo = 1;
73875
73876   pOrderBy = pSelect->pOrderBy;
73877   if( pOrderBy==0 ) return 0;
73878   db = pParse->db;
73879 #if SQLCIPHER_MAX_COLUMN
73880   if( pOrderBy->nExpr>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
73881     sqlcipher3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73882     return 1;
73883   }
73884 #endif
73885   for(i=0; i<pOrderBy->nExpr; i++){
73886     pOrderBy->a[i].done = 0;
73887   }
73888   pSelect->pNext = 0;
73889   while( pSelect->pPrior ){
73890     pSelect->pPrior->pNext = pSelect;
73891     pSelect = pSelect->pPrior;
73892   }
73893   while( pSelect && moreToDo ){
73894     struct ExprList_item *pItem;
73895     moreToDo = 0;
73896     pEList = pSelect->pEList;
73897     assert( pEList!=0 );
73898     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73899       int iCol = -1;
73900       Expr *pE, *pDup;
73901       if( pItem->done ) continue;
73902       pE = pItem->pExpr;
73903       if( sqlcipher3ExprIsInteger(pE, &iCol) ){
73904         if( iCol<=0 || iCol>pEList->nExpr ){
73905           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73906           return 1;
73907         }
73908       }else{
73909         iCol = resolveAsName(pParse, pEList, pE);
73910         if( iCol==0 ){
73911           pDup = sqlcipher3ExprDup(db, pE, 0);
73912           if( !db->mallocFailed ){
73913             assert(pDup);
73914             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73915           }
73916           sqlcipher3ExprDelete(db, pDup);
73917         }
73918       }
73919       if( iCol>0 ){
73920         CollSeq *pColl = pE->pColl;
73921         int flags = pE->flags & EP_ExpCollate;
73922         sqlcipher3ExprDelete(db, pE);
73923         pItem->pExpr = pE = sqlcipher3Expr(db, TK_INTEGER, 0);
73924         if( pE==0 ) return 1;
73925         pE->pColl = pColl;
73926         pE->flags |= EP_IntValue | flags;
73927         pE->u.iValue = iCol;
73928         pItem->iCol = (u16)iCol;
73929         pItem->done = 1;
73930       }else{
73931         moreToDo = 1;
73932       }
73933     }
73934     pSelect = pSelect->pNext;
73935   }
73936   for(i=0; i<pOrderBy->nExpr; i++){
73937     if( pOrderBy->a[i].done==0 ){
73938       sqlcipher3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73939             "column in the result set", i+1);
73940       return 1;
73941     }
73942   }
73943   return 0;
73944 }
73945
73946 /*
73947 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
73948 ** the SELECT statement pSelect.  If any term is reference to a
73949 ** result set expression (as determined by the ExprList.a.iCol field)
73950 ** then convert that term into a copy of the corresponding result set
73951 ** column.
73952 **
73953 ** If any errors are detected, add an error message to pParse and
73954 ** return non-zero.  Return zero if no errors are seen.
73955 */
73956 SQLCIPHER_PRIVATE int sqlcipher3ResolveOrderGroupBy(
73957   Parse *pParse,        /* Parsing context.  Leave error messages here */
73958   Select *pSelect,      /* The SELECT statement containing the clause */
73959   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
73960   const char *zType     /* "ORDER" or "GROUP" */
73961 ){
73962   int i;
73963   sqlcipher3 *db = pParse->db;
73964   ExprList *pEList;
73965   struct ExprList_item *pItem;
73966
73967   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
73968 #if SQLCIPHER_MAX_COLUMN
73969   if( pOrderBy->nExpr>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
73970     sqlcipher3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
73971     return 1;
73972   }
73973 #endif
73974   pEList = pSelect->pEList;
73975   assert( pEList!=0 );  /* sqlcipher3SelectNew() guarantees this */
73976   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73977     if( pItem->iCol ){
73978       if( pItem->iCol>pEList->nExpr ){
73979         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
73980         return 1;
73981       }
73982       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
73983     }
73984   }
73985   return 0;
73986 }
73987
73988 /*
73989 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
73990 ** The Name context of the SELECT statement is pNC.  zType is either
73991 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
73992 **
73993 ** This routine resolves each term of the clause into an expression.
73994 ** If the order-by term is an integer I between 1 and N (where N is the
73995 ** number of columns in the result set of the SELECT) then the expression
73996 ** in the resolution is a copy of the I-th result-set expression.  If
73997 ** the order-by term is an identify that corresponds to the AS-name of
73998 ** a result-set expression, then the term resolves to a copy of the
73999 ** result-set expression.  Otherwise, the expression is resolved in
74000 ** the usual way - using sqlcipher3ResolveExprNames().
74001 **
74002 ** This routine returns the number of errors.  If errors occur, then
74003 ** an appropriate error message might be left in pParse.  (OOM errors
74004 ** excepted.)
74005 */
74006 static int resolveOrderGroupBy(
74007   NameContext *pNC,     /* The name context of the SELECT statement */
74008   Select *pSelect,      /* The SELECT statement holding pOrderBy */
74009   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
74010   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
74011 ){
74012   int i;                         /* Loop counter */
74013   int iCol;                      /* Column number */
74014   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
74015   Parse *pParse;                 /* Parsing context */
74016   int nResult;                   /* Number of terms in the result set */
74017
74018   if( pOrderBy==0 ) return 0;
74019   nResult = pSelect->pEList->nExpr;
74020   pParse = pNC->pParse;
74021   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74022     Expr *pE = pItem->pExpr;
74023     iCol = resolveAsName(pParse, pSelect->pEList, pE);
74024     if( iCol>0 ){
74025       /* If an AS-name match is found, mark this ORDER BY column as being
74026       ** a copy of the iCol-th result-set column.  The subsequent call to
74027       ** sqlcipher3ResolveOrderGroupBy() will convert the expression to a
74028       ** copy of the iCol-th result-set expression. */
74029       pItem->iCol = (u16)iCol;
74030       continue;
74031     }
74032     if( sqlcipher3ExprIsInteger(pE, &iCol) ){
74033       /* The ORDER BY term is an integer constant.  Again, set the column
74034       ** number so that sqlcipher3ResolveOrderGroupBy() will convert the
74035       ** order-by term to a copy of the result-set expression */
74036       if( iCol<1 ){
74037         resolveOutOfRangeError(pParse, zType, i+1, nResult);
74038         return 1;
74039       }
74040       pItem->iCol = (u16)iCol;
74041       continue;
74042     }
74043
74044     /* Otherwise, treat the ORDER BY term as an ordinary expression */
74045     pItem->iCol = 0;
74046     if( sqlcipher3ResolveExprNames(pNC, pE) ){
74047       return 1;
74048     }
74049   }
74050   return sqlcipher3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
74051 }
74052
74053 /*
74054 ** Resolve names in the SELECT statement p and all of its descendents.
74055 */
74056 static int resolveSelectStep(Walker *pWalker, Select *p){
74057   NameContext *pOuterNC;  /* Context that contains this SELECT */
74058   NameContext sNC;        /* Name context of this SELECT */
74059   int isCompound;         /* True if p is a compound select */
74060   int nCompound;          /* Number of compound terms processed so far */
74061   Parse *pParse;          /* Parsing context */
74062   ExprList *pEList;       /* Result set expression list */
74063   int i;                  /* Loop counter */
74064   ExprList *pGroupBy;     /* The GROUP BY clause */
74065   Select *pLeftmost;      /* Left-most of SELECT of a compound */
74066   sqlcipher3 *db;            /* Database connection */
74067   
74068
74069   assert( p!=0 );
74070   if( p->selFlags & SF_Resolved ){
74071     return WRC_Prune;
74072   }
74073   pOuterNC = pWalker->u.pNC;
74074   pParse = pWalker->pParse;
74075   db = pParse->db;
74076
74077   /* Normally sqlcipher3SelectExpand() will be called first and will have
74078   ** already expanded this SELECT.  However, if this is a subquery within
74079   ** an expression, sqlcipher3ResolveExprNames() will be called without a
74080   ** prior call to sqlcipher3SelectExpand().  When that happens, let
74081   ** sqlcipher3SelectPrep() do all of the processing for this SELECT.
74082   ** sqlcipher3SelectPrep() will invoke both sqlcipher3SelectExpand() and
74083   ** this routine in the correct order.
74084   */
74085   if( (p->selFlags & SF_Expanded)==0 ){
74086     sqlcipher3SelectPrep(pParse, p, pOuterNC);
74087     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
74088   }
74089
74090   isCompound = p->pPrior!=0;
74091   nCompound = 0;
74092   pLeftmost = p;
74093   while( p ){
74094     assert( (p->selFlags & SF_Expanded)!=0 );
74095     assert( (p->selFlags & SF_Resolved)==0 );
74096     p->selFlags |= SF_Resolved;
74097
74098     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
74099     ** are not allowed to refer to any names, so pass an empty NameContext.
74100     */
74101     memset(&sNC, 0, sizeof(sNC));
74102     sNC.pParse = pParse;
74103     if( sqlcipher3ResolveExprNames(&sNC, p->pLimit) ||
74104         sqlcipher3ResolveExprNames(&sNC, p->pOffset) ){
74105       return WRC_Abort;
74106     }
74107   
74108     /* Set up the local name-context to pass to sqlcipher3ResolveExprNames() to
74109     ** resolve the result-set expression list.
74110     */
74111     sNC.allowAgg = 1;
74112     sNC.pSrcList = p->pSrc;
74113     sNC.pNext = pOuterNC;
74114   
74115     /* Resolve names in the result set. */
74116     pEList = p->pEList;
74117     assert( pEList!=0 );
74118     for(i=0; i<pEList->nExpr; i++){
74119       Expr *pX = pEList->a[i].pExpr;
74120       if( sqlcipher3ResolveExprNames(&sNC, pX) ){
74121         return WRC_Abort;
74122       }
74123     }
74124   
74125     /* Recursively resolve names in all subqueries
74126     */
74127     for(i=0; i<p->pSrc->nSrc; i++){
74128       struct SrcList_item *pItem = &p->pSrc->a[i];
74129       if( pItem->pSelect ){
74130         NameContext *pNC;         /* Used to iterate name contexts */
74131         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
74132         const char *zSavedContext = pParse->zAuthContext;
74133
74134         /* Count the total number of references to pOuterNC and all of its
74135         ** parent contexts. After resolving references to expressions in
74136         ** pItem->pSelect, check if this value has changed. If so, then
74137         ** SELECT statement pItem->pSelect must be correlated. Set the
74138         ** pItem->isCorrelated flag if this is the case. */
74139         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
74140
74141         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
74142         sqlcipher3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
74143         pParse->zAuthContext = zSavedContext;
74144         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
74145
74146         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
74147         assert( pItem->isCorrelated==0 && nRef<=0 );
74148         pItem->isCorrelated = (nRef!=0);
74149       }
74150     }
74151   
74152     /* If there are no aggregate functions in the result-set, and no GROUP BY 
74153     ** expression, do not allow aggregates in any of the other expressions.
74154     */
74155     assert( (p->selFlags & SF_Aggregate)==0 );
74156     pGroupBy = p->pGroupBy;
74157     if( pGroupBy || sNC.hasAgg ){
74158       p->selFlags |= SF_Aggregate;
74159     }else{
74160       sNC.allowAgg = 0;
74161     }
74162   
74163     /* If a HAVING clause is present, then there must be a GROUP BY clause.
74164     */
74165     if( p->pHaving && !pGroupBy ){
74166       sqlcipher3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
74167       return WRC_Abort;
74168     }
74169   
74170     /* Add the expression list to the name-context before parsing the
74171     ** other expressions in the SELECT statement. This is so that
74172     ** expressions in the WHERE clause (etc.) can refer to expressions by
74173     ** aliases in the result set.
74174     **
74175     ** Minor point: If this is the case, then the expression will be
74176     ** re-evaluated for each reference to it.
74177     */
74178     sNC.pEList = p->pEList;
74179     if( sqlcipher3ResolveExprNames(&sNC, p->pWhere) ||
74180        sqlcipher3ResolveExprNames(&sNC, p->pHaving)
74181     ){
74182       return WRC_Abort;
74183     }
74184
74185     /* The ORDER BY and GROUP BY clauses may not refer to terms in
74186     ** outer queries 
74187     */
74188     sNC.pNext = 0;
74189     sNC.allowAgg = 1;
74190
74191     /* Process the ORDER BY clause for singleton SELECT statements.
74192     ** The ORDER BY clause for compounds SELECT statements is handled
74193     ** below, after all of the result-sets for all of the elements of
74194     ** the compound have been resolved.
74195     */
74196     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
74197       return WRC_Abort;
74198     }
74199     if( db->mallocFailed ){
74200       return WRC_Abort;
74201     }
74202   
74203     /* Resolve the GROUP BY clause.  At the same time, make sure 
74204     ** the GROUP BY clause does not contain aggregate functions.
74205     */
74206     if( pGroupBy ){
74207       struct ExprList_item *pItem;
74208     
74209       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
74210         return WRC_Abort;
74211       }
74212       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
74213         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
74214           sqlcipher3ErrorMsg(pParse, "aggregate functions are not allowed in "
74215               "the GROUP BY clause");
74216           return WRC_Abort;
74217         }
74218       }
74219     }
74220
74221     /* Advance to the next term of the compound
74222     */
74223     p = p->pPrior;
74224     nCompound++;
74225   }
74226
74227   /* Resolve the ORDER BY on a compound SELECT after all terms of
74228   ** the compound have been resolved.
74229   */
74230   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
74231     return WRC_Abort;
74232   }
74233
74234   return WRC_Prune;
74235 }
74236
74237 /*
74238 ** This routine walks an expression tree and resolves references to
74239 ** table columns and result-set columns.  At the same time, do error
74240 ** checking on function usage and set a flag if any aggregate functions
74241 ** are seen.
74242 **
74243 ** To resolve table columns references we look for nodes (or subtrees) of the 
74244 ** form X.Y.Z or Y.Z or just Z where
74245 **
74246 **      X:   The name of a database.  Ex:  "main" or "temp" or
74247 **           the symbolic name assigned to an ATTACH-ed database.
74248 **
74249 **      Y:   The name of a table in a FROM clause.  Or in a trigger
74250 **           one of the special names "old" or "new".
74251 **
74252 **      Z:   The name of a column in table Y.
74253 **
74254 ** The node at the root of the subtree is modified as follows:
74255 **
74256 **    Expr.op        Changed to TK_COLUMN
74257 **    Expr.pTab      Points to the Table object for X.Y
74258 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
74259 **    Expr.iTable    The VDBE cursor number for X.Y
74260 **
74261 **
74262 ** To resolve result-set references, look for expression nodes of the
74263 ** form Z (with no X and Y prefix) where the Z matches the right-hand
74264 ** size of an AS clause in the result-set of a SELECT.  The Z expression
74265 ** is replaced by a copy of the left-hand side of the result-set expression.
74266 ** Table-name and function resolution occurs on the substituted expression
74267 ** tree.  For example, in:
74268 **
74269 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
74270 **
74271 ** The "x" term of the order by is replaced by "a+b" to render:
74272 **
74273 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
74274 **
74275 ** Function calls are checked to make sure that the function is 
74276 ** defined and that the correct number of arguments are specified.
74277 ** If the function is an aggregate function, then the pNC->hasAgg is
74278 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
74279 ** If an expression contains aggregate functions then the EP_Agg
74280 ** property on the expression is set.
74281 **
74282 ** An error message is left in pParse if anything is amiss.  The number
74283 ** if errors is returned.
74284 */
74285 SQLCIPHER_PRIVATE int sqlcipher3ResolveExprNames( 
74286   NameContext *pNC,       /* Namespace to resolve expressions in. */
74287   Expr *pExpr             /* The expression to be analyzed. */
74288 ){
74289   int savedHasAgg;
74290   Walker w;
74291
74292   if( pExpr==0 ) return 0;
74293 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74294   {
74295     Parse *pParse = pNC->pParse;
74296     if( sqlcipher3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
74297       return 1;
74298     }
74299     pParse->nHeight += pExpr->nHeight;
74300   }
74301 #endif
74302   savedHasAgg = pNC->hasAgg;
74303   pNC->hasAgg = 0;
74304   w.xExprCallback = resolveExprStep;
74305   w.xSelectCallback = resolveSelectStep;
74306   w.pParse = pNC->pParse;
74307   w.u.pNC = pNC;
74308   sqlcipher3WalkExpr(&w, pExpr);
74309 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74310   pNC->pParse->nHeight -= pExpr->nHeight;
74311 #endif
74312   if( pNC->nErr>0 || w.pParse->nErr>0 ){
74313     ExprSetProperty(pExpr, EP_Error);
74314   }
74315   if( pNC->hasAgg ){
74316     ExprSetProperty(pExpr, EP_Agg);
74317   }else if( savedHasAgg ){
74318     pNC->hasAgg = 1;
74319   }
74320   return ExprHasProperty(pExpr, EP_Error);
74321 }
74322
74323
74324 /*
74325 ** Resolve all names in all expressions of a SELECT and in all
74326 ** decendents of the SELECT, including compounds off of p->pPrior,
74327 ** subqueries in expressions, and subqueries used as FROM clause
74328 ** terms.
74329 **
74330 ** See sqlcipher3ResolveExprNames() for a description of the kinds of
74331 ** transformations that occur.
74332 **
74333 ** All SELECT statements should have been expanded using
74334 ** sqlcipher3SelectExpand() prior to invoking this routine.
74335 */
74336 SQLCIPHER_PRIVATE void sqlcipher3ResolveSelectNames(
74337   Parse *pParse,         /* The parser context */
74338   Select *p,             /* The SELECT statement being coded. */
74339   NameContext *pOuterNC  /* Name context for parent SELECT statement */
74340 ){
74341   Walker w;
74342
74343   assert( p!=0 );
74344   w.xExprCallback = resolveExprStep;
74345   w.xSelectCallback = resolveSelectStep;
74346   w.pParse = pParse;
74347   w.u.pNC = pOuterNC;
74348   sqlcipher3WalkSelect(&w, p);
74349 }
74350
74351 /************** End of resolve.c *********************************************/
74352 /************** Begin file expr.c ********************************************/
74353 /*
74354 ** 2001 September 15
74355 **
74356 ** The author disclaims copyright to this source code.  In place of
74357 ** a legal notice, here is a blessing:
74358 **
74359 **    May you do good and not evil.
74360 **    May you find forgiveness for yourself and forgive others.
74361 **    May you share freely, never taking more than you give.
74362 **
74363 *************************************************************************
74364 ** This file contains routines used for analyzing expressions and
74365 ** for generating VDBE code that evaluates expressions in SQLite.
74366 */
74367
74368 /*
74369 ** Return the 'affinity' of the expression pExpr if any.
74370 **
74371 ** If pExpr is a column, a reference to a column via an 'AS' alias,
74372 ** or a sub-select with a column as the return value, then the 
74373 ** affinity of that column is returned. Otherwise, 0x00 is returned,
74374 ** indicating no affinity for the expression.
74375 **
74376 ** i.e. the WHERE clause expresssions in the following statements all
74377 ** have an affinity:
74378 **
74379 ** CREATE TABLE t1(a);
74380 ** SELECT * FROM t1 WHERE a;
74381 ** SELECT a AS b FROM t1 WHERE b;
74382 ** SELECT * FROM t1 WHERE (select a from t1);
74383 */
74384 SQLCIPHER_PRIVATE char sqlcipher3ExprAffinity(Expr *pExpr){
74385   int op = pExpr->op;
74386   if( op==TK_SELECT ){
74387     assert( pExpr->flags&EP_xIsSelect );
74388     return sqlcipher3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
74389   }
74390 #ifndef SQLCIPHER_OMIT_CAST
74391   if( op==TK_CAST ){
74392     assert( !ExprHasProperty(pExpr, EP_IntValue) );
74393     return sqlcipher3AffinityType(pExpr->u.zToken);
74394   }
74395 #endif
74396   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
74397    && pExpr->pTab!=0
74398   ){
74399     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
74400     ** a TK_COLUMN but was previously evaluated and cached in a register */
74401     int j = pExpr->iColumn;
74402     if( j<0 ) return SQLCIPHER_AFF_INTEGER;
74403     assert( pExpr->pTab && j<pExpr->pTab->nCol );
74404     return pExpr->pTab->aCol[j].affinity;
74405   }
74406   return pExpr->affinity;
74407 }
74408
74409 /*
74410 ** Set the explicit collating sequence for an expression to the
74411 ** collating sequence supplied in the second argument.
74412 */
74413 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetColl(Expr *pExpr, CollSeq *pColl){
74414   if( pExpr && pColl ){
74415     pExpr->pColl = pColl;
74416     pExpr->flags |= EP_ExpCollate;
74417   }
74418   return pExpr;
74419 }
74420
74421 /*
74422 ** Set the collating sequence for expression pExpr to be the collating
74423 ** sequence named by pToken.   Return a pointer to the revised expression.
74424 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
74425 ** flag.  An explicit collating sequence will override implicit
74426 ** collating sequences.
74427 */
74428 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
74429   char *zColl = 0;            /* Dequoted name of collation sequence */
74430   CollSeq *pColl;
74431   sqlcipher3 *db = pParse->db;
74432   zColl = sqlcipher3NameFromToken(db, pCollName);
74433   pColl = sqlcipher3LocateCollSeq(pParse, zColl);
74434   sqlcipher3ExprSetColl(pExpr, pColl);
74435   sqlcipher3DbFree(db, zColl);
74436   return pExpr;
74437 }
74438
74439 /*
74440 ** Return the default collation sequence for the expression pExpr. If
74441 ** there is no default collation type, return 0.
74442 */
74443 SQLCIPHER_PRIVATE CollSeq *sqlcipher3ExprCollSeq(Parse *pParse, Expr *pExpr){
74444   CollSeq *pColl = 0;
74445   Expr *p = pExpr;
74446   while( p ){
74447     int op;
74448     pColl = p->pColl;
74449     if( pColl ) break;
74450     op = p->op;
74451     if( p->pTab!=0 && (
74452         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
74453     )){
74454       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
74455       ** a TK_COLUMN but was previously evaluated and cached in a register */
74456       const char *zColl;
74457       int j = p->iColumn;
74458       if( j>=0 ){
74459         sqlcipher3 *db = pParse->db;
74460         zColl = p->pTab->aCol[j].zColl;
74461         pColl = sqlcipher3FindCollSeq(db, ENC(db), zColl, 0);
74462         pExpr->pColl = pColl;
74463       }
74464       break;
74465     }
74466     if( op!=TK_CAST && op!=TK_UPLUS ){
74467       break;
74468     }
74469     p = p->pLeft;
74470   }
74471   if( sqlcipher3CheckCollSeq(pParse, pColl) ){ 
74472     pColl = 0;
74473   }
74474   return pColl;
74475 }
74476
74477 /*
74478 ** pExpr is an operand of a comparison operator.  aff2 is the
74479 ** type affinity of the other operand.  This routine returns the
74480 ** type affinity that should be used for the comparison operator.
74481 */
74482 SQLCIPHER_PRIVATE char sqlcipher3CompareAffinity(Expr *pExpr, char aff2){
74483   char aff1 = sqlcipher3ExprAffinity(pExpr);
74484   if( aff1 && aff2 ){
74485     /* Both sides of the comparison are columns. If one has numeric
74486     ** affinity, use that. Otherwise use no affinity.
74487     */
74488     if( sqlcipher3IsNumericAffinity(aff1) || sqlcipher3IsNumericAffinity(aff2) ){
74489       return SQLCIPHER_AFF_NUMERIC;
74490     }else{
74491       return SQLCIPHER_AFF_NONE;
74492     }
74493   }else if( !aff1 && !aff2 ){
74494     /* Neither side of the comparison is a column.  Compare the
74495     ** results directly.
74496     */
74497     return SQLCIPHER_AFF_NONE;
74498   }else{
74499     /* One side is a column, the other is not. Use the columns affinity. */
74500     assert( aff1==0 || aff2==0 );
74501     return (aff1 + aff2);
74502   }
74503 }
74504
74505 /*
74506 ** pExpr is a comparison operator.  Return the type affinity that should
74507 ** be applied to both operands prior to doing the comparison.
74508 */
74509 static char comparisonAffinity(Expr *pExpr){
74510   char aff;
74511   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
74512           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
74513           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
74514   assert( pExpr->pLeft );
74515   aff = sqlcipher3ExprAffinity(pExpr->pLeft);
74516   if( pExpr->pRight ){
74517     aff = sqlcipher3CompareAffinity(pExpr->pRight, aff);
74518   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74519     aff = sqlcipher3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
74520   }else if( !aff ){
74521     aff = SQLCIPHER_AFF_NONE;
74522   }
74523   return aff;
74524 }
74525
74526 /*
74527 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
74528 ** idx_affinity is the affinity of an indexed column. Return true
74529 ** if the index with affinity idx_affinity may be used to implement
74530 ** the comparison in pExpr.
74531 */
74532 SQLCIPHER_PRIVATE int sqlcipher3IndexAffinityOk(Expr *pExpr, char idx_affinity){
74533   char aff = comparisonAffinity(pExpr);
74534   switch( aff ){
74535     case SQLCIPHER_AFF_NONE:
74536       return 1;
74537     case SQLCIPHER_AFF_TEXT:
74538       return idx_affinity==SQLCIPHER_AFF_TEXT;
74539     default:
74540       return sqlcipher3IsNumericAffinity(idx_affinity);
74541   }
74542 }
74543
74544 /*
74545 ** Return the P5 value that should be used for a binary comparison
74546 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
74547 */
74548 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
74549   u8 aff = (char)sqlcipher3ExprAffinity(pExpr2);
74550   aff = (u8)sqlcipher3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74551   return aff;
74552 }
74553
74554 /*
74555 ** Return a pointer to the collation sequence that should be used by
74556 ** a binary comparison operator comparing pLeft and pRight.
74557 **
74558 ** If the left hand expression has a collating sequence type, then it is
74559 ** used. Otherwise the collation sequence for the right hand expression
74560 ** is used, or the default (BINARY) if neither expression has a collating
74561 ** type.
74562 **
74563 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
74564 ** it is not considered.
74565 */
74566 SQLCIPHER_PRIVATE CollSeq *sqlcipher3BinaryCompareCollSeq(
74567   Parse *pParse, 
74568   Expr *pLeft, 
74569   Expr *pRight
74570 ){
74571   CollSeq *pColl;
74572   assert( pLeft );
74573   if( pLeft->flags & EP_ExpCollate ){
74574     assert( pLeft->pColl );
74575     pColl = pLeft->pColl;
74576   }else if( pRight && pRight->flags & EP_ExpCollate ){
74577     assert( pRight->pColl );
74578     pColl = pRight->pColl;
74579   }else{
74580     pColl = sqlcipher3ExprCollSeq(pParse, pLeft);
74581     if( !pColl ){
74582       pColl = sqlcipher3ExprCollSeq(pParse, pRight);
74583     }
74584   }
74585   return pColl;
74586 }
74587
74588 /*
74589 ** Generate code for a comparison operator.
74590 */
74591 static int codeCompare(
74592   Parse *pParse,    /* The parsing (and code generating) context */
74593   Expr *pLeft,      /* The left operand */
74594   Expr *pRight,     /* The right operand */
74595   int opcode,       /* The comparison opcode */
74596   int in1, int in2, /* Register holding operands */
74597   int dest,         /* Jump here if true.  */
74598   int jumpIfNull    /* If true, jump if either operand is NULL */
74599 ){
74600   int p5;
74601   int addr;
74602   CollSeq *p4;
74603
74604   p4 = sqlcipher3BinaryCompareCollSeq(pParse, pLeft, pRight);
74605   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74606   addr = sqlcipher3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74607                            (void*)p4, P4_COLLSEQ);
74608   sqlcipher3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74609   return addr;
74610 }
74611
74612 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74613 /*
74614 ** Check that argument nHeight is less than or equal to the maximum
74615 ** expression depth allowed. If it is not, leave an error message in
74616 ** pParse.
74617 */
74618 SQLCIPHER_PRIVATE int sqlcipher3ExprCheckHeight(Parse *pParse, int nHeight){
74619   int rc = SQLCIPHER_OK;
74620   int mxHeight = pParse->db->aLimit[SQLCIPHER_LIMIT_EXPR_DEPTH];
74621   if( nHeight>mxHeight ){
74622     sqlcipher3ErrorMsg(pParse, 
74623        "Expression tree is too large (maximum depth %d)", mxHeight
74624     );
74625     rc = SQLCIPHER_ERROR;
74626   }
74627   return rc;
74628 }
74629
74630 /* The following three functions, heightOfExpr(), heightOfExprList()
74631 ** and heightOfSelect(), are used to determine the maximum height
74632 ** of any expression tree referenced by the structure passed as the
74633 ** first argument.
74634 **
74635 ** If this maximum height is greater than the current value pointed
74636 ** to by pnHeight, the second parameter, then set *pnHeight to that
74637 ** value.
74638 */
74639 static void heightOfExpr(Expr *p, int *pnHeight){
74640   if( p ){
74641     if( p->nHeight>*pnHeight ){
74642       *pnHeight = p->nHeight;
74643     }
74644   }
74645 }
74646 static void heightOfExprList(ExprList *p, int *pnHeight){
74647   if( p ){
74648     int i;
74649     for(i=0; i<p->nExpr; i++){
74650       heightOfExpr(p->a[i].pExpr, pnHeight);
74651     }
74652   }
74653 }
74654 static void heightOfSelect(Select *p, int *pnHeight){
74655   if( p ){
74656     heightOfExpr(p->pWhere, pnHeight);
74657     heightOfExpr(p->pHaving, pnHeight);
74658     heightOfExpr(p->pLimit, pnHeight);
74659     heightOfExpr(p->pOffset, pnHeight);
74660     heightOfExprList(p->pEList, pnHeight);
74661     heightOfExprList(p->pGroupBy, pnHeight);
74662     heightOfExprList(p->pOrderBy, pnHeight);
74663     heightOfSelect(p->pPrior, pnHeight);
74664   }
74665 }
74666
74667 /*
74668 ** Set the Expr.nHeight variable in the structure passed as an 
74669 ** argument. An expression with no children, Expr.pList or 
74670 ** Expr.pSelect member has a height of 1. Any other expression
74671 ** has a height equal to the maximum height of any other 
74672 ** referenced Expr plus one.
74673 */
74674 static void exprSetHeight(Expr *p){
74675   int nHeight = 0;
74676   heightOfExpr(p->pLeft, &nHeight);
74677   heightOfExpr(p->pRight, &nHeight);
74678   if( ExprHasProperty(p, EP_xIsSelect) ){
74679     heightOfSelect(p->x.pSelect, &nHeight);
74680   }else{
74681     heightOfExprList(p->x.pList, &nHeight);
74682   }
74683   p->nHeight = nHeight + 1;
74684 }
74685
74686 /*
74687 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
74688 ** the height is greater than the maximum allowed expression depth,
74689 ** leave an error in pParse.
74690 */
74691 SQLCIPHER_PRIVATE void sqlcipher3ExprSetHeight(Parse *pParse, Expr *p){
74692   exprSetHeight(p);
74693   sqlcipher3ExprCheckHeight(pParse, p->nHeight);
74694 }
74695
74696 /*
74697 ** Return the maximum height of any expression tree referenced
74698 ** by the select statement passed as an argument.
74699 */
74700 SQLCIPHER_PRIVATE int sqlcipher3SelectExprHeight(Select *p){
74701   int nHeight = 0;
74702   heightOfSelect(p, &nHeight);
74703   return nHeight;
74704 }
74705 #else
74706   #define exprSetHeight(y)
74707 #endif /* SQLCIPHER_MAX_EXPR_DEPTH>0 */
74708
74709 /*
74710 ** This routine is the core allocator for Expr nodes.
74711 **
74712 ** Construct a new expression node and return a pointer to it.  Memory
74713 ** for this node and for the pToken argument is a single allocation
74714 ** obtained from sqlcipher3DbMalloc().  The calling function
74715 ** is responsible for making sure the node eventually gets freed.
74716 **
74717 ** If dequote is true, then the token (if it exists) is dequoted.
74718 ** If dequote is false, no dequoting is performance.  The deQuote
74719 ** parameter is ignored if pToken is NULL or if the token does not
74720 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74721 ** then the EP_DblQuoted flag is set on the expression node.
74722 **
74723 ** Special case:  If op==TK_INTEGER and pToken points to a string that
74724 ** can be translated into a 32-bit integer, then the token is not
74725 ** stored in u.zToken.  Instead, the integer values is written
74726 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
74727 ** is allocated to hold the integer text and the dequote flag is ignored.
74728 */
74729 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAlloc(
74730   sqlcipher3 *db,            /* Handle for sqlcipher3DbMallocZero() (may be null) */
74731   int op,                 /* Expression opcode */
74732   const Token *pToken,    /* Token argument.  Might be NULL */
74733   int dequote             /* True to dequote */
74734 ){
74735   Expr *pNew;
74736   int nExtra = 0;
74737   int iValue = 0;
74738
74739   if( pToken ){
74740     if( op!=TK_INTEGER || pToken->z==0
74741           || sqlcipher3GetInt32(pToken->z, &iValue)==0 ){
74742       nExtra = pToken->n+1;
74743       assert( iValue>=0 );
74744     }
74745   }
74746   pNew = sqlcipher3DbMallocZero(db, sizeof(Expr)+nExtra);
74747   if( pNew ){
74748     pNew->op = (u8)op;
74749     pNew->iAgg = -1;
74750     if( pToken ){
74751       if( nExtra==0 ){
74752         pNew->flags |= EP_IntValue;
74753         pNew->u.iValue = iValue;
74754       }else{
74755         int c;
74756         pNew->u.zToken = (char*)&pNew[1];
74757         assert( pToken->z!=0 || pToken->n==0 );
74758         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74759         pNew->u.zToken[pToken->n] = 0;
74760         if( dequote && nExtra>=3 
74761              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74762           sqlcipher3Dequote(pNew->u.zToken);
74763           if( c=='"' ) pNew->flags |= EP_DblQuoted;
74764         }
74765       }
74766     }
74767 #if SQLCIPHER_MAX_EXPR_DEPTH>0
74768     pNew->nHeight = 1;
74769 #endif  
74770   }
74771   return pNew;
74772 }
74773
74774 /*
74775 ** Allocate a new expression node from a zero-terminated token that has
74776 ** already been dequoted.
74777 */
74778 SQLCIPHER_PRIVATE Expr *sqlcipher3Expr(
74779   sqlcipher3 *db,            /* Handle for sqlcipher3DbMallocZero() (may be null) */
74780   int op,                 /* Expression opcode */
74781   const char *zToken      /* Token argument.  Might be NULL */
74782 ){
74783   Token x;
74784   x.z = zToken;
74785   x.n = zToken ? sqlcipher3Strlen30(zToken) : 0;
74786   return sqlcipher3ExprAlloc(db, op, &x, 0);
74787 }
74788
74789 /*
74790 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
74791 **
74792 ** If pRoot==NULL that means that a memory allocation error has occurred.
74793 ** In that case, delete the subtrees pLeft and pRight.
74794 */
74795 SQLCIPHER_PRIVATE void sqlcipher3ExprAttachSubtrees(
74796   sqlcipher3 *db,
74797   Expr *pRoot,
74798   Expr *pLeft,
74799   Expr *pRight
74800 ){
74801   if( pRoot==0 ){
74802     assert( db->mallocFailed );
74803     sqlcipher3ExprDelete(db, pLeft);
74804     sqlcipher3ExprDelete(db, pRight);
74805   }else{
74806     if( pRight ){
74807       pRoot->pRight = pRight;
74808       if( pRight->flags & EP_ExpCollate ){
74809         pRoot->flags |= EP_ExpCollate;
74810         pRoot->pColl = pRight->pColl;
74811       }
74812     }
74813     if( pLeft ){
74814       pRoot->pLeft = pLeft;
74815       if( pLeft->flags & EP_ExpCollate ){
74816         pRoot->flags |= EP_ExpCollate;
74817         pRoot->pColl = pLeft->pColl;
74818       }
74819     }
74820     exprSetHeight(pRoot);
74821   }
74822 }
74823
74824 /*
74825 ** Allocate a Expr node which joins as many as two subtrees.
74826 **
74827 ** One or both of the subtrees can be NULL.  Return a pointer to the new
74828 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74829 ** free the subtrees and return NULL.
74830 */
74831 SQLCIPHER_PRIVATE Expr *sqlcipher3PExpr(
74832   Parse *pParse,          /* Parsing context */
74833   int op,                 /* Expression opcode */
74834   Expr *pLeft,            /* Left operand */
74835   Expr *pRight,           /* Right operand */
74836   const Token *pToken     /* Argument token */
74837 ){
74838   Expr *p = sqlcipher3ExprAlloc(pParse->db, op, pToken, 1);
74839   sqlcipher3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74840   if( p ) {
74841     sqlcipher3ExprCheckHeight(pParse, p->nHeight);
74842   }
74843   return p;
74844 }
74845
74846 /*
74847 ** Join two expressions using an AND operator.  If either expression is
74848 ** NULL, then just return the other expression.
74849 */
74850 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprAnd(sqlcipher3 *db, Expr *pLeft, Expr *pRight){
74851   if( pLeft==0 ){
74852     return pRight;
74853   }else if( pRight==0 ){
74854     return pLeft;
74855   }else{
74856     Expr *pNew = sqlcipher3ExprAlloc(db, TK_AND, 0, 0);
74857     sqlcipher3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74858     return pNew;
74859   }
74860 }
74861
74862 /*
74863 ** Construct a new expression node for a function with multiple
74864 ** arguments.
74865 */
74866 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74867   Expr *pNew;
74868   sqlcipher3 *db = pParse->db;
74869   assert( pToken );
74870   pNew = sqlcipher3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74871   if( pNew==0 ){
74872     sqlcipher3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74873     return 0;
74874   }
74875   pNew->x.pList = pList;
74876   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74877   sqlcipher3ExprSetHeight(pParse, pNew);
74878   return pNew;
74879 }
74880
74881 /*
74882 ** Assign a variable number to an expression that encodes a wildcard
74883 ** in the original SQL statement.  
74884 **
74885 ** Wildcards consisting of a single "?" are assigned the next sequential
74886 ** variable number.
74887 **
74888 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74889 ** sure "nnn" is not too be to avoid a denial of service attack when
74890 ** the SQL statement comes from an external source.
74891 **
74892 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74893 ** as the previous instance of the same wildcard.  Or if this is the first
74894 ** instance of the wildcard, the next sequenial variable number is
74895 ** assigned.
74896 */
74897 SQLCIPHER_PRIVATE void sqlcipher3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74898   sqlcipher3 *db = pParse->db;
74899   const char *z;
74900
74901   if( pExpr==0 ) return;
74902   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74903   z = pExpr->u.zToken;
74904   assert( z!=0 );
74905   assert( z[0]!=0 );
74906   if( z[1]==0 ){
74907     /* Wildcard of the form "?".  Assign the next variable number */
74908     assert( z[0]=='?' );
74909     pExpr->iColumn = (ynVar)(++pParse->nVar);
74910   }else{
74911     ynVar x = 0;
74912     u32 n = sqlcipher3Strlen30(z);
74913     if( z[0]=='?' ){
74914       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74915       ** use it as the variable number */
74916       i64 i;
74917       int bOk = 0==sqlcipher3Atoi64(&z[1], &i, n-1, SQLCIPHER_UTF8);
74918       pExpr->iColumn = x = (ynVar)i;
74919       testcase( i==0 );
74920       testcase( i==1 );
74921       testcase( i==db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER]-1 );
74922       testcase( i==db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER] );
74923       if( bOk==0 || i<1 || i>db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER] ){
74924         sqlcipher3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74925             db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER]);
74926         x = 0;
74927       }
74928       if( i>pParse->nVar ){
74929         pParse->nVar = (int)i;
74930       }
74931     }else{
74932       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74933       ** number as the prior appearance of the same name, or if the name
74934       ** has never appeared before, reuse the same variable number
74935       */
74936       ynVar i;
74937       for(i=0; i<pParse->nzVar; i++){
74938         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
74939           pExpr->iColumn = x = (ynVar)i+1;
74940           break;
74941         }
74942       }
74943       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74944     }
74945     if( x>0 ){
74946       if( x>pParse->nzVar ){
74947         char **a;
74948         a = sqlcipher3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
74949         if( a==0 ) return;  /* Error reported through db->mallocFailed */
74950         pParse->azVar = a;
74951         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
74952         pParse->nzVar = x;
74953       }
74954       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
74955         sqlcipher3DbFree(db, pParse->azVar[x-1]);
74956         pParse->azVar[x-1] = sqlcipher3DbStrNDup(db, z, n);
74957       }
74958     }
74959   } 
74960   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER] ){
74961     sqlcipher3ErrorMsg(pParse, "too many SQL variables");
74962   }
74963 }
74964
74965 /*
74966 ** Recursively delete an expression tree.
74967 */
74968 SQLCIPHER_PRIVATE void sqlcipher3ExprDelete(sqlcipher3 *db, Expr *p){
74969   if( p==0 ) return;
74970   /* Sanity check: Assert that the IntValue is non-negative if it exists */
74971   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
74972   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74973     sqlcipher3ExprDelete(db, p->pLeft);
74974     sqlcipher3ExprDelete(db, p->pRight);
74975     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
74976       sqlcipher3DbFree(db, p->u.zToken);
74977     }
74978     if( ExprHasProperty(p, EP_xIsSelect) ){
74979       sqlcipher3SelectDelete(db, p->x.pSelect);
74980     }else{
74981       sqlcipher3ExprListDelete(db, p->x.pList);
74982     }
74983   }
74984   if( !ExprHasProperty(p, EP_Static) ){
74985     sqlcipher3DbFree(db, p);
74986   }
74987 }
74988
74989 /*
74990 ** Return the number of bytes allocated for the expression structure 
74991 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
74992 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
74993 */
74994 static int exprStructSize(Expr *p){
74995   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
74996   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
74997   return EXPR_FULLSIZE;
74998 }
74999
75000 /*
75001 ** The dupedExpr*Size() routines each return the number of bytes required
75002 ** to store a copy of an expression or expression tree.  They differ in
75003 ** how much of the tree is measured.
75004 **
75005 **     dupedExprStructSize()     Size of only the Expr structure 
75006 **     dupedExprNodeSize()       Size of Expr + space for token
75007 **     dupedExprSize()           Expr + token + subtree components
75008 **
75009 ***************************************************************************
75010 **
75011 ** The dupedExprStructSize() function returns two values OR-ed together:  
75012 ** (1) the space required for a copy of the Expr structure only and 
75013 ** (2) the EP_xxx flags that indicate what the structure size should be.
75014 ** The return values is always one of:
75015 **
75016 **      EXPR_FULLSIZE
75017 **      EXPR_REDUCEDSIZE   | EP_Reduced
75018 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
75019 **
75020 ** The size of the structure can be found by masking the return value
75021 ** of this routine with 0xfff.  The flags can be found by masking the
75022 ** return value with EP_Reduced|EP_TokenOnly.
75023 **
75024 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
75025 ** (unreduced) Expr objects as they or originally constructed by the parser.
75026 ** During expression analysis, extra information is computed and moved into
75027 ** later parts of teh Expr object and that extra information might get chopped
75028 ** off if the expression is reduced.  Note also that it does not work to
75029 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
75030 ** to reduce a pristine expression tree from the parser.  The implementation
75031 ** of dupedExprStructSize() contain multiple assert() statements that attempt
75032 ** to enforce this constraint.
75033 */
75034 static int dupedExprStructSize(Expr *p, int flags){
75035   int nSize;
75036   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
75037   if( 0==(flags&EXPRDUP_REDUCE) ){
75038     nSize = EXPR_FULLSIZE;
75039   }else{
75040     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
75041     assert( !ExprHasProperty(p, EP_FromJoin) ); 
75042     assert( (p->flags2 & EP2_MallocedToken)==0 );
75043     assert( (p->flags2 & EP2_Irreducible)==0 );
75044     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
75045       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
75046     }else{
75047       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
75048     }
75049   }
75050   return nSize;
75051 }
75052
75053 /*
75054 ** This function returns the space in bytes required to store the copy 
75055 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
75056 ** string is defined.)
75057 */
75058 static int dupedExprNodeSize(Expr *p, int flags){
75059   int nByte = dupedExprStructSize(p, flags) & 0xfff;
75060   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75061     nByte += sqlcipher3Strlen30(p->u.zToken)+1;
75062   }
75063   return ROUND8(nByte);
75064 }
75065
75066 /*
75067 ** Return the number of bytes required to create a duplicate of the 
75068 ** expression passed as the first argument. The second argument is a
75069 ** mask containing EXPRDUP_XXX flags.
75070 **
75071 ** The value returned includes space to create a copy of the Expr struct
75072 ** itself and the buffer referred to by Expr.u.zToken, if any.
75073 **
75074 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
75075 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
75076 ** and Expr.pRight variables (but not for any structures pointed to or 
75077 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
75078 */
75079 static int dupedExprSize(Expr *p, int flags){
75080   int nByte = 0;
75081   if( p ){
75082     nByte = dupedExprNodeSize(p, flags);
75083     if( flags&EXPRDUP_REDUCE ){
75084       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
75085     }
75086   }
75087   return nByte;
75088 }
75089
75090 /*
75091 ** This function is similar to sqlcipher3ExprDup(), except that if pzBuffer 
75092 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
75093 ** to store the copy of expression p, the copies of p->u.zToken
75094 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
75095 ** if any. Before returning, *pzBuffer is set to the first byte passed the
75096 ** portion of the buffer copied into by this function.
75097 */
75098 static Expr *exprDup(sqlcipher3 *db, Expr *p, int flags, u8 **pzBuffer){
75099   Expr *pNew = 0;                      /* Value to return */
75100   if( p ){
75101     const int isReduced = (flags&EXPRDUP_REDUCE);
75102     u8 *zAlloc;
75103     u32 staticFlag = 0;
75104
75105     assert( pzBuffer==0 || isReduced );
75106
75107     /* Figure out where to write the new Expr structure. */
75108     if( pzBuffer ){
75109       zAlloc = *pzBuffer;
75110       staticFlag = EP_Static;
75111     }else{
75112       zAlloc = sqlcipher3DbMallocRaw(db, dupedExprSize(p, flags));
75113     }
75114     pNew = (Expr *)zAlloc;
75115
75116     if( pNew ){
75117       /* Set nNewSize to the size allocated for the structure pointed to
75118       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
75119       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
75120       ** by the copy of the p->u.zToken string (if any).
75121       */
75122       const unsigned nStructSize = dupedExprStructSize(p, flags);
75123       const int nNewSize = nStructSize & 0xfff;
75124       int nToken;
75125       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75126         nToken = sqlcipher3Strlen30(p->u.zToken) + 1;
75127       }else{
75128         nToken = 0;
75129       }
75130       if( isReduced ){
75131         assert( ExprHasProperty(p, EP_Reduced)==0 );
75132         memcpy(zAlloc, p, nNewSize);
75133       }else{
75134         int nSize = exprStructSize(p);
75135         memcpy(zAlloc, p, nSize);
75136         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
75137       }
75138
75139       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
75140       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
75141       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
75142       pNew->flags |= staticFlag;
75143
75144       /* Copy the p->u.zToken string, if any. */
75145       if( nToken ){
75146         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
75147         memcpy(zToken, p->u.zToken, nToken);
75148       }
75149
75150       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
75151         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
75152         if( ExprHasProperty(p, EP_xIsSelect) ){
75153           pNew->x.pSelect = sqlcipher3SelectDup(db, p->x.pSelect, isReduced);
75154         }else{
75155           pNew->x.pList = sqlcipher3ExprListDup(db, p->x.pList, isReduced);
75156         }
75157       }
75158
75159       /* Fill in pNew->pLeft and pNew->pRight. */
75160       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
75161         zAlloc += dupedExprNodeSize(p, flags);
75162         if( ExprHasProperty(pNew, EP_Reduced) ){
75163           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
75164           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
75165         }
75166         if( pzBuffer ){
75167           *pzBuffer = zAlloc;
75168         }
75169       }else{
75170         pNew->flags2 = 0;
75171         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75172           pNew->pLeft = sqlcipher3ExprDup(db, p->pLeft, 0);
75173           pNew->pRight = sqlcipher3ExprDup(db, p->pRight, 0);
75174         }
75175       }
75176
75177     }
75178   }
75179   return pNew;
75180 }
75181
75182 /*
75183 ** The following group of routines make deep copies of expressions,
75184 ** expression lists, ID lists, and select statements.  The copies can
75185 ** be deleted (by being passed to their respective ...Delete() routines)
75186 ** without effecting the originals.
75187 **
75188 ** The expression list, ID, and source lists return by sqlcipher3ExprListDup(),
75189 ** sqlcipher3IdListDup(), and sqlcipher3SrcListDup() can not be further expanded 
75190 ** by subsequent calls to sqlcipher*ListAppend() routines.
75191 **
75192 ** Any tables that the SrcList might point to are not duplicated.
75193 **
75194 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
75195 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
75196 ** truncated version of the usual Expr structure that will be stored as
75197 ** part of the in-memory representation of the database schema.
75198 */
75199 SQLCIPHER_PRIVATE Expr *sqlcipher3ExprDup(sqlcipher3 *db, Expr *p, int flags){
75200   return exprDup(db, p, flags, 0);
75201 }
75202 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListDup(sqlcipher3 *db, ExprList *p, int flags){
75203   ExprList *pNew;
75204   struct ExprList_item *pItem, *pOldItem;
75205   int i;
75206   if( p==0 ) return 0;
75207   pNew = sqlcipher3DbMallocRaw(db, sizeof(*pNew) );
75208   if( pNew==0 ) return 0;
75209   pNew->iECursor = 0;
75210   pNew->nExpr = pNew->nAlloc = p->nExpr;
75211   pNew->a = pItem = sqlcipher3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
75212   if( pItem==0 ){
75213     sqlcipher3DbFree(db, pNew);
75214     return 0;
75215   } 
75216   pOldItem = p->a;
75217   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
75218     Expr *pOldExpr = pOldItem->pExpr;
75219     pItem->pExpr = sqlcipher3ExprDup(db, pOldExpr, flags);
75220     pItem->zName = sqlcipher3DbStrDup(db, pOldItem->zName);
75221     pItem->zSpan = sqlcipher3DbStrDup(db, pOldItem->zSpan);
75222     pItem->sortOrder = pOldItem->sortOrder;
75223     pItem->done = 0;
75224     pItem->iCol = pOldItem->iCol;
75225     pItem->iAlias = pOldItem->iAlias;
75226   }
75227   return pNew;
75228 }
75229
75230 /*
75231 ** If cursors, triggers, views and subqueries are all omitted from
75232 ** the build, then none of the following routines, except for 
75233 ** sqlcipher3SelectDup(), can be called. sqlcipher3SelectDup() is sometimes
75234 ** called with a NULL argument.
75235 */
75236 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_TRIGGER) \
75237  || !defined(SQLCIPHER_OMIT_SUBQUERY)
75238 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListDup(sqlcipher3 *db, SrcList *p, int flags){
75239   SrcList *pNew;
75240   int i;
75241   int nByte;
75242   if( p==0 ) return 0;
75243   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
75244   pNew = sqlcipher3DbMallocRaw(db, nByte );
75245   if( pNew==0 ) return 0;
75246   pNew->nSrc = pNew->nAlloc = p->nSrc;
75247   for(i=0; i<p->nSrc; i++){
75248     struct SrcList_item *pNewItem = &pNew->a[i];
75249     struct SrcList_item *pOldItem = &p->a[i];
75250     Table *pTab;
75251     pNewItem->zDatabase = sqlcipher3DbStrDup(db, pOldItem->zDatabase);
75252     pNewItem->zName = sqlcipher3DbStrDup(db, pOldItem->zName);
75253     pNewItem->zAlias = sqlcipher3DbStrDup(db, pOldItem->zAlias);
75254     pNewItem->jointype = pOldItem->jointype;
75255     pNewItem->iCursor = pOldItem->iCursor;
75256     pNewItem->addrFillSub = pOldItem->addrFillSub;
75257     pNewItem->regReturn = pOldItem->regReturn;
75258     pNewItem->isCorrelated = pOldItem->isCorrelated;
75259     pNewItem->zIndex = sqlcipher3DbStrDup(db, pOldItem->zIndex);
75260     pNewItem->notIndexed = pOldItem->notIndexed;
75261     pNewItem->pIndex = pOldItem->pIndex;
75262     pTab = pNewItem->pTab = pOldItem->pTab;
75263     if( pTab ){
75264       pTab->nRef++;
75265     }
75266     pNewItem->pSelect = sqlcipher3SelectDup(db, pOldItem->pSelect, flags);
75267     pNewItem->pOn = sqlcipher3ExprDup(db, pOldItem->pOn, flags);
75268     pNewItem->pUsing = sqlcipher3IdListDup(db, pOldItem->pUsing);
75269     pNewItem->colUsed = pOldItem->colUsed;
75270   }
75271   return pNew;
75272 }
75273 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListDup(sqlcipher3 *db, IdList *p){
75274   IdList *pNew;
75275   int i;
75276   if( p==0 ) return 0;
75277   pNew = sqlcipher3DbMallocRaw(db, sizeof(*pNew) );
75278   if( pNew==0 ) return 0;
75279   pNew->nId = pNew->nAlloc = p->nId;
75280   pNew->a = sqlcipher3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
75281   if( pNew->a==0 ){
75282     sqlcipher3DbFree(db, pNew);
75283     return 0;
75284   }
75285   for(i=0; i<p->nId; i++){
75286     struct IdList_item *pNewItem = &pNew->a[i];
75287     struct IdList_item *pOldItem = &p->a[i];
75288     pNewItem->zName = sqlcipher3DbStrDup(db, pOldItem->zName);
75289     pNewItem->idx = pOldItem->idx;
75290   }
75291   return pNew;
75292 }
75293 SQLCIPHER_PRIVATE Select *sqlcipher3SelectDup(sqlcipher3 *db, Select *p, int flags){
75294   Select *pNew;
75295   if( p==0 ) return 0;
75296   pNew = sqlcipher3DbMallocRaw(db, sizeof(*p) );
75297   if( pNew==0 ) return 0;
75298   pNew->pEList = sqlcipher3ExprListDup(db, p->pEList, flags);
75299   pNew->pSrc = sqlcipher3SrcListDup(db, p->pSrc, flags);
75300   pNew->pWhere = sqlcipher3ExprDup(db, p->pWhere, flags);
75301   pNew->pGroupBy = sqlcipher3ExprListDup(db, p->pGroupBy, flags);
75302   pNew->pHaving = sqlcipher3ExprDup(db, p->pHaving, flags);
75303   pNew->pOrderBy = sqlcipher3ExprListDup(db, p->pOrderBy, flags);
75304   pNew->op = p->op;
75305   pNew->pPrior = sqlcipher3SelectDup(db, p->pPrior, flags);
75306   pNew->pLimit = sqlcipher3ExprDup(db, p->pLimit, flags);
75307   pNew->pOffset = sqlcipher3ExprDup(db, p->pOffset, flags);
75308   pNew->iLimit = 0;
75309   pNew->iOffset = 0;
75310   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
75311   pNew->pRightmost = 0;
75312   pNew->addrOpenEphm[0] = -1;
75313   pNew->addrOpenEphm[1] = -1;
75314   pNew->addrOpenEphm[2] = -1;
75315   return pNew;
75316 }
75317 #else
75318 SQLCIPHER_PRIVATE Select *sqlcipher3SelectDup(sqlcipher3 *db, Select *p, int flags){
75319   assert( p==0 );
75320   return 0;
75321 }
75322 #endif
75323
75324
75325 /*
75326 ** Add a new element to the end of an expression list.  If pList is
75327 ** initially NULL, then create a new expression list.
75328 **
75329 ** If a memory allocation error occurs, the entire list is freed and
75330 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
75331 ** that the new entry was successfully appended.
75332 */
75333 SQLCIPHER_PRIVATE ExprList *sqlcipher3ExprListAppend(
75334   Parse *pParse,          /* Parsing context */
75335   ExprList *pList,        /* List to which to append. Might be NULL */
75336   Expr *pExpr             /* Expression to be appended. Might be NULL */
75337 ){
75338   sqlcipher3 *db = pParse->db;
75339   if( pList==0 ){
75340     pList = sqlcipher3DbMallocZero(db, sizeof(ExprList) );
75341     if( pList==0 ){
75342       goto no_mem;
75343     }
75344     assert( pList->nAlloc==0 );
75345   }
75346   if( pList->nAlloc<=pList->nExpr ){
75347     struct ExprList_item *a;
75348     int n = pList->nAlloc*2 + 4;
75349     a = sqlcipher3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
75350     if( a==0 ){
75351       goto no_mem;
75352     }
75353     pList->a = a;
75354     pList->nAlloc = sqlcipher3DbMallocSize(db, a)/sizeof(a[0]);
75355   }
75356   assert( pList->a!=0 );
75357   if( 1 ){
75358     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
75359     memset(pItem, 0, sizeof(*pItem));
75360     pItem->pExpr = pExpr;
75361   }
75362   return pList;
75363
75364 no_mem:     
75365   /* Avoid leaking memory if malloc has failed. */
75366   sqlcipher3ExprDelete(db, pExpr);
75367   sqlcipher3ExprListDelete(db, pList);
75368   return 0;
75369 }
75370
75371 /*
75372 ** Set the ExprList.a[].zName element of the most recently added item
75373 ** on the expression list.
75374 **
75375 ** pList might be NULL following an OOM error.  But pName should never be
75376 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75377 ** is set.
75378 */
75379 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetName(
75380   Parse *pParse,          /* Parsing context */
75381   ExprList *pList,        /* List to which to add the span. */
75382   Token *pName,           /* Name to be added */
75383   int dequote             /* True to cause the name to be dequoted */
75384 ){
75385   assert( pList!=0 || pParse->db->mallocFailed!=0 );
75386   if( pList ){
75387     struct ExprList_item *pItem;
75388     assert( pList->nExpr>0 );
75389     pItem = &pList->a[pList->nExpr-1];
75390     assert( pItem->zName==0 );
75391     pItem->zName = sqlcipher3DbStrNDup(pParse->db, pName->z, pName->n);
75392     if( dequote && pItem->zName ) sqlcipher3Dequote(pItem->zName);
75393   }
75394 }
75395
75396 /*
75397 ** Set the ExprList.a[].zSpan element of the most recently added item
75398 ** on the expression list.
75399 **
75400 ** pList might be NULL following an OOM error.  But pSpan should never be
75401 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75402 ** is set.
75403 */
75404 SQLCIPHER_PRIVATE void sqlcipher3ExprListSetSpan(
75405   Parse *pParse,          /* Parsing context */
75406   ExprList *pList,        /* List to which to add the span. */
75407   ExprSpan *pSpan         /* The span to be added */
75408 ){
75409   sqlcipher3 *db = pParse->db;
75410   assert( pList!=0 || db->mallocFailed!=0 );
75411   if( pList ){
75412     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
75413     assert( pList->nExpr>0 );
75414     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
75415     sqlcipher3DbFree(db, pItem->zSpan);
75416     pItem->zSpan = sqlcipher3DbStrNDup(db, (char*)pSpan->zStart,
75417                                     (int)(pSpan->zEnd - pSpan->zStart));
75418   }
75419 }
75420
75421 /*
75422 ** If the expression list pEList contains more than iLimit elements,
75423 ** leave an error message in pParse.
75424 */
75425 SQLCIPHER_PRIVATE void sqlcipher3ExprListCheckLength(
75426   Parse *pParse,
75427   ExprList *pEList,
75428   const char *zObject
75429 ){
75430   int mx = pParse->db->aLimit[SQLCIPHER_LIMIT_COLUMN];
75431   testcase( pEList && pEList->nExpr==mx );
75432   testcase( pEList && pEList->nExpr==mx+1 );
75433   if( pEList && pEList->nExpr>mx ){
75434     sqlcipher3ErrorMsg(pParse, "too many columns in %s", zObject);
75435   }
75436 }
75437
75438 /*
75439 ** Delete an entire expression list.
75440 */
75441 SQLCIPHER_PRIVATE void sqlcipher3ExprListDelete(sqlcipher3 *db, ExprList *pList){
75442   int i;
75443   struct ExprList_item *pItem;
75444   if( pList==0 ) return;
75445   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
75446   assert( pList->nExpr<=pList->nAlloc );
75447   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
75448     sqlcipher3ExprDelete(db, pItem->pExpr);
75449     sqlcipher3DbFree(db, pItem->zName);
75450     sqlcipher3DbFree(db, pItem->zSpan);
75451   }
75452   sqlcipher3DbFree(db, pList->a);
75453   sqlcipher3DbFree(db, pList);
75454 }
75455
75456 /*
75457 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
75458 ** to an integer.  These routines are checking an expression to see
75459 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
75460 ** not constant.
75461 **
75462 ** These callback routines are used to implement the following:
75463 **
75464 **     sqlcipher3ExprIsConstant()
75465 **     sqlcipher3ExprIsConstantNotJoin()
75466 **     sqlcipher3ExprIsConstantOrFunction()
75467 **
75468 */
75469 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
75470
75471   /* If pWalker->u.i is 3 then any term of the expression that comes from
75472   ** the ON or USING clauses of a join disqualifies the expression
75473   ** from being considered constant. */
75474   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
75475     pWalker->u.i = 0;
75476     return WRC_Abort;
75477   }
75478
75479   switch( pExpr->op ){
75480     /* Consider functions to be constant if all their arguments are constant
75481     ** and pWalker->u.i==2 */
75482     case TK_FUNCTION:
75483       if( pWalker->u.i==2 ) return 0;
75484       /* Fall through */
75485     case TK_ID:
75486     case TK_COLUMN:
75487     case TK_AGG_FUNCTION:
75488     case TK_AGG_COLUMN:
75489       testcase( pExpr->op==TK_ID );
75490       testcase( pExpr->op==TK_COLUMN );
75491       testcase( pExpr->op==TK_AGG_FUNCTION );
75492       testcase( pExpr->op==TK_AGG_COLUMN );
75493       pWalker->u.i = 0;
75494       return WRC_Abort;
75495     default:
75496       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
75497       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
75498       return WRC_Continue;
75499   }
75500 }
75501 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
75502   UNUSED_PARAMETER(NotUsed);
75503   pWalker->u.i = 0;
75504   return WRC_Abort;
75505 }
75506 static int exprIsConst(Expr *p, int initFlag){
75507   Walker w;
75508   w.u.i = initFlag;
75509   w.xExprCallback = exprNodeIsConstant;
75510   w.xSelectCallback = selectNodeIsConstant;
75511   sqlcipher3WalkExpr(&w, p);
75512   return w.u.i;
75513 }
75514
75515 /*
75516 ** Walk an expression tree.  Return 1 if the expression is constant
75517 ** and 0 if it involves variables or function calls.
75518 **
75519 ** For the purposes of this function, a double-quoted string (ex: "abc")
75520 ** is considered a variable but a single-quoted string (ex: 'abc') is
75521 ** a constant.
75522 */
75523 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstant(Expr *p){
75524   return exprIsConst(p, 1);
75525 }
75526
75527 /*
75528 ** Walk an expression tree.  Return 1 if the expression is constant
75529 ** that does no originate from the ON or USING clauses of a join.
75530 ** Return 0 if it involves variables or function calls or terms from
75531 ** an ON or USING clause.
75532 */
75533 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantNotJoin(Expr *p){
75534   return exprIsConst(p, 3);
75535 }
75536
75537 /*
75538 ** Walk an expression tree.  Return 1 if the expression is constant
75539 ** or a function call with constant arguments.  Return and 0 if there
75540 ** are any variables.
75541 **
75542 ** For the purposes of this function, a double-quoted string (ex: "abc")
75543 ** is considered a variable but a single-quoted string (ex: 'abc') is
75544 ** a constant.
75545 */
75546 SQLCIPHER_PRIVATE int sqlcipher3ExprIsConstantOrFunction(Expr *p){
75547   return exprIsConst(p, 2);
75548 }
75549
75550 /*
75551 ** If the expression p codes a constant integer that is small enough
75552 ** to fit in a 32-bit integer, return 1 and put the value of the integer
75553 ** in *pValue.  If the expression is not an integer or if it is too big
75554 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75555 */
75556 SQLCIPHER_PRIVATE int sqlcipher3ExprIsInteger(Expr *p, int *pValue){
75557   int rc = 0;
75558
75559   /* If an expression is an integer literal that fits in a signed 32-bit
75560   ** integer, then the EP_IntValue flag will have already been set */
75561   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75562            || sqlcipher3GetInt32(p->u.zToken, &rc)==0 );
75563
75564   if( p->flags & EP_IntValue ){
75565     *pValue = p->u.iValue;
75566     return 1;
75567   }
75568   switch( p->op ){
75569     case TK_UPLUS: {
75570       rc = sqlcipher3ExprIsInteger(p->pLeft, pValue);
75571       break;
75572     }
75573     case TK_UMINUS: {
75574       int v;
75575       if( sqlcipher3ExprIsInteger(p->pLeft, &v) ){
75576         *pValue = -v;
75577         rc = 1;
75578       }
75579       break;
75580     }
75581     default: break;
75582   }
75583   return rc;
75584 }
75585
75586 /*
75587 ** Return FALSE if there is no chance that the expression can be NULL.
75588 **
75589 ** If the expression might be NULL or if the expression is too complex
75590 ** to tell return TRUE.  
75591 **
75592 ** This routine is used as an optimization, to skip OP_IsNull opcodes
75593 ** when we know that a value cannot be NULL.  Hence, a false positive
75594 ** (returning TRUE when in fact the expression can never be NULL) might
75595 ** be a small performance hit but is otherwise harmless.  On the other
75596 ** hand, a false negative (returning FALSE when the result could be NULL)
75597 ** will likely result in an incorrect answer.  So when in doubt, return
75598 ** TRUE.
75599 */
75600 SQLCIPHER_PRIVATE int sqlcipher3ExprCanBeNull(const Expr *p){
75601   u8 op;
75602   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75603   op = p->op;
75604   if( op==TK_REGISTER ) op = p->op2;
75605   switch( op ){
75606     case TK_INTEGER:
75607     case TK_STRING:
75608     case TK_FLOAT:
75609     case TK_BLOB:
75610       return 0;
75611     default:
75612       return 1;
75613   }
75614 }
75615
75616 /*
75617 ** Generate an OP_IsNull instruction that tests register iReg and jumps
75618 ** to location iDest if the value in iReg is NULL.  The value in iReg 
75619 ** was computed by pExpr.  If we can look at pExpr at compile-time and
75620 ** determine that it can never generate a NULL, then the OP_IsNull operation
75621 ** can be omitted.
75622 */
75623 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeIsNullJump(
75624   Vdbe *v,            /* The VDBE under construction */
75625   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75626   int iReg,           /* Test the value in this register for NULL */
75627   int iDest           /* Jump here if the value is null */
75628 ){
75629   if( sqlcipher3ExprCanBeNull(pExpr) ){
75630     sqlcipher3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75631   }
75632 }
75633
75634 /*
75635 ** Return TRUE if the given expression is a constant which would be
75636 ** unchanged by OP_Affinity with the affinity given in the second
75637 ** argument.
75638 **
75639 ** This routine is used to determine if the OP_Affinity operation
75640 ** can be omitted.  When in doubt return FALSE.  A false negative
75641 ** is harmless.  A false positive, however, can result in the wrong
75642 ** answer.
75643 */
75644 SQLCIPHER_PRIVATE int sqlcipher3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75645   u8 op;
75646   if( aff==SQLCIPHER_AFF_NONE ) return 1;
75647   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75648   op = p->op;
75649   if( op==TK_REGISTER ) op = p->op2;
75650   switch( op ){
75651     case TK_INTEGER: {
75652       return aff==SQLCIPHER_AFF_INTEGER || aff==SQLCIPHER_AFF_NUMERIC;
75653     }
75654     case TK_FLOAT: {
75655       return aff==SQLCIPHER_AFF_REAL || aff==SQLCIPHER_AFF_NUMERIC;
75656     }
75657     case TK_STRING: {
75658       return aff==SQLCIPHER_AFF_TEXT;
75659     }
75660     case TK_BLOB: {
75661       return 1;
75662     }
75663     case TK_COLUMN: {
75664       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75665       return p->iColumn<0
75666           && (aff==SQLCIPHER_AFF_INTEGER || aff==SQLCIPHER_AFF_NUMERIC);
75667     }
75668     default: {
75669       return 0;
75670     }
75671   }
75672 }
75673
75674 /*
75675 ** Return TRUE if the given string is a row-id column name.
75676 */
75677 SQLCIPHER_PRIVATE int sqlcipher3IsRowid(const char *z){
75678   if( sqlcipher3StrICmp(z, "_ROWID_")==0 ) return 1;
75679   if( sqlcipher3StrICmp(z, "ROWID")==0 ) return 1;
75680   if( sqlcipher3StrICmp(z, "OID")==0 ) return 1;
75681   return 0;
75682 }
75683
75684 /*
75685 ** Return true if we are able to the IN operator optimization on a
75686 ** query of the form
75687 **
75688 **       x IN (SELECT ...)
75689 **
75690 ** Where the SELECT... clause is as specified by the parameter to this
75691 ** routine.
75692 **
75693 ** The Select object passed in has already been preprocessed and no
75694 ** errors have been found.
75695 */
75696 #ifndef SQLCIPHER_OMIT_SUBQUERY
75697 static int isCandidateForInOpt(Select *p){
75698   SrcList *pSrc;
75699   ExprList *pEList;
75700   Table *pTab;
75701   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75702   if( p->pPrior ) return 0;              /* Not a compound SELECT */
75703   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75704     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75705     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75706     return 0; /* No DISTINCT keyword and no aggregate functions */
75707   }
75708   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75709   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75710   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75711   if( p->pWhere ) return 0;              /* Has no WHERE clause */
75712   pSrc = p->pSrc;
75713   assert( pSrc!=0 );
75714   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75715   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75716   pTab = pSrc->a[0].pTab;
75717   if( NEVER(pTab==0) ) return 0;
75718   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75719   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75720   pEList = p->pEList;
75721   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75722   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75723   return 1;
75724 }
75725 #endif /* SQLCIPHER_OMIT_SUBQUERY */
75726
75727 /*
75728 ** This function is used by the implementation of the IN (...) operator.
75729 ** It's job is to find or create a b-tree structure that may be used
75730 ** either to test for membership of the (...) set or to iterate through
75731 ** its members, skipping duplicates.
75732 **
75733 ** The index of the cursor opened on the b-tree (database table, database index 
75734 ** or ephermal table) is stored in pX->iTable before this function returns.
75735 ** The returned value of this function indicates the b-tree type, as follows:
75736 **
75737 **   IN_INDEX_ROWID - The cursor was opened on a database table.
75738 **   IN_INDEX_INDEX - The cursor was opened on a database index.
75739 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
75740 **                    populated epheremal table.
75741 **
75742 ** An existing b-tree may only be used if the SELECT is of the simple
75743 ** form:
75744 **
75745 **     SELECT <column> FROM <table>
75746 **
75747 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75748 ** through the set members, skipping any duplicates. In this case an
75749 ** epheremal table must be used unless the selected <column> is guaranteed
75750 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
75751 ** has a UNIQUE constraint or UNIQUE index.
75752 **
75753 ** If the prNotFound parameter is not 0, then the b-tree will be used 
75754 ** for fast set membership tests. In this case an epheremal table must 
75755 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
75756 ** be found with <column> as its left-most column.
75757 **
75758 ** When the b-tree is being used for membership tests, the calling function
75759 ** needs to know whether or not the structure contains an SQL NULL 
75760 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75761 ** If there is any chance that the (...) might contain a NULL value at
75762 ** runtime, then a register is allocated and the register number written
75763 ** to *prNotFound. If there is no chance that the (...) contains a
75764 ** NULL value, then *prNotFound is left unchanged.
75765 **
75766 ** If a register is allocated and its location stored in *prNotFound, then
75767 ** its initial value is NULL.  If the (...) does not remain constant
75768 ** for the duration of the query (i.e. the SELECT within the (...)
75769 ** is a correlated subquery) then the value of the allocated register is
75770 ** reset to NULL each time the subquery is rerun. This allows the
75771 ** caller to use vdbe code equivalent to the following:
75772 **
75773 **   if( register==NULL ){
75774 **     has_null = <test if data structure contains null>
75775 **     register = 1
75776 **   }
75777 **
75778 ** in order to avoid running the <test if data structure contains null>
75779 ** test more often than is necessary.
75780 */
75781 #ifndef SQLCIPHER_OMIT_SUBQUERY
75782 SQLCIPHER_PRIVATE int sqlcipher3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75783   Select *p;                            /* SELECT to the right of IN operator */
75784   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75785   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75786   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75787
75788   assert( pX->op==TK_IN );
75789
75790   /* Check to see if an existing table or index can be used to
75791   ** satisfy the query.  This is preferable to generating a new 
75792   ** ephemeral table.
75793   */
75794   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75795   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75796     sqlcipher3 *db = pParse->db;              /* Database connection */
75797     Vdbe *v = sqlcipher3GetVdbe(pParse);      /* Virtual machine being coded */
75798     Table *pTab;                           /* Table <table>. */
75799     Expr *pExpr;                           /* Expression <column> */
75800     int iCol;                              /* Index of column <column> */
75801     int iDb;                               /* Database idx for pTab */
75802
75803     assert( p );                        /* Because of isCandidateForInOpt(p) */
75804     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75805     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75806     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75807     pTab = p->pSrc->a[0].pTab;
75808     pExpr = p->pEList->a[0].pExpr;
75809     iCol = pExpr->iColumn;
75810    
75811     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75812     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
75813     sqlcipher3CodeVerifySchema(pParse, iDb);
75814     sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75815
75816     /* This function is only called from two places. In both cases the vdbe
75817     ** has already been allocated. So assume sqlcipher3GetVdbe() is always
75818     ** successful here.
75819     */
75820     assert(v);
75821     if( iCol<0 ){
75822       int iMem = ++pParse->nMem;
75823       int iAddr;
75824
75825       iAddr = sqlcipher3VdbeAddOp1(v, OP_Once, iMem);
75826
75827       sqlcipher3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75828       eType = IN_INDEX_ROWID;
75829
75830       sqlcipher3VdbeJumpHere(v, iAddr);
75831     }else{
75832       Index *pIdx;                         /* Iterator variable */
75833
75834       /* The collation sequence used by the comparison. If an index is to
75835       ** be used in place of a temp-table, it must be ordered according
75836       ** to this collation sequence.  */
75837       CollSeq *pReq = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75838
75839       /* Check that the affinity that will be used to perform the 
75840       ** comparison is the same as the affinity of the column. If
75841       ** it is not, it is not possible to use any index.
75842       */
75843       char aff = comparisonAffinity(pX);
75844       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLCIPHER_AFF_NONE);
75845
75846       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75847         if( (pIdx->aiColumn[0]==iCol)
75848          && sqlcipher3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75849          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75850         ){
75851           int iMem = ++pParse->nMem;
75852           int iAddr;
75853           char *pKey;
75854   
75855           pKey = (char *)sqlcipher3IndexKeyinfo(pParse, pIdx);
75856           iAddr = sqlcipher3VdbeAddOp1(v, OP_Once, iMem);
75857   
75858           sqlcipher3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75859                                pKey,P4_KEYINFO_HANDOFF);
75860           VdbeComment((v, "%s", pIdx->zName));
75861           eType = IN_INDEX_INDEX;
75862
75863           sqlcipher3VdbeJumpHere(v, iAddr);
75864           if( prNotFound && !pTab->aCol[iCol].notNull ){
75865             *prNotFound = ++pParse->nMem;
75866           }
75867         }
75868       }
75869     }
75870   }
75871
75872   if( eType==0 ){
75873     /* Could not found an existing table or index to use as the RHS b-tree.
75874     ** We will have to generate an ephemeral table to do the job.
75875     */
75876     double savedNQueryLoop = pParse->nQueryLoop;
75877     int rMayHaveNull = 0;
75878     eType = IN_INDEX_EPH;
75879     if( prNotFound ){
75880       *prNotFound = rMayHaveNull = ++pParse->nMem;
75881     }else{
75882       testcase( pParse->nQueryLoop>(double)1 );
75883       pParse->nQueryLoop = (double)1;
75884       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75885         eType = IN_INDEX_ROWID;
75886       }
75887     }
75888     sqlcipher3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75889     pParse->nQueryLoop = savedNQueryLoop;
75890   }else{
75891     pX->iTable = iTab;
75892   }
75893   return eType;
75894 }
75895 #endif
75896
75897 /*
75898 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75899 ** or IN operators.  Examples:
75900 **
75901 **     (SELECT a FROM b)          -- subquery
75902 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75903 **     x IN (4,5,11)              -- IN operator with list on right-hand side
75904 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75905 **
75906 ** The pExpr parameter describes the expression that contains the IN
75907 ** operator or subquery.
75908 **
75909 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75910 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75911 ** to some integer key column of a table B-Tree. In this case, use an
75912 ** intkey B-Tree to store the set of IN(...) values instead of the usual
75913 ** (slower) variable length keys B-Tree.
75914 **
75915 ** If rMayHaveNull is non-zero, that means that the operation is an IN
75916 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75917 ** Furthermore, the IN is in a WHERE clause and that we really want
75918 ** to iterate over the RHS of the IN operator in order to quickly locate
75919 ** all corresponding LHS elements.  All this routine does is initialize
75920 ** the register given by rMayHaveNull to NULL.  Calling routines will take
75921 ** care of changing this register value to non-NULL if the RHS is NULL-free.
75922 **
75923 ** If rMayHaveNull is zero, that means that the subquery is being used
75924 ** for membership testing only.  There is no need to initialize any
75925 ** registers to indicate the presense or absence of NULLs on the RHS.
75926 **
75927 ** For a SELECT or EXISTS operator, return the register that holds the
75928 ** result.  For IN operators or if an error occurs, the return value is 0.
75929 */
75930 #ifndef SQLCIPHER_OMIT_SUBQUERY
75931 SQLCIPHER_PRIVATE int sqlcipher3CodeSubselect(
75932   Parse *pParse,          /* Parsing context */
75933   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
75934   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
75935   int isRowid             /* If true, LHS of IN operator is a rowid */
75936 ){
75937   int testAddr = -1;                      /* One-time test address */
75938   int rReg = 0;                           /* Register storing resulting */
75939   Vdbe *v = sqlcipher3GetVdbe(pParse);
75940   if( NEVER(v==0) ) return 0;
75941   sqlcipher3ExprCachePush(pParse);
75942
75943   /* This code must be run in its entirety every time it is encountered
75944   ** if any of the following is true:
75945   **
75946   **    *  The right-hand side is a correlated subquery
75947   **    *  The right-hand side is an expression list containing variables
75948   **    *  We are inside a trigger
75949   **
75950   ** If all of the above are false, then we can run this code just once
75951   ** save the results, and reuse the same result on subsequent invocations.
75952   */
75953   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
75954     int mem = ++pParse->nMem;
75955     testAddr = sqlcipher3VdbeAddOp1(v, OP_Once, mem);
75956   }
75957
75958 #ifndef SQLCIPHER_OMIT_EXPLAIN
75959   if( pParse->explain==2 ){
75960     char *zMsg = sqlcipher3MPrintf(
75961         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
75962         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
75963     );
75964     sqlcipher3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
75965   }
75966 #endif
75967
75968   switch( pExpr->op ){
75969     case TK_IN: {
75970       char affinity;              /* Affinity of the LHS of the IN */
75971       KeyInfo keyInfo;            /* Keyinfo for the generated table */
75972       int addr;                   /* Address of OP_OpenEphemeral instruction */
75973       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
75974
75975       if( rMayHaveNull ){
75976         sqlcipher3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
75977       }
75978
75979       affinity = sqlcipher3ExprAffinity(pLeft);
75980
75981       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
75982       ** expression it is handled the same way.  An ephemeral table is 
75983       ** filled with single-field index keys representing the results
75984       ** from the SELECT or the <exprlist>.
75985       **
75986       ** If the 'x' expression is a column value, or the SELECT...
75987       ** statement returns a column value, then the affinity of that
75988       ** column is used to build the index keys. If both 'x' and the
75989       ** SELECT... statement are columns, then numeric affinity is used
75990       ** if either column has NUMERIC or INTEGER affinity. If neither
75991       ** 'x' nor the SELECT... statement are columns, then numeric affinity
75992       ** is used.
75993       */
75994       pExpr->iTable = pParse->nTab++;
75995       addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
75996       if( rMayHaveNull==0 ) sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
75997       memset(&keyInfo, 0, sizeof(keyInfo));
75998       keyInfo.nField = 1;
75999
76000       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76001         /* Case 1:     expr IN (SELECT ...)
76002         **
76003         ** Generate code to write the results of the select into the temporary
76004         ** table allocated and opened above.
76005         */
76006         SelectDest dest;
76007         ExprList *pEList;
76008
76009         assert( !isRowid );
76010         sqlcipher3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
76011         dest.affinity = (u8)affinity;
76012         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
76013         pExpr->x.pSelect->iLimit = 0;
76014         if( sqlcipher3Select(pParse, pExpr->x.pSelect, &dest) ){
76015           return 0;
76016         }
76017         pEList = pExpr->x.pSelect->pEList;
76018         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
76019           keyInfo.aColl[0] = sqlcipher3BinaryCompareCollSeq(pParse, pExpr->pLeft,
76020               pEList->a[0].pExpr);
76021         }
76022       }else if( ALWAYS(pExpr->x.pList!=0) ){
76023         /* Case 2:     expr IN (exprlist)
76024         **
76025         ** For each expression, build an index key from the evaluation and
76026         ** store it in the temporary table. If <expr> is a column, then use
76027         ** that columns affinity when building index keys. If <expr> is not
76028         ** a column, use numeric affinity.
76029         */
76030         int i;
76031         ExprList *pList = pExpr->x.pList;
76032         struct ExprList_item *pItem;
76033         int r1, r2, r3;
76034
76035         if( !affinity ){
76036           affinity = SQLCIPHER_AFF_NONE;
76037         }
76038         keyInfo.aColl[0] = sqlcipher3ExprCollSeq(pParse, pExpr->pLeft);
76039
76040         /* Loop through each expression in <exprlist>. */
76041         r1 = sqlcipher3GetTempReg(pParse);
76042         r2 = sqlcipher3GetTempReg(pParse);
76043         sqlcipher3VdbeAddOp2(v, OP_Null, 0, r2);
76044         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
76045           Expr *pE2 = pItem->pExpr;
76046           int iValToIns;
76047
76048           /* If the expression is not constant then we will need to
76049           ** disable the test that was generated above that makes sure
76050           ** this code only executes once.  Because for a non-constant
76051           ** expression we need to rerun this code each time.
76052           */
76053           if( testAddr>=0 && !sqlcipher3ExprIsConstant(pE2) ){
76054             sqlcipher3VdbeChangeToNoop(v, testAddr);
76055             testAddr = -1;
76056           }
76057
76058           /* Evaluate the expression and insert it into the temp table */
76059           if( isRowid && sqlcipher3ExprIsInteger(pE2, &iValToIns) ){
76060             sqlcipher3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
76061           }else{
76062             r3 = sqlcipher3ExprCodeTarget(pParse, pE2, r1);
76063             if( isRowid ){
76064               sqlcipher3VdbeAddOp2(v, OP_MustBeInt, r3,
76065                                 sqlcipher3VdbeCurrentAddr(v)+2);
76066               sqlcipher3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
76067             }else{
76068               sqlcipher3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
76069               sqlcipher3ExprCacheAffinityChange(pParse, r3, 1);
76070               sqlcipher3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
76071             }
76072           }
76073         }
76074         sqlcipher3ReleaseTempReg(pParse, r1);
76075         sqlcipher3ReleaseTempReg(pParse, r2);
76076       }
76077       if( !isRowid ){
76078         sqlcipher3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
76079       }
76080       break;
76081     }
76082
76083     case TK_EXISTS:
76084     case TK_SELECT:
76085     default: {
76086       /* If this has to be a scalar SELECT.  Generate code to put the
76087       ** value of this select in a memory cell and record the number
76088       ** of the memory cell in iColumn.  If this is an EXISTS, write
76089       ** an integer 0 (not exists) or 1 (exists) into a memory cell
76090       ** and record that memory cell in iColumn.
76091       */
76092       Select *pSel;                         /* SELECT statement to encode */
76093       SelectDest dest;                      /* How to deal with SELECt result */
76094
76095       testcase( pExpr->op==TK_EXISTS );
76096       testcase( pExpr->op==TK_SELECT );
76097       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
76098
76099       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
76100       pSel = pExpr->x.pSelect;
76101       sqlcipher3SelectDestInit(&dest, 0, ++pParse->nMem);
76102       if( pExpr->op==TK_SELECT ){
76103         dest.eDest = SRT_Mem;
76104         sqlcipher3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
76105         VdbeComment((v, "Init subquery result"));
76106       }else{
76107         dest.eDest = SRT_Exists;
76108         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
76109         VdbeComment((v, "Init EXISTS result"));
76110       }
76111       sqlcipher3ExprDelete(pParse->db, pSel->pLimit);
76112       pSel->pLimit = sqlcipher3PExpr(pParse, TK_INTEGER, 0, 0,
76113                                   &sqlcipher3IntTokens[1]);
76114       pSel->iLimit = 0;
76115       if( sqlcipher3Select(pParse, pSel, &dest) ){
76116         return 0;
76117       }
76118       rReg = dest.iParm;
76119       ExprSetIrreducible(pExpr);
76120       break;
76121     }
76122   }
76123
76124   if( testAddr>=0 ){
76125     sqlcipher3VdbeJumpHere(v, testAddr);
76126   }
76127   sqlcipher3ExprCachePop(pParse, 1);
76128
76129   return rReg;
76130 }
76131 #endif /* SQLCIPHER_OMIT_SUBQUERY */
76132
76133 #ifndef SQLCIPHER_OMIT_SUBQUERY
76134 /*
76135 ** Generate code for an IN expression.
76136 **
76137 **      x IN (SELECT ...)
76138 **      x IN (value, value, ...)
76139 **
76140 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
76141 ** is an array of zero or more values.  The expression is true if the LHS is
76142 ** contained within the RHS.  The value of the expression is unknown (NULL)
76143 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
76144 ** RHS contains one or more NULL values.
76145 **
76146 ** This routine generates code will jump to destIfFalse if the LHS is not 
76147 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
76148 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
76149 ** within the RHS then fall through.
76150 */
76151 static void sqlcipher3ExprCodeIN(
76152   Parse *pParse,        /* Parsing and code generating context */
76153   Expr *pExpr,          /* The IN expression */
76154   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
76155   int destIfNull        /* Jump here if the results are unknown due to NULLs */
76156 ){
76157   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
76158   char affinity;        /* Comparison affinity to use */
76159   int eType;            /* Type of the RHS */
76160   int r1;               /* Temporary use register */
76161   Vdbe *v;              /* Statement under construction */
76162
76163   /* Compute the RHS.   After this step, the table with cursor
76164   ** pExpr->iTable will contains the values that make up the RHS.
76165   */
76166   v = pParse->pVdbe;
76167   assert( v!=0 );       /* OOM detected prior to this routine */
76168   VdbeNoopComment((v, "begin IN expr"));
76169   eType = sqlcipher3FindInIndex(pParse, pExpr, &rRhsHasNull);
76170
76171   /* Figure out the affinity to use to create a key from the results
76172   ** of the expression. affinityStr stores a static string suitable for
76173   ** P4 of OP_MakeRecord.
76174   */
76175   affinity = comparisonAffinity(pExpr);
76176
76177   /* Code the LHS, the <expr> from "<expr> IN (...)".
76178   */
76179   sqlcipher3ExprCachePush(pParse);
76180   r1 = sqlcipher3GetTempReg(pParse);
76181   sqlcipher3ExprCode(pParse, pExpr->pLeft, r1);
76182
76183   /* If the LHS is NULL, then the result is either false or NULL depending
76184   ** on whether the RHS is empty or not, respectively.
76185   */
76186   if( destIfNull==destIfFalse ){
76187     /* Shortcut for the common case where the false and NULL outcomes are
76188     ** the same. */
76189     sqlcipher3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
76190   }else{
76191     int addr1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, r1);
76192     sqlcipher3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
76193     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
76194     sqlcipher3VdbeJumpHere(v, addr1);
76195   }
76196
76197   if( eType==IN_INDEX_ROWID ){
76198     /* In this case, the RHS is the ROWID of table b-tree
76199     */
76200     sqlcipher3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
76201     sqlcipher3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
76202   }else{
76203     /* In this case, the RHS is an index b-tree.
76204     */
76205     sqlcipher3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
76206
76207     /* If the set membership test fails, then the result of the 
76208     ** "x IN (...)" expression must be either 0 or NULL. If the set
76209     ** contains no NULL values, then the result is 0. If the set 
76210     ** contains one or more NULL values, then the result of the
76211     ** expression is also NULL.
76212     */
76213     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
76214       /* This branch runs if it is known at compile time that the RHS
76215       ** cannot contain NULL values. This happens as the result
76216       ** of a "NOT NULL" constraint in the database schema.
76217       **
76218       ** Also run this branch if NULL is equivalent to FALSE
76219       ** for this particular IN operator.
76220       */
76221       sqlcipher3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
76222
76223     }else{
76224       /* In this branch, the RHS of the IN might contain a NULL and
76225       ** the presence of a NULL on the RHS makes a difference in the
76226       ** outcome.
76227       */
76228       int j1, j2, j3;
76229
76230       /* First check to see if the LHS is contained in the RHS.  If so,
76231       ** then the presence of NULLs in the RHS does not matter, so jump
76232       ** over all of the code that follows.
76233       */
76234       j1 = sqlcipher3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
76235
76236       /* Here we begin generating code that runs if the LHS is not
76237       ** contained within the RHS.  Generate additional code that
76238       ** tests the RHS for NULLs.  If the RHS contains a NULL then
76239       ** jump to destIfNull.  If there are no NULLs in the RHS then
76240       ** jump to destIfFalse.
76241       */
76242       j2 = sqlcipher3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
76243       j3 = sqlcipher3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
76244       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
76245       sqlcipher3VdbeJumpHere(v, j3);
76246       sqlcipher3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
76247       sqlcipher3VdbeJumpHere(v, j2);
76248
76249       /* Jump to the appropriate target depending on whether or not
76250       ** the RHS contains a NULL
76251       */
76252       sqlcipher3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
76253       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
76254
76255       /* The OP_Found at the top of this branch jumps here when true, 
76256       ** causing the overall IN expression evaluation to fall through.
76257       */
76258       sqlcipher3VdbeJumpHere(v, j1);
76259     }
76260   }
76261   sqlcipher3ReleaseTempReg(pParse, r1);
76262   sqlcipher3ExprCachePop(pParse, 1);
76263   VdbeComment((v, "end IN expr"));
76264 }
76265 #endif /* SQLCIPHER_OMIT_SUBQUERY */
76266
76267 /*
76268 ** Duplicate an 8-byte value
76269 */
76270 static char *dup8bytes(Vdbe *v, const char *in){
76271   char *out = sqlcipher3DbMallocRaw(sqlcipher3VdbeDb(v), 8);
76272   if( out ){
76273     memcpy(out, in, 8);
76274   }
76275   return out;
76276 }
76277
76278 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
76279 /*
76280 ** Generate an instruction that will put the floating point
76281 ** value described by z[0..n-1] into register iMem.
76282 **
76283 ** The z[] string will probably not be zero-terminated.  But the 
76284 ** z[n] character is guaranteed to be something that does not look
76285 ** like the continuation of the number.
76286 */
76287 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
76288   if( ALWAYS(z!=0) ){
76289     double value;
76290     char *zV;
76291     sqlcipher3AtoF(z, &value, sqlcipher3Strlen30(z), SQLCIPHER_UTF8);
76292     assert( !sqlcipher3IsNaN(value) ); /* The new AtoF never returns NaN */
76293     if( negateFlag ) value = -value;
76294     zV = dup8bytes(v, (char*)&value);
76295     sqlcipher3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
76296   }
76297 }
76298 #endif
76299
76300
76301 /*
76302 ** Generate an instruction that will put the integer describe by
76303 ** text z[0..n-1] into register iMem.
76304 **
76305 ** Expr.u.zToken is always UTF8 and zero-terminated.
76306 */
76307 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
76308   Vdbe *v = pParse->pVdbe;
76309   if( pExpr->flags & EP_IntValue ){
76310     int i = pExpr->u.iValue;
76311     assert( i>=0 );
76312     if( negFlag ) i = -i;
76313     sqlcipher3VdbeAddOp2(v, OP_Integer, i, iMem);
76314   }else{
76315     int c;
76316     i64 value;
76317     const char *z = pExpr->u.zToken;
76318     assert( z!=0 );
76319     c = sqlcipher3Atoi64(z, &value, sqlcipher3Strlen30(z), SQLCIPHER_UTF8);
76320     if( c==0 || (c==2 && negFlag) ){
76321       char *zV;
76322       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
76323       zV = dup8bytes(v, (char*)&value);
76324       sqlcipher3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
76325     }else{
76326 #ifdef SQLCIPHER_OMIT_FLOATING_POINT
76327       sqlcipher3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
76328 #else
76329       codeReal(v, z, negFlag, iMem);
76330 #endif
76331     }
76332   }
76333 }
76334
76335 /*
76336 ** Clear a cache entry.
76337 */
76338 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
76339   if( p->tempReg ){
76340     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76341       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
76342     }
76343     p->tempReg = 0;
76344   }
76345 }
76346
76347
76348 /*
76349 ** Record in the column cache that a particular column from a
76350 ** particular table is stored in a particular register.
76351 */
76352 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
76353   int i;
76354   int minLru;
76355   int idxLru;
76356   struct yColCache *p;
76357
76358   assert( iReg>0 );  /* Register numbers are always positive */
76359   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
76360
76361   /* The SQLCIPHER_ColumnCache flag disables the column cache.  This is used
76362   ** for testing only - to verify that SQLite always gets the same answer
76363   ** with and without the column cache.
76364   */
76365   if( pParse->db->flags & SQLCIPHER_ColumnCache ) return;
76366
76367   /* First replace any existing entry.
76368   **
76369   ** Actually, the way the column cache is currently used, we are guaranteed
76370   ** that the object will never already be in cache.  Verify this guarantee.
76371   */
76372 #ifndef NDEBUG
76373   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76374 #if 0 /* This code wold remove the entry from the cache if it existed */
76375     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
76376       cacheEntryClear(pParse, p);
76377       p->iLevel = pParse->iCacheLevel;
76378       p->iReg = iReg;
76379       p->lru = pParse->iCacheCnt++;
76380       return;
76381     }
76382 #endif
76383     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
76384   }
76385 #endif
76386
76387   /* Find an empty slot and replace it */
76388   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76389     if( p->iReg==0 ){
76390       p->iLevel = pParse->iCacheLevel;
76391       p->iTable = iTab;
76392       p->iColumn = iCol;
76393       p->iReg = iReg;
76394       p->tempReg = 0;
76395       p->lru = pParse->iCacheCnt++;
76396       return;
76397     }
76398   }
76399
76400   /* Replace the last recently used */
76401   minLru = 0x7fffffff;
76402   idxLru = -1;
76403   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76404     if( p->lru<minLru ){
76405       idxLru = i;
76406       minLru = p->lru;
76407     }
76408   }
76409   if( ALWAYS(idxLru>=0) ){
76410     p = &pParse->aColCache[idxLru];
76411     p->iLevel = pParse->iCacheLevel;
76412     p->iTable = iTab;
76413     p->iColumn = iCol;
76414     p->iReg = iReg;
76415     p->tempReg = 0;
76416     p->lru = pParse->iCacheCnt++;
76417     return;
76418   }
76419 }
76420
76421 /*
76422 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
76423 ** Purge the range of registers from the column cache.
76424 */
76425 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
76426   int i;
76427   int iLast = iReg + nReg - 1;
76428   struct yColCache *p;
76429   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76430     int r = p->iReg;
76431     if( r>=iReg && r<=iLast ){
76432       cacheEntryClear(pParse, p);
76433       p->iReg = 0;
76434     }
76435   }
76436 }
76437
76438 /*
76439 ** Remember the current column cache context.  Any new entries added
76440 ** added to the column cache after this call are removed when the
76441 ** corresponding pop occurs.
76442 */
76443 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePush(Parse *pParse){
76444   pParse->iCacheLevel++;
76445 }
76446
76447 /*
76448 ** Remove from the column cache any entries that were added since the
76449 ** the previous N Push operations.  In other words, restore the cache
76450 ** to the state it was in N Pushes ago.
76451 */
76452 SQLCIPHER_PRIVATE void sqlcipher3ExprCachePop(Parse *pParse, int N){
76453   int i;
76454   struct yColCache *p;
76455   assert( N>0 );
76456   assert( pParse->iCacheLevel>=N );
76457   pParse->iCacheLevel -= N;
76458   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76459     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
76460       cacheEntryClear(pParse, p);
76461       p->iReg = 0;
76462     }
76463   }
76464 }
76465
76466 /*
76467 ** When a cached column is reused, make sure that its register is
76468 ** no longer available as a temp register.  ticket #3879:  that same
76469 ** register might be in the cache in multiple places, so be sure to
76470 ** get them all.
76471 */
76472 static void sqlcipher3ExprCachePinRegister(Parse *pParse, int iReg){
76473   int i;
76474   struct yColCache *p;
76475   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76476     if( p->iReg==iReg ){
76477       p->tempReg = 0;
76478     }
76479   }
76480 }
76481
76482 /*
76483 ** Generate code to extract the value of the iCol-th column of a table.
76484 */
76485 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeGetColumnOfTable(
76486   Vdbe *v,        /* The VDBE under construction */
76487   Table *pTab,    /* The table containing the value */
76488   int iTabCur,    /* The cursor for this table */
76489   int iCol,       /* Index of the column to extract */
76490   int regOut      /* Extract the valud into this register */
76491 ){
76492   if( iCol<0 || iCol==pTab->iPKey ){
76493     sqlcipher3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
76494   }else{
76495     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
76496     sqlcipher3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
76497   }
76498   if( iCol>=0 ){
76499     sqlcipher3ColumnDefault(v, pTab, iCol, regOut);
76500   }
76501 }
76502
76503 /*
76504 ** Generate code that will extract the iColumn-th column from
76505 ** table pTab and store the column value in a register.  An effort
76506 ** is made to store the column value in register iReg, but this is
76507 ** not guaranteed.  The location of the column value is returned.
76508 **
76509 ** There must be an open cursor to pTab in iTable when this routine
76510 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
76511 */
76512 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeGetColumn(
76513   Parse *pParse,   /* Parsing and code generating context */
76514   Table *pTab,     /* Description of the table we are reading from */
76515   int iColumn,     /* Index of the table column */
76516   int iTable,      /* The cursor pointing to the table */
76517   int iReg         /* Store results here */
76518 ){
76519   Vdbe *v = pParse->pVdbe;
76520   int i;
76521   struct yColCache *p;
76522
76523   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76524     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76525       p->lru = pParse->iCacheCnt++;
76526       sqlcipher3ExprCachePinRegister(pParse, p->iReg);
76527       return p->iReg;
76528     }
76529   }  
76530   assert( v!=0 );
76531   sqlcipher3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76532   sqlcipher3ExprCacheStore(pParse, iTable, iColumn, iReg);
76533   return iReg;
76534 }
76535
76536 /*
76537 ** Clear all column cache entries.
76538 */
76539 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheClear(Parse *pParse){
76540   int i;
76541   struct yColCache *p;
76542
76543   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76544     if( p->iReg ){
76545       cacheEntryClear(pParse, p);
76546       p->iReg = 0;
76547     }
76548   }
76549 }
76550
76551 /*
76552 ** Record the fact that an affinity change has occurred on iCount
76553 ** registers starting with iStart.
76554 */
76555 SQLCIPHER_PRIVATE void sqlcipher3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76556   sqlcipher3ExprCacheRemove(pParse, iStart, iCount);
76557 }
76558
76559 /*
76560 ** Generate code to move content from registers iFrom...iFrom+nReg-1
76561 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76562 */
76563 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76564   int i;
76565   struct yColCache *p;
76566   if( NEVER(iFrom==iTo) ) return;
76567   sqlcipher3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
76568   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76569     int x = p->iReg;
76570     if( x>=iFrom && x<iFrom+nReg ){
76571       p->iReg += iTo-iFrom;
76572     }
76573   }
76574 }
76575
76576 /*
76577 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
76578 ** over to iTo..iTo+nReg-1.
76579 */
76580 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
76581   int i;
76582   if( NEVER(iFrom==iTo) ) return;
76583   for(i=0; i<nReg; i++){
76584     sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
76585   }
76586 }
76587
76588 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
76589 /*
76590 ** Return true if any register in the range iFrom..iTo (inclusive)
76591 ** is used as part of the column cache.
76592 **
76593 ** This routine is used within assert() and testcase() macros only
76594 ** and does not appear in a normal build.
76595 */
76596 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76597   int i;
76598   struct yColCache *p;
76599   for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
76600     int r = p->iReg;
76601     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76602   }
76603   return 0;
76604 }
76605 #endif /* SQLCIPHER_DEBUG || SQLCIPHER_COVERAGE_TEST */
76606
76607 /*
76608 ** Generate code into the current Vdbe to evaluate the given
76609 ** expression.  Attempt to store the results in register "target".
76610 ** Return the register where results are stored.
76611 **
76612 ** With this routine, there is no guarantee that results will
76613 ** be stored in target.  The result might be stored in some other
76614 ** register if it is convenient to do so.  The calling function
76615 ** must check the return code and move the results to the desired
76616 ** register.
76617 */
76618 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76619   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76620   int op;                   /* The opcode being coded */
76621   int inReg = target;       /* Results stored in register inReg */
76622   int regFree1 = 0;         /* If non-zero free this temporary register */
76623   int regFree2 = 0;         /* If non-zero free this temporary register */
76624   int r1, r2, r3, r4;       /* Various register numbers */
76625   sqlcipher3 *db = pParse->db; /* The database connection */
76626
76627   assert( target>0 && target<=pParse->nMem );
76628   if( v==0 ){
76629     assert( pParse->db->mallocFailed );
76630     return 0;
76631   }
76632
76633   if( pExpr==0 ){
76634     op = TK_NULL;
76635   }else{
76636     op = pExpr->op;
76637   }
76638   switch( op ){
76639     case TK_AGG_COLUMN: {
76640       AggInfo *pAggInfo = pExpr->pAggInfo;
76641       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76642       if( !pAggInfo->directMode ){
76643         assert( pCol->iMem>0 );
76644         inReg = pCol->iMem;
76645         break;
76646       }else if( pAggInfo->useSortingIdx ){
76647         sqlcipher3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76648                               pCol->iSorterColumn, target);
76649         break;
76650       }
76651       /* Otherwise, fall thru into the TK_COLUMN case */
76652     }
76653     case TK_COLUMN: {
76654       if( pExpr->iTable<0 ){
76655         /* This only happens when coding check constraints */
76656         assert( pParse->ckBase>0 );
76657         inReg = pExpr->iColumn + pParse->ckBase;
76658       }else{
76659         inReg = sqlcipher3ExprCodeGetColumn(pParse, pExpr->pTab,
76660                                  pExpr->iColumn, pExpr->iTable, target);
76661       }
76662       break;
76663     }
76664     case TK_INTEGER: {
76665       codeInteger(pParse, pExpr, 0, target);
76666       break;
76667     }
76668 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
76669     case TK_FLOAT: {
76670       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76671       codeReal(v, pExpr->u.zToken, 0, target);
76672       break;
76673     }
76674 #endif
76675     case TK_STRING: {
76676       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76677       sqlcipher3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76678       break;
76679     }
76680     case TK_NULL: {
76681       sqlcipher3VdbeAddOp2(v, OP_Null, 0, target);
76682       break;
76683     }
76684 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
76685     case TK_BLOB: {
76686       int n;
76687       const char *z;
76688       char *zBlob;
76689       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76690       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76691       assert( pExpr->u.zToken[1]=='\'' );
76692       z = &pExpr->u.zToken[2];
76693       n = sqlcipher3Strlen30(z) - 1;
76694       assert( z[n]=='\'' );
76695       zBlob = sqlcipher3HexToBlob(sqlcipher3VdbeDb(v), z, n);
76696       sqlcipher3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76697       break;
76698     }
76699 #endif
76700     case TK_VARIABLE: {
76701       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76702       assert( pExpr->u.zToken!=0 );
76703       assert( pExpr->u.zToken[0]!=0 );
76704       sqlcipher3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76705       if( pExpr->u.zToken[1]!=0 ){
76706         assert( pExpr->u.zToken[0]=='?' 
76707              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76708         sqlcipher3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76709       }
76710       break;
76711     }
76712     case TK_REGISTER: {
76713       inReg = pExpr->iTable;
76714       break;
76715     }
76716     case TK_AS: {
76717       inReg = sqlcipher3ExprCodeTarget(pParse, pExpr->pLeft, target);
76718       break;
76719     }
76720 #ifndef SQLCIPHER_OMIT_CAST
76721     case TK_CAST: {
76722       /* Expressions of the form:   CAST(pLeft AS token) */
76723       int aff, to_op;
76724       inReg = sqlcipher3ExprCodeTarget(pParse, pExpr->pLeft, target);
76725       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76726       aff = sqlcipher3AffinityType(pExpr->u.zToken);
76727       to_op = aff - SQLCIPHER_AFF_TEXT + OP_ToText;
76728       assert( to_op==OP_ToText    || aff!=SQLCIPHER_AFF_TEXT    );
76729       assert( to_op==OP_ToBlob    || aff!=SQLCIPHER_AFF_NONE    );
76730       assert( to_op==OP_ToNumeric || aff!=SQLCIPHER_AFF_NUMERIC );
76731       assert( to_op==OP_ToInt     || aff!=SQLCIPHER_AFF_INTEGER );
76732       assert( to_op==OP_ToReal    || aff!=SQLCIPHER_AFF_REAL    );
76733       testcase( to_op==OP_ToText );
76734       testcase( to_op==OP_ToBlob );
76735       testcase( to_op==OP_ToNumeric );
76736       testcase( to_op==OP_ToInt );
76737       testcase( to_op==OP_ToReal );
76738       if( inReg!=target ){
76739         sqlcipher3VdbeAddOp2(v, OP_SCopy, inReg, target);
76740         inReg = target;
76741       }
76742       sqlcipher3VdbeAddOp1(v, to_op, inReg);
76743       testcase( usedAsColumnCache(pParse, inReg, inReg) );
76744       sqlcipher3ExprCacheAffinityChange(pParse, inReg, 1);
76745       break;
76746     }
76747 #endif /* SQLCIPHER_OMIT_CAST */
76748     case TK_LT:
76749     case TK_LE:
76750     case TK_GT:
76751     case TK_GE:
76752     case TK_NE:
76753     case TK_EQ: {
76754       assert( TK_LT==OP_Lt );
76755       assert( TK_LE==OP_Le );
76756       assert( TK_GT==OP_Gt );
76757       assert( TK_GE==OP_Ge );
76758       assert( TK_EQ==OP_Eq );
76759       assert( TK_NE==OP_Ne );
76760       testcase( op==TK_LT );
76761       testcase( op==TK_LE );
76762       testcase( op==TK_GT );
76763       testcase( op==TK_GE );
76764       testcase( op==TK_EQ );
76765       testcase( op==TK_NE );
76766       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76767       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76768       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76769                   r1, r2, inReg, SQLCIPHER_STOREP2);
76770       testcase( regFree1==0 );
76771       testcase( regFree2==0 );
76772       break;
76773     }
76774     case TK_IS:
76775     case TK_ISNOT: {
76776       testcase( op==TK_IS );
76777       testcase( op==TK_ISNOT );
76778       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76779       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76780       op = (op==TK_IS) ? TK_EQ : TK_NE;
76781       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76782                   r1, r2, inReg, SQLCIPHER_STOREP2 | SQLCIPHER_NULLEQ);
76783       testcase( regFree1==0 );
76784       testcase( regFree2==0 );
76785       break;
76786     }
76787     case TK_AND:
76788     case TK_OR:
76789     case TK_PLUS:
76790     case TK_STAR:
76791     case TK_MINUS:
76792     case TK_REM:
76793     case TK_BITAND:
76794     case TK_BITOR:
76795     case TK_SLASH:
76796     case TK_LSHIFT:
76797     case TK_RSHIFT: 
76798     case TK_CONCAT: {
76799       assert( TK_AND==OP_And );
76800       assert( TK_OR==OP_Or );
76801       assert( TK_PLUS==OP_Add );
76802       assert( TK_MINUS==OP_Subtract );
76803       assert( TK_REM==OP_Remainder );
76804       assert( TK_BITAND==OP_BitAnd );
76805       assert( TK_BITOR==OP_BitOr );
76806       assert( TK_SLASH==OP_Divide );
76807       assert( TK_LSHIFT==OP_ShiftLeft );
76808       assert( TK_RSHIFT==OP_ShiftRight );
76809       assert( TK_CONCAT==OP_Concat );
76810       testcase( op==TK_AND );
76811       testcase( op==TK_OR );
76812       testcase( op==TK_PLUS );
76813       testcase( op==TK_MINUS );
76814       testcase( op==TK_REM );
76815       testcase( op==TK_BITAND );
76816       testcase( op==TK_BITOR );
76817       testcase( op==TK_SLASH );
76818       testcase( op==TK_LSHIFT );
76819       testcase( op==TK_RSHIFT );
76820       testcase( op==TK_CONCAT );
76821       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76822       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76823       sqlcipher3VdbeAddOp3(v, op, r2, r1, target);
76824       testcase( regFree1==0 );
76825       testcase( regFree2==0 );
76826       break;
76827     }
76828     case TK_UMINUS: {
76829       Expr *pLeft = pExpr->pLeft;
76830       assert( pLeft );
76831       if( pLeft->op==TK_INTEGER ){
76832         codeInteger(pParse, pLeft, 1, target);
76833 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
76834       }else if( pLeft->op==TK_FLOAT ){
76835         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76836         codeReal(v, pLeft->u.zToken, 1, target);
76837 #endif
76838       }else{
76839         regFree1 = r1 = sqlcipher3GetTempReg(pParse);
76840         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, r1);
76841         r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76842         sqlcipher3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76843         testcase( regFree2==0 );
76844       }
76845       inReg = target;
76846       break;
76847     }
76848     case TK_BITNOT:
76849     case TK_NOT: {
76850       assert( TK_BITNOT==OP_BitNot );
76851       assert( TK_NOT==OP_Not );
76852       testcase( op==TK_BITNOT );
76853       testcase( op==TK_NOT );
76854       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76855       testcase( regFree1==0 );
76856       inReg = target;
76857       sqlcipher3VdbeAddOp2(v, op, r1, inReg);
76858       break;
76859     }
76860     case TK_ISNULL:
76861     case TK_NOTNULL: {
76862       int addr;
76863       assert( TK_ISNULL==OP_IsNull );
76864       assert( TK_NOTNULL==OP_NotNull );
76865       testcase( op==TK_ISNULL );
76866       testcase( op==TK_NOTNULL );
76867       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, target);
76868       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76869       testcase( regFree1==0 );
76870       addr = sqlcipher3VdbeAddOp1(v, op, r1);
76871       sqlcipher3VdbeAddOp2(v, OP_AddImm, target, -1);
76872       sqlcipher3VdbeJumpHere(v, addr);
76873       break;
76874     }
76875     case TK_AGG_FUNCTION: {
76876       AggInfo *pInfo = pExpr->pAggInfo;
76877       if( pInfo==0 ){
76878         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76879         sqlcipher3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76880       }else{
76881         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76882       }
76883       break;
76884     }
76885     case TK_CONST_FUNC:
76886     case TK_FUNCTION: {
76887       ExprList *pFarg;       /* List of function arguments */
76888       int nFarg;             /* Number of function arguments */
76889       FuncDef *pDef;         /* The function definition object */
76890       int nId;               /* Length of the function name in bytes */
76891       const char *zId;       /* The function name */
76892       int constMask = 0;     /* Mask of function arguments that are constant */
76893       int i;                 /* Loop counter */
76894       u8 enc = ENC(db);      /* The text encoding used by this database */
76895       CollSeq *pColl = 0;    /* A collating sequence */
76896
76897       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76898       testcase( op==TK_CONST_FUNC );
76899       testcase( op==TK_FUNCTION );
76900       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76901         pFarg = 0;
76902       }else{
76903         pFarg = pExpr->x.pList;
76904       }
76905       nFarg = pFarg ? pFarg->nExpr : 0;
76906       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76907       zId = pExpr->u.zToken;
76908       nId = sqlcipher3Strlen30(zId);
76909       pDef = sqlcipher3FindFunction(db, zId, nId, nFarg, enc, 0);
76910       if( pDef==0 ){
76911         sqlcipher3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76912         break;
76913       }
76914
76915       /* Attempt a direct implementation of the built-in COALESCE() and
76916       ** IFNULL() functions.  This avoids unnecessary evalation of
76917       ** arguments past the first non-NULL argument.
76918       */
76919       if( pDef->flags & SQLCIPHER_FUNC_COALESCE ){
76920         int endCoalesce = sqlcipher3VdbeMakeLabel(v);
76921         assert( nFarg>=2 );
76922         sqlcipher3ExprCode(pParse, pFarg->a[0].pExpr, target);
76923         for(i=1; i<nFarg; i++){
76924           sqlcipher3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76925           sqlcipher3ExprCacheRemove(pParse, target, 1);
76926           sqlcipher3ExprCachePush(pParse);
76927           sqlcipher3ExprCode(pParse, pFarg->a[i].pExpr, target);
76928           sqlcipher3ExprCachePop(pParse, 1);
76929         }
76930         sqlcipher3VdbeResolveLabel(v, endCoalesce);
76931         break;
76932       }
76933
76934
76935       if( pFarg ){
76936         r1 = sqlcipher3GetTempRange(pParse, nFarg);
76937         sqlcipher3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
76938         sqlcipher3ExprCodeExprList(pParse, pFarg, r1, 1);
76939         sqlcipher3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
76940       }else{
76941         r1 = 0;
76942       }
76943 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
76944       /* Possibly overload the function if the first argument is
76945       ** a virtual table column.
76946       **
76947       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
76948       ** second argument, not the first, as the argument to test to
76949       ** see if it is a column in a virtual table.  This is done because
76950       ** the left operand of infix functions (the operand we want to
76951       ** control overloading) ends up as the second argument to the
76952       ** function.  The expression "A glob B" is equivalent to 
76953       ** "glob(B,A).  We want to use the A in "A glob B" to test
76954       ** for function overloading.  But we use the B term in "glob(B,A)".
76955       */
76956       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
76957         pDef = sqlcipher3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
76958       }else if( nFarg>0 ){
76959         pDef = sqlcipher3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
76960       }
76961 #endif
76962       for(i=0; i<nFarg; i++){
76963         if( i<32 && sqlcipher3ExprIsConstant(pFarg->a[i].pExpr) ){
76964           constMask |= (1<<i);
76965         }
76966         if( (pDef->flags & SQLCIPHER_FUNC_NEEDCOLL)!=0 && !pColl ){
76967           pColl = sqlcipher3ExprCollSeq(pParse, pFarg->a[i].pExpr);
76968         }
76969       }
76970       if( pDef->flags & SQLCIPHER_FUNC_NEEDCOLL ){
76971         if( !pColl ) pColl = db->pDfltColl; 
76972         sqlcipher3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
76973       }
76974       sqlcipher3VdbeAddOp4(v, OP_Function, constMask, r1, target,
76975                         (char*)pDef, P4_FUNCDEF);
76976       sqlcipher3VdbeChangeP5(v, (u8)nFarg);
76977       if( nFarg ){
76978         sqlcipher3ReleaseTempRange(pParse, r1, nFarg);
76979       }
76980       break;
76981     }
76982 #ifndef SQLCIPHER_OMIT_SUBQUERY
76983     case TK_EXISTS:
76984     case TK_SELECT: {
76985       testcase( op==TK_EXISTS );
76986       testcase( op==TK_SELECT );
76987       inReg = sqlcipher3CodeSubselect(pParse, pExpr, 0, 0);
76988       break;
76989     }
76990     case TK_IN: {
76991       int destIfFalse = sqlcipher3VdbeMakeLabel(v);
76992       int destIfNull = sqlcipher3VdbeMakeLabel(v);
76993       sqlcipher3VdbeAddOp2(v, OP_Null, 0, target);
76994       sqlcipher3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76995       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, target);
76996       sqlcipher3VdbeResolveLabel(v, destIfFalse);
76997       sqlcipher3VdbeAddOp2(v, OP_AddImm, target, 0);
76998       sqlcipher3VdbeResolveLabel(v, destIfNull);
76999       break;
77000     }
77001 #endif /* SQLCIPHER_OMIT_SUBQUERY */
77002
77003
77004     /*
77005     **    x BETWEEN y AND z
77006     **
77007     ** This is equivalent to
77008     **
77009     **    x>=y AND x<=z
77010     **
77011     ** X is stored in pExpr->pLeft.
77012     ** Y is stored in pExpr->pList->a[0].pExpr.
77013     ** Z is stored in pExpr->pList->a[1].pExpr.
77014     */
77015     case TK_BETWEEN: {
77016       Expr *pLeft = pExpr->pLeft;
77017       struct ExprList_item *pLItem = pExpr->x.pList->a;
77018       Expr *pRight = pLItem->pExpr;
77019
77020       r1 = sqlcipher3ExprCodeTemp(pParse, pLeft, &regFree1);
77021       r2 = sqlcipher3ExprCodeTemp(pParse, pRight, &regFree2);
77022       testcase( regFree1==0 );
77023       testcase( regFree2==0 );
77024       r3 = sqlcipher3GetTempReg(pParse);
77025       r4 = sqlcipher3GetTempReg(pParse);
77026       codeCompare(pParse, pLeft, pRight, OP_Ge,
77027                   r1, r2, r3, SQLCIPHER_STOREP2);
77028       pLItem++;
77029       pRight = pLItem->pExpr;
77030       sqlcipher3ReleaseTempReg(pParse, regFree2);
77031       r2 = sqlcipher3ExprCodeTemp(pParse, pRight, &regFree2);
77032       testcase( regFree2==0 );
77033       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLCIPHER_STOREP2);
77034       sqlcipher3VdbeAddOp3(v, OP_And, r3, r4, target);
77035       sqlcipher3ReleaseTempReg(pParse, r3);
77036       sqlcipher3ReleaseTempReg(pParse, r4);
77037       break;
77038     }
77039     case TK_UPLUS: {
77040       inReg = sqlcipher3ExprCodeTarget(pParse, pExpr->pLeft, target);
77041       break;
77042     }
77043
77044     case TK_TRIGGER: {
77045       /* If the opcode is TK_TRIGGER, then the expression is a reference
77046       ** to a column in the new.* or old.* pseudo-tables available to
77047       ** trigger programs. In this case Expr.iTable is set to 1 for the
77048       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77049       ** is set to the column of the pseudo-table to read, or to -1 to
77050       ** read the rowid field.
77051       **
77052       ** The expression is implemented using an OP_Param opcode. The p1
77053       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
77054       ** to reference another column of the old.* pseudo-table, where 
77055       ** i is the index of the column. For a new.rowid reference, p1 is
77056       ** set to (n+1), where n is the number of columns in each pseudo-table.
77057       ** For a reference to any other column in the new.* pseudo-table, p1
77058       ** is set to (n+2+i), where n and i are as defined previously. For
77059       ** example, if the table on which triggers are being fired is
77060       ** declared as:
77061       **
77062       **   CREATE TABLE t1(a, b);
77063       **
77064       ** Then p1 is interpreted as follows:
77065       **
77066       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
77067       **   p1==1   ->    old.a         p1==4   ->    new.a
77068       **   p1==2   ->    old.b         p1==5   ->    new.b       
77069       */
77070       Table *pTab = pExpr->pTab;
77071       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
77072
77073       assert( pExpr->iTable==0 || pExpr->iTable==1 );
77074       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
77075       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
77076       assert( p1>=0 && p1<(pTab->nCol*2+2) );
77077
77078       sqlcipher3VdbeAddOp2(v, OP_Param, p1, target);
77079       VdbeComment((v, "%s.%s -> $%d",
77080         (pExpr->iTable ? "new" : "old"),
77081         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
77082         target
77083       ));
77084
77085 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
77086       /* If the column has REAL affinity, it may currently be stored as an
77087       ** integer. Use OP_RealAffinity to make sure it is really real.  */
77088       if( pExpr->iColumn>=0 
77089        && pTab->aCol[pExpr->iColumn].affinity==SQLCIPHER_AFF_REAL
77090       ){
77091         sqlcipher3VdbeAddOp1(v, OP_RealAffinity, target);
77092       }
77093 #endif
77094       break;
77095     }
77096
77097
77098     /*
77099     ** Form A:
77100     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77101     **
77102     ** Form B:
77103     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77104     **
77105     ** Form A is can be transformed into the equivalent form B as follows:
77106     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
77107     **        WHEN x=eN THEN rN ELSE y END
77108     **
77109     ** X (if it exists) is in pExpr->pLeft.
77110     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
77111     ** ELSE clause and no other term matches, then the result of the
77112     ** exprssion is NULL.
77113     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
77114     **
77115     ** The result of the expression is the Ri for the first matching Ei,
77116     ** or if there is no matching Ei, the ELSE term Y, or if there is
77117     ** no ELSE term, NULL.
77118     */
77119     default: assert( op==TK_CASE ); {
77120       int endLabel;                     /* GOTO label for end of CASE stmt */
77121       int nextCase;                     /* GOTO label for next WHEN clause */
77122       int nExpr;                        /* 2x number of WHEN terms */
77123       int i;                            /* Loop counter */
77124       ExprList *pEList;                 /* List of WHEN terms */
77125       struct ExprList_item *aListelem;  /* Array of WHEN terms */
77126       Expr opCompare;                   /* The X==Ei expression */
77127       Expr cacheX;                      /* Cached expression X */
77128       Expr *pX;                         /* The X expression */
77129       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
77130       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
77131
77132       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
77133       assert((pExpr->x.pList->nExpr % 2) == 0);
77134       assert(pExpr->x.pList->nExpr > 0);
77135       pEList = pExpr->x.pList;
77136       aListelem = pEList->a;
77137       nExpr = pEList->nExpr;
77138       endLabel = sqlcipher3VdbeMakeLabel(v);
77139       if( (pX = pExpr->pLeft)!=0 ){
77140         cacheX = *pX;
77141         testcase( pX->op==TK_COLUMN );
77142         testcase( pX->op==TK_REGISTER );
77143         cacheX.iTable = sqlcipher3ExprCodeTemp(pParse, pX, &regFree1);
77144         testcase( regFree1==0 );
77145         cacheX.op = TK_REGISTER;
77146         opCompare.op = TK_EQ;
77147         opCompare.pLeft = &cacheX;
77148         pTest = &opCompare;
77149         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
77150         ** The value in regFree1 might get SCopy-ed into the file result.
77151         ** So make sure that the regFree1 register is not reused for other
77152         ** purposes and possibly overwritten.  */
77153         regFree1 = 0;
77154       }
77155       for(i=0; i<nExpr; i=i+2){
77156         sqlcipher3ExprCachePush(pParse);
77157         if( pX ){
77158           assert( pTest!=0 );
77159           opCompare.pRight = aListelem[i].pExpr;
77160         }else{
77161           pTest = aListelem[i].pExpr;
77162         }
77163         nextCase = sqlcipher3VdbeMakeLabel(v);
77164         testcase( pTest->op==TK_COLUMN );
77165         sqlcipher3ExprIfFalse(pParse, pTest, nextCase, SQLCIPHER_JUMPIFNULL);
77166         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
77167         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
77168         sqlcipher3ExprCode(pParse, aListelem[i+1].pExpr, target);
77169         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, endLabel);
77170         sqlcipher3ExprCachePop(pParse, 1);
77171         sqlcipher3VdbeResolveLabel(v, nextCase);
77172       }
77173       if( pExpr->pRight ){
77174         sqlcipher3ExprCachePush(pParse);
77175         sqlcipher3ExprCode(pParse, pExpr->pRight, target);
77176         sqlcipher3ExprCachePop(pParse, 1);
77177       }else{
77178         sqlcipher3VdbeAddOp2(v, OP_Null, 0, target);
77179       }
77180       assert( db->mallocFailed || pParse->nErr>0 
77181            || pParse->iCacheLevel==iCacheLevel );
77182       sqlcipher3VdbeResolveLabel(v, endLabel);
77183       break;
77184     }
77185 #ifndef SQLCIPHER_OMIT_TRIGGER
77186     case TK_RAISE: {
77187       assert( pExpr->affinity==OE_Rollback 
77188            || pExpr->affinity==OE_Abort
77189            || pExpr->affinity==OE_Fail
77190            || pExpr->affinity==OE_Ignore
77191       );
77192       if( !pParse->pTriggerTab ){
77193         sqlcipher3ErrorMsg(pParse,
77194                        "RAISE() may only be used within a trigger-program");
77195         return 0;
77196       }
77197       if( pExpr->affinity==OE_Abort ){
77198         sqlcipher3MayAbort(pParse);
77199       }
77200       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77201       if( pExpr->affinity==OE_Ignore ){
77202         sqlcipher3VdbeAddOp4(
77203             v, OP_Halt, SQLCIPHER_OK, OE_Ignore, 0, pExpr->u.zToken,0);
77204       }else{
77205         sqlcipher3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
77206       }
77207
77208       break;
77209     }
77210 #endif
77211   }
77212   sqlcipher3ReleaseTempReg(pParse, regFree1);
77213   sqlcipher3ReleaseTempReg(pParse, regFree2);
77214   return inReg;
77215 }
77216
77217 /*
77218 ** Generate code to evaluate an expression and store the results
77219 ** into a register.  Return the register number where the results
77220 ** are stored.
77221 **
77222 ** If the register is a temporary register that can be deallocated,
77223 ** then write its number into *pReg.  If the result register is not
77224 ** a temporary, then set *pReg to zero.
77225 */
77226 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
77227   int r1 = sqlcipher3GetTempReg(pParse);
77228   int r2 = sqlcipher3ExprCodeTarget(pParse, pExpr, r1);
77229   if( r2==r1 ){
77230     *pReg = r1;
77231   }else{
77232     sqlcipher3ReleaseTempReg(pParse, r1);
77233     *pReg = 0;
77234   }
77235   return r2;
77236 }
77237
77238 /*
77239 ** Generate code that will evaluate expression pExpr and store the
77240 ** results in register target.  The results are guaranteed to appear
77241 ** in register target.
77242 */
77243 SQLCIPHER_PRIVATE int sqlcipher3ExprCode(Parse *pParse, Expr *pExpr, int target){
77244   int inReg;
77245
77246   assert( target>0 && target<=pParse->nMem );
77247   if( pExpr && pExpr->op==TK_REGISTER ){
77248     sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
77249   }else{
77250     inReg = sqlcipher3ExprCodeTarget(pParse, pExpr, target);
77251     assert( pParse->pVdbe || pParse->db->mallocFailed );
77252     if( inReg!=target && pParse->pVdbe ){
77253       sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
77254     }
77255   }
77256   return target;
77257 }
77258
77259 /*
77260 ** Generate code that evalutes the given expression and puts the result
77261 ** in register target.
77262 **
77263 ** Also make a copy of the expression results into another "cache" register
77264 ** and modify the expression so that the next time it is evaluated,
77265 ** the result is a copy of the cache register.
77266 **
77267 ** This routine is used for expressions that are used multiple 
77268 ** times.  They are evaluated once and the results of the expression
77269 ** are reused.
77270 */
77271 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
77272   Vdbe *v = pParse->pVdbe;
77273   int inReg;
77274   inReg = sqlcipher3ExprCode(pParse, pExpr, target);
77275   assert( target>0 );
77276   /* This routine is called for terms to INSERT or UPDATE.  And the only
77277   ** other place where expressions can be converted into TK_REGISTER is
77278   ** in WHERE clause processing.  So as currently implemented, there is
77279   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
77280   ** keep the ALWAYS() in case the conditions above change with future
77281   ** modifications or enhancements. */
77282   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
77283     int iMem;
77284     iMem = ++pParse->nMem;
77285     sqlcipher3VdbeAddOp2(v, OP_Copy, inReg, iMem);
77286     pExpr->iTable = iMem;
77287     pExpr->op2 = pExpr->op;
77288     pExpr->op = TK_REGISTER;
77289   }
77290   return inReg;
77291 }
77292
77293 /*
77294 ** Return TRUE if pExpr is an constant expression that is appropriate
77295 ** for factoring out of a loop.  Appropriate expressions are:
77296 **
77297 **    *  Any expression that evaluates to two or more opcodes.
77298 **
77299 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
77300 **       or OP_Variable that does not need to be placed in a 
77301 **       specific register.
77302 **
77303 ** There is no point in factoring out single-instruction constant
77304 ** expressions that need to be placed in a particular register.  
77305 ** We could factor them out, but then we would end up adding an
77306 ** OP_SCopy instruction to move the value into the correct register
77307 ** later.  We might as well just use the original instruction and
77308 ** avoid the OP_SCopy.
77309 */
77310 static int isAppropriateForFactoring(Expr *p){
77311   if( !sqlcipher3ExprIsConstantNotJoin(p) ){
77312     return 0;  /* Only constant expressions are appropriate for factoring */
77313   }
77314   if( (p->flags & EP_FixedDest)==0 ){
77315     return 1;  /* Any constant without a fixed destination is appropriate */
77316   }
77317   while( p->op==TK_UPLUS ) p = p->pLeft;
77318   switch( p->op ){
77319 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
77320     case TK_BLOB:
77321 #endif
77322     case TK_VARIABLE:
77323     case TK_INTEGER:
77324     case TK_FLOAT:
77325     case TK_NULL:
77326     case TK_STRING: {
77327       testcase( p->op==TK_BLOB );
77328       testcase( p->op==TK_VARIABLE );
77329       testcase( p->op==TK_INTEGER );
77330       testcase( p->op==TK_FLOAT );
77331       testcase( p->op==TK_NULL );
77332       testcase( p->op==TK_STRING );
77333       /* Single-instruction constants with a fixed destination are
77334       ** better done in-line.  If we factor them, they will just end
77335       ** up generating an OP_SCopy to move the value to the destination
77336       ** register. */
77337       return 0;
77338     }
77339     case TK_UMINUS: {
77340       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77341         return 0;
77342       }
77343       break;
77344     }
77345     default: {
77346       break;
77347     }
77348   }
77349   return 1;
77350 }
77351
77352 /*
77353 ** If pExpr is a constant expression that is appropriate for
77354 ** factoring out of a loop, then evaluate the expression
77355 ** into a register and convert the expression into a TK_REGISTER
77356 ** expression.
77357 */
77358 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77359   Parse *pParse = pWalker->pParse;
77360   switch( pExpr->op ){
77361     case TK_IN:
77362     case TK_REGISTER: {
77363       return WRC_Prune;
77364     }
77365     case TK_FUNCTION:
77366     case TK_AGG_FUNCTION:
77367     case TK_CONST_FUNC: {
77368       /* The arguments to a function have a fixed destination.
77369       ** Mark them this way to avoid generated unneeded OP_SCopy
77370       ** instructions. 
77371       */
77372       ExprList *pList = pExpr->x.pList;
77373       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77374       if( pList ){
77375         int i = pList->nExpr;
77376         struct ExprList_item *pItem = pList->a;
77377         for(; i>0; i--, pItem++){
77378           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77379         }
77380       }
77381       break;
77382     }
77383   }
77384   if( isAppropriateForFactoring(pExpr) ){
77385     int r1 = ++pParse->nMem;
77386     int r2;
77387     r2 = sqlcipher3ExprCodeTarget(pParse, pExpr, r1);
77388     if( NEVER(r1!=r2) ) sqlcipher3ReleaseTempReg(pParse, r1);
77389     pExpr->op2 = pExpr->op;
77390     pExpr->op = TK_REGISTER;
77391     pExpr->iTable = r2;
77392     return WRC_Prune;
77393   }
77394   return WRC_Continue;
77395 }
77396
77397 /*
77398 ** Preevaluate constant subexpressions within pExpr and store the
77399 ** results in registers.  Modify pExpr so that the constant subexpresions
77400 ** are TK_REGISTER opcodes that refer to the precomputed values.
77401 **
77402 ** This routine is a no-op if the jump to the cookie-check code has
77403 ** already occur.  Since the cookie-check jump is generated prior to
77404 ** any other serious processing, this check ensures that there is no
77405 ** way to accidently bypass the constant initializations.
77406 **
77407 ** This routine is also a no-op if the SQLCIPHER_FactorOutConst optimization
77408 ** is disabled via the sqlcipher3_test_control(SQLCIPHER_TESTCTRL_OPTIMIZATIONS)
77409 ** interface.  This allows test logic to verify that the same answer is
77410 ** obtained for queries regardless of whether or not constants are
77411 ** precomputed into registers or if they are inserted in-line.
77412 */
77413 SQLCIPHER_PRIVATE void sqlcipher3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77414   Walker w;
77415   if( pParse->cookieGoto ) return;
77416   if( (pParse->db->flags & SQLCIPHER_FactorOutConst)!=0 ) return;
77417   w.xExprCallback = evalConstExpr;
77418   w.xSelectCallback = 0;
77419   w.pParse = pParse;
77420   sqlcipher3WalkExpr(&w, pExpr);
77421 }
77422
77423
77424 /*
77425 ** Generate code that pushes the value of every element of the given
77426 ** expression list into a sequence of registers beginning at target.
77427 **
77428 ** Return the number of elements evaluated.
77429 */
77430 SQLCIPHER_PRIVATE int sqlcipher3ExprCodeExprList(
77431   Parse *pParse,     /* Parsing context */
77432   ExprList *pList,   /* The expression list to be coded */
77433   int target,        /* Where to write results */
77434   int doHardCopy     /* Make a hard copy of every element */
77435 ){
77436   struct ExprList_item *pItem;
77437   int i, n;
77438   assert( pList!=0 );
77439   assert( target>0 );
77440   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77441   n = pList->nExpr;
77442   for(pItem=pList->a, i=0; i<n; i++, pItem++){
77443     Expr *pExpr = pItem->pExpr;
77444     int inReg = sqlcipher3ExprCodeTarget(pParse, pExpr, target+i);
77445     if( inReg!=target+i ){
77446       sqlcipher3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77447                         inReg, target+i);
77448     }
77449   }
77450   return n;
77451 }
77452
77453 /*
77454 ** Generate code for a BETWEEN operator.
77455 **
77456 **    x BETWEEN y AND z
77457 **
77458 ** The above is equivalent to 
77459 **
77460 **    x>=y AND x<=z
77461 **
77462 ** Code it as such, taking care to do the common subexpression
77463 ** elementation of x.
77464 */
77465 static void exprCodeBetween(
77466   Parse *pParse,    /* Parsing and code generating context */
77467   Expr *pExpr,      /* The BETWEEN expression */
77468   int dest,         /* Jump here if the jump is taken */
77469   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77470   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77471 ){
77472   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77473   Expr compLeft;    /* The  x>=y  term */
77474   Expr compRight;   /* The  x<=z  term */
77475   Expr exprX;       /* The  x  subexpression */
77476   int regFree1 = 0; /* Temporary use register */
77477
77478   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77479   exprX = *pExpr->pLeft;
77480   exprAnd.op = TK_AND;
77481   exprAnd.pLeft = &compLeft;
77482   exprAnd.pRight = &compRight;
77483   compLeft.op = TK_GE;
77484   compLeft.pLeft = &exprX;
77485   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77486   compRight.op = TK_LE;
77487   compRight.pLeft = &exprX;
77488   compRight.pRight = pExpr->x.pList->a[1].pExpr;
77489   exprX.iTable = sqlcipher3ExprCodeTemp(pParse, &exprX, &regFree1);
77490   exprX.op = TK_REGISTER;
77491   if( jumpIfTrue ){
77492     sqlcipher3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77493   }else{
77494     sqlcipher3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77495   }
77496   sqlcipher3ReleaseTempReg(pParse, regFree1);
77497
77498   /* Ensure adequate test coverage */
77499   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77500   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77501   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77502   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77503   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77504   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77505   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77506   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77507 }
77508
77509 /*
77510 ** Generate code for a boolean expression such that a jump is made
77511 ** to the label "dest" if the expression is true but execution
77512 ** continues straight thru if the expression is false.
77513 **
77514 ** If the expression evaluates to NULL (neither true nor false), then
77515 ** take the jump if the jumpIfNull flag is SQLCIPHER_JUMPIFNULL.
77516 **
77517 ** This code depends on the fact that certain token values (ex: TK_EQ)
77518 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77519 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77520 ** the make process cause these values to align.  Assert()s in the code
77521 ** below verify that the numbers are aligned correctly.
77522 */
77523 SQLCIPHER_PRIVATE void sqlcipher3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77524   Vdbe *v = pParse->pVdbe;
77525   int op = 0;
77526   int regFree1 = 0;
77527   int regFree2 = 0;
77528   int r1, r2;
77529
77530   assert( jumpIfNull==SQLCIPHER_JUMPIFNULL || jumpIfNull==0 );
77531   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
77532   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77533   op = pExpr->op;
77534   switch( op ){
77535     case TK_AND: {
77536       int d2 = sqlcipher3VdbeMakeLabel(v);
77537       testcase( jumpIfNull==0 );
77538       sqlcipher3ExprCachePush(pParse);
77539       sqlcipher3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLCIPHER_JUMPIFNULL);
77540       sqlcipher3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77541       sqlcipher3VdbeResolveLabel(v, d2);
77542       sqlcipher3ExprCachePop(pParse, 1);
77543       break;
77544     }
77545     case TK_OR: {
77546       testcase( jumpIfNull==0 );
77547       sqlcipher3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77548       sqlcipher3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77549       break;
77550     }
77551     case TK_NOT: {
77552       testcase( jumpIfNull==0 );
77553       sqlcipher3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77554       break;
77555     }
77556     case TK_LT:
77557     case TK_LE:
77558     case TK_GT:
77559     case TK_GE:
77560     case TK_NE:
77561     case TK_EQ: {
77562       assert( TK_LT==OP_Lt );
77563       assert( TK_LE==OP_Le );
77564       assert( TK_GT==OP_Gt );
77565       assert( TK_GE==OP_Ge );
77566       assert( TK_EQ==OP_Eq );
77567       assert( TK_NE==OP_Ne );
77568       testcase( op==TK_LT );
77569       testcase( op==TK_LE );
77570       testcase( op==TK_GT );
77571       testcase( op==TK_GE );
77572       testcase( op==TK_EQ );
77573       testcase( op==TK_NE );
77574       testcase( jumpIfNull==0 );
77575       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77576       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77577       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77578                   r1, r2, dest, jumpIfNull);
77579       testcase( regFree1==0 );
77580       testcase( regFree2==0 );
77581       break;
77582     }
77583     case TK_IS:
77584     case TK_ISNOT: {
77585       testcase( op==TK_IS );
77586       testcase( op==TK_ISNOT );
77587       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77588       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77589       op = (op==TK_IS) ? TK_EQ : TK_NE;
77590       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77591                   r1, r2, dest, SQLCIPHER_NULLEQ);
77592       testcase( regFree1==0 );
77593       testcase( regFree2==0 );
77594       break;
77595     }
77596     case TK_ISNULL:
77597     case TK_NOTNULL: {
77598       assert( TK_ISNULL==OP_IsNull );
77599       assert( TK_NOTNULL==OP_NotNull );
77600       testcase( op==TK_ISNULL );
77601       testcase( op==TK_NOTNULL );
77602       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77603       sqlcipher3VdbeAddOp2(v, op, r1, dest);
77604       testcase( regFree1==0 );
77605       break;
77606     }
77607     case TK_BETWEEN: {
77608       testcase( jumpIfNull==0 );
77609       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77610       break;
77611     }
77612 #ifndef SQLCIPHER_OMIT_SUBQUERY
77613     case TK_IN: {
77614       int destIfFalse = sqlcipher3VdbeMakeLabel(v);
77615       int destIfNull = jumpIfNull ? dest : destIfFalse;
77616       sqlcipher3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77617       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, dest);
77618       sqlcipher3VdbeResolveLabel(v, destIfFalse);
77619       break;
77620     }
77621 #endif
77622     default: {
77623       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr, &regFree1);
77624       sqlcipher3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77625       testcase( regFree1==0 );
77626       testcase( jumpIfNull==0 );
77627       break;
77628     }
77629   }
77630   sqlcipher3ReleaseTempReg(pParse, regFree1);
77631   sqlcipher3ReleaseTempReg(pParse, regFree2);  
77632 }
77633
77634 /*
77635 ** Generate code for a boolean expression such that a jump is made
77636 ** to the label "dest" if the expression is false but execution
77637 ** continues straight thru if the expression is true.
77638 **
77639 ** If the expression evaluates to NULL (neither true nor false) then
77640 ** jump if jumpIfNull is SQLCIPHER_JUMPIFNULL or fall through if jumpIfNull
77641 ** is 0.
77642 */
77643 SQLCIPHER_PRIVATE void sqlcipher3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77644   Vdbe *v = pParse->pVdbe;
77645   int op = 0;
77646   int regFree1 = 0;
77647   int regFree2 = 0;
77648   int r1, r2;
77649
77650   assert( jumpIfNull==SQLCIPHER_JUMPIFNULL || jumpIfNull==0 );
77651   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
77652   if( pExpr==0 )    return;
77653
77654   /* The value of pExpr->op and op are related as follows:
77655   **
77656   **       pExpr->op            op
77657   **       ---------          ----------
77658   **       TK_ISNULL          OP_NotNull
77659   **       TK_NOTNULL         OP_IsNull
77660   **       TK_NE              OP_Eq
77661   **       TK_EQ              OP_Ne
77662   **       TK_GT              OP_Le
77663   **       TK_LE              OP_Gt
77664   **       TK_GE              OP_Lt
77665   **       TK_LT              OP_Ge
77666   **
77667   ** For other values of pExpr->op, op is undefined and unused.
77668   ** The value of TK_ and OP_ constants are arranged such that we
77669   ** can compute the mapping above using the following expression.
77670   ** Assert()s verify that the computation is correct.
77671   */
77672   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77673
77674   /* Verify correct alignment of TK_ and OP_ constants
77675   */
77676   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
77677   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
77678   assert( pExpr->op!=TK_NE || op==OP_Eq );
77679   assert( pExpr->op!=TK_EQ || op==OP_Ne );
77680   assert( pExpr->op!=TK_LT || op==OP_Ge );
77681   assert( pExpr->op!=TK_LE || op==OP_Gt );
77682   assert( pExpr->op!=TK_GT || op==OP_Le );
77683   assert( pExpr->op!=TK_GE || op==OP_Lt );
77684
77685   switch( pExpr->op ){
77686     case TK_AND: {
77687       testcase( jumpIfNull==0 );
77688       sqlcipher3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77689       sqlcipher3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77690       break;
77691     }
77692     case TK_OR: {
77693       int d2 = sqlcipher3VdbeMakeLabel(v);
77694       testcase( jumpIfNull==0 );
77695       sqlcipher3ExprCachePush(pParse);
77696       sqlcipher3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLCIPHER_JUMPIFNULL);
77697       sqlcipher3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77698       sqlcipher3VdbeResolveLabel(v, d2);
77699       sqlcipher3ExprCachePop(pParse, 1);
77700       break;
77701     }
77702     case TK_NOT: {
77703       testcase( jumpIfNull==0 );
77704       sqlcipher3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77705       break;
77706     }
77707     case TK_LT:
77708     case TK_LE:
77709     case TK_GT:
77710     case TK_GE:
77711     case TK_NE:
77712     case TK_EQ: {
77713       testcase( op==TK_LT );
77714       testcase( op==TK_LE );
77715       testcase( op==TK_GT );
77716       testcase( op==TK_GE );
77717       testcase( op==TK_EQ );
77718       testcase( op==TK_NE );
77719       testcase( jumpIfNull==0 );
77720       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77721       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77722       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77723                   r1, r2, dest, jumpIfNull);
77724       testcase( regFree1==0 );
77725       testcase( regFree2==0 );
77726       break;
77727     }
77728     case TK_IS:
77729     case TK_ISNOT: {
77730       testcase( pExpr->op==TK_IS );
77731       testcase( pExpr->op==TK_ISNOT );
77732       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77733       r2 = sqlcipher3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77734       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
77735       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77736                   r1, r2, dest, SQLCIPHER_NULLEQ);
77737       testcase( regFree1==0 );
77738       testcase( regFree2==0 );
77739       break;
77740     }
77741     case TK_ISNULL:
77742     case TK_NOTNULL: {
77743       testcase( op==TK_ISNULL );
77744       testcase( op==TK_NOTNULL );
77745       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77746       sqlcipher3VdbeAddOp2(v, op, r1, dest);
77747       testcase( regFree1==0 );
77748       break;
77749     }
77750     case TK_BETWEEN: {
77751       testcase( jumpIfNull==0 );
77752       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
77753       break;
77754     }
77755 #ifndef SQLCIPHER_OMIT_SUBQUERY
77756     case TK_IN: {
77757       if( jumpIfNull ){
77758         sqlcipher3ExprCodeIN(pParse, pExpr, dest, dest);
77759       }else{
77760         int destIfNull = sqlcipher3VdbeMakeLabel(v);
77761         sqlcipher3ExprCodeIN(pParse, pExpr, dest, destIfNull);
77762         sqlcipher3VdbeResolveLabel(v, destIfNull);
77763       }
77764       break;
77765     }
77766 #endif
77767     default: {
77768       r1 = sqlcipher3ExprCodeTemp(pParse, pExpr, &regFree1);
77769       sqlcipher3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
77770       testcase( regFree1==0 );
77771       testcase( jumpIfNull==0 );
77772       break;
77773     }
77774   }
77775   sqlcipher3ReleaseTempReg(pParse, regFree1);
77776   sqlcipher3ReleaseTempReg(pParse, regFree2);
77777 }
77778
77779 /*
77780 ** Do a deep comparison of two expression trees.  Return 0 if the two
77781 ** expressions are completely identical.  Return 1 if they differ only
77782 ** by a COLLATE operator at the top level.  Return 2 if there are differences
77783 ** other than the top-level COLLATE operator.
77784 **
77785 ** Sometimes this routine will return 2 even if the two expressions
77786 ** really are equivalent.  If we cannot prove that the expressions are
77787 ** identical, we return 2 just to be safe.  So if this routine
77788 ** returns 2, then you do not really know for certain if the two
77789 ** expressions are the same.  But if you get a 0 or 1 return, then you
77790 ** can be sure the expressions are the same.  In the places where
77791 ** this routine is used, it does not hurt to get an extra 2 - that
77792 ** just might result in some slightly slower code.  But returning
77793 ** an incorrect 0 or 1 could lead to a malfunction.
77794 */
77795 SQLCIPHER_PRIVATE int sqlcipher3ExprCompare(Expr *pA, Expr *pB){
77796   if( pA==0||pB==0 ){
77797     return pB==pA ? 0 : 2;
77798   }
77799   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
77800   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
77801   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
77802     return 2;
77803   }
77804   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
77805   if( pA->op!=pB->op ) return 2;
77806   if( sqlcipher3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
77807   if( sqlcipher3ExprCompare(pA->pRight, pB->pRight) ) return 2;
77808   if( sqlcipher3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
77809   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
77810   if( ExprHasProperty(pA, EP_IntValue) ){
77811     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
77812       return 2;
77813     }
77814   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
77815     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
77816     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
77817       return 2;
77818     }
77819   }
77820   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
77821   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
77822   return 0;
77823 }
77824
77825 /*
77826 ** Compare two ExprList objects.  Return 0 if they are identical and 
77827 ** non-zero if they differ in any way.
77828 **
77829 ** This routine might return non-zero for equivalent ExprLists.  The
77830 ** only consequence will be disabled optimizations.  But this routine
77831 ** must never return 0 if the two ExprList objects are different, or
77832 ** a malfunction will result.
77833 **
77834 ** Two NULL pointers are considered to be the same.  But a NULL pointer
77835 ** always differs from a non-NULL pointer.
77836 */
77837 SQLCIPHER_PRIVATE int sqlcipher3ExprListCompare(ExprList *pA, ExprList *pB){
77838   int i;
77839   if( pA==0 && pB==0 ) return 0;
77840   if( pA==0 || pB==0 ) return 1;
77841   if( pA->nExpr!=pB->nExpr ) return 1;
77842   for(i=0; i<pA->nExpr; i++){
77843     Expr *pExprA = pA->a[i].pExpr;
77844     Expr *pExprB = pB->a[i].pExpr;
77845     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
77846     if( sqlcipher3ExprCompare(pExprA, pExprB) ) return 1;
77847   }
77848   return 0;
77849 }
77850
77851 /*
77852 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
77853 ** the new element.  Return a negative number if malloc fails.
77854 */
77855 static int addAggInfoColumn(sqlcipher3 *db, AggInfo *pInfo){
77856   int i;
77857   pInfo->aCol = sqlcipher3ArrayAllocate(
77858        db,
77859        pInfo->aCol,
77860        sizeof(pInfo->aCol[0]),
77861        3,
77862        &pInfo->nColumn,
77863        &pInfo->nColumnAlloc,
77864        &i
77865   );
77866   return i;
77867 }    
77868
77869 /*
77870 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
77871 ** the new element.  Return a negative number if malloc fails.
77872 */
77873 static int addAggInfoFunc(sqlcipher3 *db, AggInfo *pInfo){
77874   int i;
77875   pInfo->aFunc = sqlcipher3ArrayAllocate(
77876        db, 
77877        pInfo->aFunc,
77878        sizeof(pInfo->aFunc[0]),
77879        3,
77880        &pInfo->nFunc,
77881        &pInfo->nFuncAlloc,
77882        &i
77883   );
77884   return i;
77885 }    
77886
77887 /*
77888 ** This is the xExprCallback for a tree walker.  It is used to
77889 ** implement sqlcipher3ExprAnalyzeAggregates().  See sqlcipher3ExprAnalyzeAggregates
77890 ** for additional information.
77891 */
77892 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
77893   int i;
77894   NameContext *pNC = pWalker->u.pNC;
77895   Parse *pParse = pNC->pParse;
77896   SrcList *pSrcList = pNC->pSrcList;
77897   AggInfo *pAggInfo = pNC->pAggInfo;
77898
77899   switch( pExpr->op ){
77900     case TK_AGG_COLUMN:
77901     case TK_COLUMN: {
77902       testcase( pExpr->op==TK_AGG_COLUMN );
77903       testcase( pExpr->op==TK_COLUMN );
77904       /* Check to see if the column is in one of the tables in the FROM
77905       ** clause of the aggregate query */
77906       if( ALWAYS(pSrcList!=0) ){
77907         struct SrcList_item *pItem = pSrcList->a;
77908         for(i=0; i<pSrcList->nSrc; i++, pItem++){
77909           struct AggInfo_col *pCol;
77910           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77911           if( pExpr->iTable==pItem->iCursor ){
77912             /* If we reach this point, it means that pExpr refers to a table
77913             ** that is in the FROM clause of the aggregate query.  
77914             **
77915             ** Make an entry for the column in pAggInfo->aCol[] if there
77916             ** is not an entry there already.
77917             */
77918             int k;
77919             pCol = pAggInfo->aCol;
77920             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
77921               if( pCol->iTable==pExpr->iTable &&
77922                   pCol->iColumn==pExpr->iColumn ){
77923                 break;
77924               }
77925             }
77926             if( (k>=pAggInfo->nColumn)
77927              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
77928             ){
77929               pCol = &pAggInfo->aCol[k];
77930               pCol->pTab = pExpr->pTab;
77931               pCol->iTable = pExpr->iTable;
77932               pCol->iColumn = pExpr->iColumn;
77933               pCol->iMem = ++pParse->nMem;
77934               pCol->iSorterColumn = -1;
77935               pCol->pExpr = pExpr;
77936               if( pAggInfo->pGroupBy ){
77937                 int j, n;
77938                 ExprList *pGB = pAggInfo->pGroupBy;
77939                 struct ExprList_item *pTerm = pGB->a;
77940                 n = pGB->nExpr;
77941                 for(j=0; j<n; j++, pTerm++){
77942                   Expr *pE = pTerm->pExpr;
77943                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
77944                       pE->iColumn==pExpr->iColumn ){
77945                     pCol->iSorterColumn = j;
77946                     break;
77947                   }
77948                 }
77949               }
77950               if( pCol->iSorterColumn<0 ){
77951                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
77952               }
77953             }
77954             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
77955             ** because it was there before or because we just created it).
77956             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
77957             ** pAggInfo->aCol[] entry.
77958             */
77959             ExprSetIrreducible(pExpr);
77960             pExpr->pAggInfo = pAggInfo;
77961             pExpr->op = TK_AGG_COLUMN;
77962             pExpr->iAgg = (i16)k;
77963             break;
77964           } /* endif pExpr->iTable==pItem->iCursor */
77965         } /* end loop over pSrcList */
77966       }
77967       return WRC_Prune;
77968     }
77969     case TK_AGG_FUNCTION: {
77970       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
77971       ** to be ignored */
77972       if( pNC->nDepth==0 ){
77973         /* Check to see if pExpr is a duplicate of another aggregate 
77974         ** function that is already in the pAggInfo structure
77975         */
77976         struct AggInfo_func *pItem = pAggInfo->aFunc;
77977         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
77978           if( sqlcipher3ExprCompare(pItem->pExpr, pExpr)==0 ){
77979             break;
77980           }
77981         }
77982         if( i>=pAggInfo->nFunc ){
77983           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
77984           */
77985           u8 enc = ENC(pParse->db);
77986           i = addAggInfoFunc(pParse->db, pAggInfo);
77987           if( i>=0 ){
77988             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77989             pItem = &pAggInfo->aFunc[i];
77990             pItem->pExpr = pExpr;
77991             pItem->iMem = ++pParse->nMem;
77992             assert( !ExprHasProperty(pExpr, EP_IntValue) );
77993             pItem->pFunc = sqlcipher3FindFunction(pParse->db,
77994                    pExpr->u.zToken, sqlcipher3Strlen30(pExpr->u.zToken),
77995                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
77996             if( pExpr->flags & EP_Distinct ){
77997               pItem->iDistinct = pParse->nTab++;
77998             }else{
77999               pItem->iDistinct = -1;
78000             }
78001           }
78002         }
78003         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
78004         */
78005         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78006         ExprSetIrreducible(pExpr);
78007         pExpr->iAgg = (i16)i;
78008         pExpr->pAggInfo = pAggInfo;
78009         return WRC_Prune;
78010       }
78011     }
78012   }
78013   return WRC_Continue;
78014 }
78015 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
78016   NameContext *pNC = pWalker->u.pNC;
78017   if( pNC->nDepth==0 ){
78018     pNC->nDepth++;
78019     sqlcipher3WalkSelect(pWalker, pSelect);
78020     pNC->nDepth--;
78021     return WRC_Prune;
78022   }else{
78023     return WRC_Continue;
78024   }
78025 }
78026
78027 /*
78028 ** Analyze the given expression looking for aggregate functions and
78029 ** for variables that need to be added to the pParse->aAgg[] array.
78030 ** Make additional entries to the pParse->aAgg[] array as necessary.
78031 **
78032 ** This routine should only be called after the expression has been
78033 ** analyzed by sqlcipher3ResolveExprNames().
78034 */
78035 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
78036   Walker w;
78037   w.xExprCallback = analyzeAggregate;
78038   w.xSelectCallback = analyzeAggregatesInSelect;
78039   w.u.pNC = pNC;
78040   assert( pNC->pSrcList!=0 );
78041   sqlcipher3WalkExpr(&w, pExpr);
78042 }
78043
78044 /*
78045 ** Call sqlcipher3ExprAnalyzeAggregates() for every expression in an
78046 ** expression list.  Return the number of errors.
78047 **
78048 ** If an error is found, the analysis is cut short.
78049 */
78050 SQLCIPHER_PRIVATE void sqlcipher3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
78051   struct ExprList_item *pItem;
78052   int i;
78053   if( pList ){
78054     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78055       sqlcipher3ExprAnalyzeAggregates(pNC, pItem->pExpr);
78056     }
78057   }
78058 }
78059
78060 /*
78061 ** Allocate a single new register for use to hold some intermediate result.
78062 */
78063 SQLCIPHER_PRIVATE int sqlcipher3GetTempReg(Parse *pParse){
78064   if( pParse->nTempReg==0 ){
78065     return ++pParse->nMem;
78066   }
78067   return pParse->aTempReg[--pParse->nTempReg];
78068 }
78069
78070 /*
78071 ** Deallocate a register, making available for reuse for some other
78072 ** purpose.
78073 **
78074 ** If a register is currently being used by the column cache, then
78075 ** the dallocation is deferred until the column cache line that uses
78076 ** the register becomes stale.
78077 */
78078 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempReg(Parse *pParse, int iReg){
78079   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78080     int i;
78081     struct yColCache *p;
78082     for(i=0, p=pParse->aColCache; i<SQLCIPHER_N_COLCACHE; i++, p++){
78083       if( p->iReg==iReg ){
78084         p->tempReg = 1;
78085         return;
78086       }
78087     }
78088     pParse->aTempReg[pParse->nTempReg++] = iReg;
78089   }
78090 }
78091
78092 /*
78093 ** Allocate or deallocate a block of nReg consecutive registers
78094 */
78095 SQLCIPHER_PRIVATE int sqlcipher3GetTempRange(Parse *pParse, int nReg){
78096   int i, n;
78097   i = pParse->iRangeReg;
78098   n = pParse->nRangeReg;
78099   if( nReg<=n ){
78100     assert( !usedAsColumnCache(pParse, i, i+n-1) );
78101     pParse->iRangeReg += nReg;
78102     pParse->nRangeReg -= nReg;
78103   }else{
78104     i = pParse->nMem+1;
78105     pParse->nMem += nReg;
78106   }
78107   return i;
78108 }
78109 SQLCIPHER_PRIVATE void sqlcipher3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
78110   sqlcipher3ExprCacheRemove(pParse, iReg, nReg);
78111   if( nReg>pParse->nRangeReg ){
78112     pParse->nRangeReg = nReg;
78113     pParse->iRangeReg = iReg;
78114   }
78115 }
78116
78117 /************** End of expr.c ************************************************/
78118 /************** Begin file alter.c *******************************************/
78119 /*
78120 ** 2005 February 15
78121 **
78122 ** The author disclaims copyright to this source code.  In place of
78123 ** a legal notice, here is a blessing:
78124 **
78125 **    May you do good and not evil.
78126 **    May you find forgiveness for yourself and forgive others.
78127 **    May you share freely, never taking more than you give.
78128 **
78129 *************************************************************************
78130 ** This file contains C code routines that used to generate VDBE code
78131 ** that implements the ALTER TABLE command.
78132 */
78133
78134 /*
78135 ** The code in this file only exists if we are not omitting the
78136 ** ALTER TABLE logic from the build.
78137 */
78138 #ifndef SQLCIPHER_OMIT_ALTERTABLE
78139
78140
78141 /*
78142 ** This function is used by SQL generated to implement the 
78143 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
78144 ** CREATE INDEX command. The second is a table name. The table name in 
78145 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
78146 ** argument and the result returned. Examples:
78147 **
78148 ** sqlcipher_rename_table('CREATE TABLE abc(a, b, c)', 'def')
78149 **     -> 'CREATE TABLE def(a, b, c)'
78150 **
78151 ** sqlcipher_rename_table('CREATE INDEX i ON abc(a)', 'def')
78152 **     -> 'CREATE INDEX i ON def(a, b, c)'
78153 */
78154 static void renameTableFunc(
78155   sqlcipher3_context *context,
78156   int NotUsed,
78157   sqlcipher3_value **argv
78158 ){
78159   unsigned char const *zSql = sqlcipher3_value_text(argv[0]);
78160   unsigned char const *zTableName = sqlcipher3_value_text(argv[1]);
78161
78162   int token;
78163   Token tname;
78164   unsigned char const *zCsr = zSql;
78165   int len = 0;
78166   char *zRet;
78167
78168   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
78169
78170   UNUSED_PARAMETER(NotUsed);
78171
78172   /* The principle used to locate the table name in the CREATE TABLE 
78173   ** statement is that the table name is the first non-space token that
78174   ** is immediately followed by a TK_LP or TK_USING token.
78175   */
78176   if( zSql ){
78177     do {
78178       if( !*zCsr ){
78179         /* Ran out of input before finding an opening bracket. Return NULL. */
78180         return;
78181       }
78182
78183       /* Store the token that zCsr points to in tname. */
78184       tname.z = (char*)zCsr;
78185       tname.n = len;
78186
78187       /* Advance zCsr to the next token. Store that token type in 'token',
78188       ** and its length in 'len' (to be used next iteration of this loop).
78189       */
78190       do {
78191         zCsr += len;
78192         len = sqlcipher3GetToken(zCsr, &token);
78193       } while( token==TK_SPACE );
78194       assert( len>0 );
78195     } while( token!=TK_LP && token!=TK_USING );
78196
78197     zRet = sqlcipher3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78198        zTableName, tname.z+tname.n);
78199     sqlcipher3_result_text(context, zRet, -1, SQLCIPHER_DYNAMIC);
78200   }
78201 }
78202
78203 /*
78204 ** This C function implements an SQL user function that is used by SQL code
78205 ** generated by the ALTER TABLE ... RENAME command to modify the definition
78206 ** of any foreign key constraints that use the table being renamed as the 
78207 ** parent table. It is passed three arguments:
78208 **
78209 **   1) The complete text of the CREATE TABLE statement being modified,
78210 **   2) The old name of the table being renamed, and
78211 **   3) The new name of the table being renamed.
78212 **
78213 ** It returns the new CREATE TABLE statement. For example:
78214 **
78215 **   sqlcipher_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78216 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
78217 */
78218 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
78219 static void renameParentFunc(
78220   sqlcipher3_context *context,
78221   int NotUsed,
78222   sqlcipher3_value **argv
78223 ){
78224   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
78225   char *zOutput = 0;
78226   char *zResult;
78227   unsigned char const *zInput = sqlcipher3_value_text(argv[0]);
78228   unsigned char const *zOld = sqlcipher3_value_text(argv[1]);
78229   unsigned char const *zNew = sqlcipher3_value_text(argv[2]);
78230
78231   unsigned const char *z;         /* Pointer to token */
78232   int n;                          /* Length of token z */
78233   int token;                      /* Type of token */
78234
78235   UNUSED_PARAMETER(NotUsed);
78236   for(z=zInput; *z; z=z+n){
78237     n = sqlcipher3GetToken(z, &token);
78238     if( token==TK_REFERENCES ){
78239       char *zParent;
78240       do {
78241         z += n;
78242         n = sqlcipher3GetToken(z, &token);
78243       }while( token==TK_SPACE );
78244
78245       zParent = sqlcipher3DbStrNDup(db, (const char *)z, n);
78246       if( zParent==0 ) break;
78247       sqlcipher3Dequote(zParent);
78248       if( 0==sqlcipher3StrICmp((const char *)zOld, zParent) ){
78249         char *zOut = sqlcipher3MPrintf(db, "%s%.*s\"%w\"", 
78250             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78251         );
78252         sqlcipher3DbFree(db, zOutput);
78253         zOutput = zOut;
78254         zInput = &z[n];
78255       }
78256       sqlcipher3DbFree(db, zParent);
78257     }
78258   }
78259
78260   zResult = sqlcipher3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
78261   sqlcipher3_result_text(context, zResult, -1, SQLCIPHER_DYNAMIC);
78262   sqlcipher3DbFree(db, zOutput);
78263 }
78264 #endif
78265
78266 #ifndef SQLCIPHER_OMIT_TRIGGER
78267 /* This function is used by SQL generated to implement the
78268 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
78269 ** statement. The second is a table name. The table name in the CREATE 
78270 ** TRIGGER statement is replaced with the third argument and the result 
78271 ** returned. This is analagous to renameTableFunc() above, except for CREATE
78272 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
78273 */
78274 static void renameTriggerFunc(
78275   sqlcipher3_context *context,
78276   int NotUsed,
78277   sqlcipher3_value **argv
78278 ){
78279   unsigned char const *zSql = sqlcipher3_value_text(argv[0]);
78280   unsigned char const *zTableName = sqlcipher3_value_text(argv[1]);
78281
78282   int token;
78283   Token tname;
78284   int dist = 3;
78285   unsigned char const *zCsr = zSql;
78286   int len = 0;
78287   char *zRet;
78288   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
78289
78290   UNUSED_PARAMETER(NotUsed);
78291
78292   /* The principle used to locate the table name in the CREATE TRIGGER 
78293   ** statement is that the table name is the first token that is immediatedly
78294   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78295   ** of TK_WHEN, TK_BEGIN or TK_FOR.
78296   */
78297   if( zSql ){
78298     do {
78299
78300       if( !*zCsr ){
78301         /* Ran out of input before finding the table name. Return NULL. */
78302         return;
78303       }
78304
78305       /* Store the token that zCsr points to in tname. */
78306       tname.z = (char*)zCsr;
78307       tname.n = len;
78308
78309       /* Advance zCsr to the next token. Store that token type in 'token',
78310       ** and its length in 'len' (to be used next iteration of this loop).
78311       */
78312       do {
78313         zCsr += len;
78314         len = sqlcipher3GetToken(zCsr, &token);
78315       }while( token==TK_SPACE );
78316       assert( len>0 );
78317
78318       /* Variable 'dist' stores the number of tokens read since the most
78319       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
78320       ** token is read and 'dist' equals 2, the condition stated above
78321       ** to be met.
78322       **
78323       ** Note that ON cannot be a database, table or column name, so
78324       ** there is no need to worry about syntax like 
78325       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78326       */
78327       dist++;
78328       if( token==TK_DOT || token==TK_ON ){
78329         dist = 0;
78330       }
78331     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78332
78333     /* Variable tname now contains the token that is the old table-name
78334     ** in the CREATE TRIGGER statement.
78335     */
78336     zRet = sqlcipher3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78337        zTableName, tname.z+tname.n);
78338     sqlcipher3_result_text(context, zRet, -1, SQLCIPHER_DYNAMIC);
78339   }
78340 }
78341 #endif   /* !SQLCIPHER_OMIT_TRIGGER */
78342
78343 /*
78344 ** Register built-in functions used to help implement ALTER TABLE
78345 */
78346 SQLCIPHER_PRIVATE void sqlcipher3AlterFunctions(void){
78347   static SQLCIPHER_WSD FuncDef aAlterTableFuncs[] = {
78348     FUNCTION(sqlcipher_rename_table,   2, 0, 0, renameTableFunc),
78349 #ifndef SQLCIPHER_OMIT_TRIGGER
78350     FUNCTION(sqlcipher_rename_trigger, 2, 0, 0, renameTriggerFunc),
78351 #endif
78352 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
78353     FUNCTION(sqlcipher_rename_parent,  3, 0, 0, renameParentFunc),
78354 #endif
78355   };
78356   int i;
78357   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
78358   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78359
78360   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78361     sqlcipher3FuncDefInsert(pHash, &aFunc[i]);
78362   }
78363 }
78364
78365 /*
78366 ** This function is used to create the text of expressions of the form:
78367 **
78368 **   name=<constant1> OR name=<constant2> OR ...
78369 **
78370 ** If argument zWhere is NULL, then a pointer string containing the text 
78371 ** "name=<constant>" is returned, where <constant> is the quoted version
78372 ** of the string passed as argument zConstant. The returned buffer is
78373 ** allocated using sqlcipher3DbMalloc(). It is the responsibility of the
78374 ** caller to ensure that it is eventually freed.
78375 **
78376 ** If argument zWhere is not NULL, then the string returned is 
78377 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78378 ** In this case zWhere is passed to sqlcipher3DbFree() before returning.
78379 ** 
78380 */
78381 static char *whereOrName(sqlcipher3 *db, char *zWhere, char *zConstant){
78382   char *zNew;
78383   if( !zWhere ){
78384     zNew = sqlcipher3MPrintf(db, "name=%Q", zConstant);
78385   }else{
78386     zNew = sqlcipher3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78387     sqlcipher3DbFree(db, zWhere);
78388   }
78389   return zNew;
78390 }
78391
78392 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
78393 /*
78394 ** Generate the text of a WHERE expression which can be used to select all
78395 ** tables that have foreign key constraints that refer to table pTab (i.e.
78396 ** constraints for which pTab is the parent table) from the sqlcipher_master
78397 ** table.
78398 */
78399 static char *whereForeignKeys(Parse *pParse, Table *pTab){
78400   FKey *p;
78401   char *zWhere = 0;
78402   for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
78403     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78404   }
78405   return zWhere;
78406 }
78407 #endif
78408
78409 /*
78410 ** Generate the text of a WHERE expression which can be used to select all
78411 ** temporary triggers on table pTab from the sqlcipher_temp_master table. If
78412 ** table pTab has no temporary triggers, or is itself stored in the 
78413 ** temporary database, NULL is returned.
78414 */
78415 static char *whereTempTriggers(Parse *pParse, Table *pTab){
78416   Trigger *pTrig;
78417   char *zWhere = 0;
78418   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78419
78420   /* If the table is not located in the temp-db (in which case NULL is 
78421   ** returned, loop through the tables list of triggers. For each trigger
78422   ** that is not part of the temp-db schema, add a clause to the WHERE 
78423   ** expression being built up in zWhere.
78424   */
78425   if( pTab->pSchema!=pTempSchema ){
78426     sqlcipher3 *db = pParse->db;
78427     for(pTrig=sqlcipher3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78428       if( pTrig->pSchema==pTempSchema ){
78429         zWhere = whereOrName(db, zWhere, pTrig->zName);
78430       }
78431     }
78432   }
78433   if( zWhere ){
78434     char *zNew = sqlcipher3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78435     sqlcipher3DbFree(pParse->db, zWhere);
78436     zWhere = zNew;
78437   }
78438   return zWhere;
78439 }
78440
78441 /*
78442 ** Generate code to drop and reload the internal representation of table
78443 ** pTab from the database, including triggers and temporary triggers.
78444 ** Argument zName is the name of the table in the database schema at
78445 ** the time the generated code is executed. This can be different from
78446 ** pTab->zName if this function is being called to code part of an 
78447 ** "ALTER TABLE RENAME TO" statement.
78448 */
78449 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78450   Vdbe *v;
78451   char *zWhere;
78452   int iDb;                   /* Index of database containing pTab */
78453 #ifndef SQLCIPHER_OMIT_TRIGGER
78454   Trigger *pTrig;
78455 #endif
78456
78457   v = sqlcipher3GetVdbe(pParse);
78458   if( NEVER(v==0) ) return;
78459   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
78460   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
78461   assert( iDb>=0 );
78462
78463 #ifndef SQLCIPHER_OMIT_TRIGGER
78464   /* Drop any table triggers from the internal schema. */
78465   for(pTrig=sqlcipher3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78466     int iTrigDb = sqlcipher3SchemaToIndex(pParse->db, pTrig->pSchema);
78467     assert( iTrigDb==iDb || iTrigDb==1 );
78468     sqlcipher3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78469   }
78470 #endif
78471
78472   /* Drop the table and index from the internal schema.  */
78473   sqlcipher3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78474
78475   /* Reload the table, index and permanent trigger schemas. */
78476   zWhere = sqlcipher3MPrintf(pParse->db, "tbl_name=%Q", zName);
78477   if( !zWhere ) return;
78478   sqlcipher3VdbeAddParseSchemaOp(v, iDb, zWhere);
78479
78480 #ifndef SQLCIPHER_OMIT_TRIGGER
78481   /* Now, if the table is not stored in the temp database, reload any temp 
78482   ** triggers. Don't use IN(...) in case SQLCIPHER_OMIT_SUBQUERY is defined. 
78483   */
78484   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78485     sqlcipher3VdbeAddParseSchemaOp(v, 1, zWhere);
78486   }
78487 #endif
78488 }
78489
78490 /*
78491 ** Parameter zName is the name of a table that is about to be altered
78492 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78493 ** If the table is a system table, this function leaves an error message
78494 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
78495 **
78496 ** Or, if zName is not a system table, zero is returned.
78497 */
78498 static int isSystemTable(Parse *pParse, const char *zName){
78499   if( sqlcipher3Strlen30(zName)>6 && 0==sqlcipher3StrNICmp(zName, "sqlcipher_", 7) ){
78500     sqlcipher3ErrorMsg(pParse, "table %s may not be altered", zName);
78501     return 1;
78502   }
78503   return 0;
78504 }
78505
78506 /*
78507 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
78508 ** command. 
78509 */
78510 SQLCIPHER_PRIVATE void sqlcipher3AlterRenameTable(
78511   Parse *pParse,            /* Parser context. */
78512   SrcList *pSrc,            /* The table to rename. */
78513   Token *pName              /* The new table name. */
78514 ){
78515   int iDb;                  /* Database that contains the table */
78516   char *zDb;                /* Name of database iDb */
78517   Table *pTab;              /* Table being renamed */
78518   char *zName = 0;          /* NULL-terminated version of pName */ 
78519   sqlcipher3 *db = pParse->db; /* Database connection */
78520   int nTabName;             /* Number of UTF-8 characters in zTabName */
78521   const char *zTabName;     /* Original name of the table */
78522   Vdbe *v;
78523 #ifndef SQLCIPHER_OMIT_TRIGGER
78524   char *zWhere = 0;         /* Where clause to locate temp triggers */
78525 #endif
78526   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78527   int savedDbFlags;         /* Saved value of db->flags */
78528
78529   savedDbFlags = db->flags;  
78530   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78531   assert( pSrc->nSrc==1 );
78532   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
78533
78534   pTab = sqlcipher3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78535   if( !pTab ) goto exit_rename_table;
78536   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
78537   zDb = db->aDb[iDb].zName;
78538   db->flags |= SQLCIPHER_PreferBuiltin;
78539
78540   /* Get a NULL terminated version of the new table name. */
78541   zName = sqlcipher3NameFromToken(db, pName);
78542   if( !zName ) goto exit_rename_table;
78543
78544   /* Check that a table or index named 'zName' does not already exist
78545   ** in database iDb. If so, this is an error.
78546   */
78547   if( sqlcipher3FindTable(db, zName, zDb) || sqlcipher3FindIndex(db, zName, zDb) ){
78548     sqlcipher3ErrorMsg(pParse, 
78549         "there is already another table or index with this name: %s", zName);
78550     goto exit_rename_table;
78551   }
78552
78553   /* Make sure it is not a system table being altered, or a reserved name
78554   ** that the table is being renamed to.
78555   */
78556   if( SQLCIPHER_OK!=isSystemTable(pParse, pTab->zName) ){
78557     goto exit_rename_table;
78558   }
78559   if( SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){ goto
78560     exit_rename_table;
78561   }
78562
78563 #ifndef SQLCIPHER_OMIT_VIEW
78564   if( pTab->pSelect ){
78565     sqlcipher3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78566     goto exit_rename_table;
78567   }
78568 #endif
78569
78570 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
78571   /* Invoke the authorization callback. */
78572   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_ALTER_TABLE, zDb, pTab->zName, 0) ){
78573     goto exit_rename_table;
78574   }
78575 #endif
78576
78577 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
78578   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
78579     goto exit_rename_table;
78580   }
78581   if( IsVirtual(pTab) ){
78582     pVTab = sqlcipher3GetVTable(db, pTab);
78583     if( pVTab->pVtab->pModule->xRename==0 ){
78584       pVTab = 0;
78585     }
78586   }
78587 #endif
78588
78589   /* Begin a transaction and code the VerifyCookie for database iDb. 
78590   ** Then modify the schema cookie (since the ALTER TABLE modifies the
78591   ** schema). Open a statement transaction if the table is a virtual
78592   ** table.
78593   */
78594   v = sqlcipher3GetVdbe(pParse);
78595   if( v==0 ){
78596     goto exit_rename_table;
78597   }
78598   sqlcipher3BeginWriteOperation(pParse, pVTab!=0, iDb);
78599   sqlcipher3ChangeCookie(pParse, iDb);
78600
78601   /* If this is a virtual table, invoke the xRename() function if
78602   ** one is defined. The xRename() callback will modify the names
78603   ** of any resources used by the v-table implementation (including other
78604   ** SQLite tables) that are identified by the name of the virtual table.
78605   */
78606 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
78607   if( pVTab ){
78608     int i = ++pParse->nMem;
78609     sqlcipher3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78610     sqlcipher3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78611     sqlcipher3MayAbort(pParse);
78612   }
78613 #endif
78614
78615   /* figure out how many UTF-8 characters are in zName */
78616   zTabName = pTab->zName;
78617   nTabName = sqlcipher3Utf8CharLen(zTabName, -1);
78618
78619 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
78620   if( db->flags&SQLCIPHER_ForeignKeys ){
78621     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
78622     ** statements corresponding to all child tables of foreign key constraints
78623     ** for which the renamed table is the parent table.  */
78624     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78625       sqlcipher3NestedParse(pParse, 
78626           "UPDATE \"%w\".%s SET "
78627               "sql = sqlcipher_rename_parent(sql, %Q, %Q) "
78628               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78629       sqlcipher3DbFree(db, zWhere);
78630     }
78631   }
78632 #endif
78633
78634   /* Modify the sqlcipher_master table to use the new table name. */
78635   sqlcipher3NestedParse(pParse,
78636       "UPDATE %Q.%s SET "
78637 #ifdef SQLCIPHER_OMIT_TRIGGER
78638           "sql = sqlcipher_rename_table(sql, %Q), "
78639 #else
78640           "sql = CASE "
78641             "WHEN type = 'trigger' THEN sqlcipher_rename_trigger(sql, %Q)"
78642             "ELSE sqlcipher_rename_table(sql, %Q) END, "
78643 #endif
78644           "tbl_name = %Q, "
78645           "name = CASE "
78646             "WHEN type='table' THEN %Q "
78647             "WHEN name LIKE 'sqlcipher_autoindex%%' AND type='index' THEN "
78648              "'sqlcipher_autoindex_' || %Q || substr(name,%d+18) "
78649             "ELSE name END "
78650       "WHERE tbl_name=%Q AND "
78651           "(type='table' OR type='index' OR type='trigger');", 
78652       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
78653 #ifndef SQLCIPHER_OMIT_TRIGGER
78654       zName,
78655 #endif
78656       zName, nTabName, zTabName
78657   );
78658
78659 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
78660   /* If the sqlcipher_sequence table exists in this database, then update 
78661   ** it with the new table name.
78662   */
78663   if( sqlcipher3FindTable(db, "sqlcipher_sequence", zDb) ){
78664     sqlcipher3NestedParse(pParse,
78665         "UPDATE \"%w\".sqlcipher_sequence set name = %Q WHERE name = %Q",
78666         zDb, zName, pTab->zName);
78667   }
78668 #endif
78669
78670 #ifndef SQLCIPHER_OMIT_TRIGGER
78671   /* If there are TEMP triggers on this table, modify the sqlcipher_temp_master
78672   ** table. Don't do this if the table being ALTERed is itself located in
78673   ** the temp database.
78674   */
78675   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78676     sqlcipher3NestedParse(pParse, 
78677         "UPDATE sqlcipher_temp_master SET "
78678             "sql = sqlcipher_rename_trigger(sql, %Q), "
78679             "tbl_name = %Q "
78680             "WHERE %s;", zName, zName, zWhere);
78681     sqlcipher3DbFree(db, zWhere);
78682   }
78683 #endif
78684
78685 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
78686   if( db->flags&SQLCIPHER_ForeignKeys ){
78687     FKey *p;
78688     for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
78689       Table *pFrom = p->pFrom;
78690       if( pFrom!=pTab ){
78691         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
78692       }
78693     }
78694   }
78695 #endif
78696
78697   /* Drop and reload the internal table schema. */
78698   reloadTableSchema(pParse, pTab, zName);
78699
78700 exit_rename_table:
78701   sqlcipher3SrcListDelete(db, pSrc);
78702   sqlcipher3DbFree(db, zName);
78703   db->flags = savedDbFlags;
78704 }
78705
78706
78707 /*
78708 ** Generate code to make sure the file format number is at least minFormat.
78709 ** The generated code will increase the file format number if necessary.
78710 */
78711 SQLCIPHER_PRIVATE void sqlcipher3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
78712   Vdbe *v;
78713   v = sqlcipher3GetVdbe(pParse);
78714   /* The VDBE should have been allocated before this routine is called.
78715   ** If that allocation failed, we would have quit before reaching this
78716   ** point */
78717   if( ALWAYS(v) ){
78718     int r1 = sqlcipher3GetTempReg(pParse);
78719     int r2 = sqlcipher3GetTempReg(pParse);
78720     int j1;
78721     sqlcipher3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
78722     sqlcipher3VdbeUsesBtree(v, iDb);
78723     sqlcipher3VdbeAddOp2(v, OP_Integer, minFormat, r2);
78724     j1 = sqlcipher3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
78725     sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
78726     sqlcipher3VdbeJumpHere(v, j1);
78727     sqlcipher3ReleaseTempReg(pParse, r1);
78728     sqlcipher3ReleaseTempReg(pParse, r2);
78729   }
78730 }
78731
78732 /*
78733 ** This function is called after an "ALTER TABLE ... ADD" statement
78734 ** has been parsed. Argument pColDef contains the text of the new
78735 ** column definition.
78736 **
78737 ** The Table structure pParse->pNewTable was extended to include
78738 ** the new column during parsing.
78739 */
78740 SQLCIPHER_PRIVATE void sqlcipher3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
78741   Table *pNew;              /* Copy of pParse->pNewTable */
78742   Table *pTab;              /* Table being altered */
78743   int iDb;                  /* Database number */
78744   const char *zDb;          /* Database name */
78745   const char *zTab;         /* Table name */
78746   char *zCol;               /* Null-terminated column definition */
78747   Column *pCol;             /* The new column */
78748   Expr *pDflt;              /* Default value for the new column */
78749   sqlcipher3 *db;              /* The database connection; */
78750
78751   db = pParse->db;
78752   if( pParse->nErr || db->mallocFailed ) return;
78753   pNew = pParse->pNewTable;
78754   assert( pNew );
78755
78756   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
78757   iDb = sqlcipher3SchemaToIndex(db, pNew->pSchema);
78758   zDb = db->aDb[iDb].zName;
78759   zTab = &pNew->zName[19];  /* Skip the "sqlcipher_altertab_" prefix on the name */
78760   pCol = &pNew->aCol[pNew->nCol-1];
78761   pDflt = pCol->pDflt;
78762   pTab = sqlcipher3FindTable(db, zTab, zDb);
78763   assert( pTab );
78764
78765 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
78766   /* Invoke the authorization callback. */
78767   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_ALTER_TABLE, zDb, pTab->zName, 0) ){
78768     return;
78769   }
78770 #endif
78771
78772   /* If the default value for the new column was specified with a 
78773   ** literal NULL, then set pDflt to 0. This simplifies checking
78774   ** for an SQL NULL default below.
78775   */
78776   if( pDflt && pDflt->op==TK_NULL ){
78777     pDflt = 0;
78778   }
78779
78780   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
78781   ** If there is a NOT NULL constraint, then the default value for the
78782   ** column must not be NULL.
78783   */
78784   if( pCol->isPrimKey ){
78785     sqlcipher3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
78786     return;
78787   }
78788   if( pNew->pIndex ){
78789     sqlcipher3ErrorMsg(pParse, "Cannot add a UNIQUE column");
78790     return;
78791   }
78792   if( (db->flags&SQLCIPHER_ForeignKeys) && pNew->pFKey && pDflt ){
78793     sqlcipher3ErrorMsg(pParse, 
78794         "Cannot add a REFERENCES column with non-NULL default value");
78795     return;
78796   }
78797   if( pCol->notNull && !pDflt ){
78798     sqlcipher3ErrorMsg(pParse, 
78799         "Cannot add a NOT NULL column with default value NULL");
78800     return;
78801   }
78802
78803   /* Ensure the default expression is something that sqlcipher3ValueFromExpr()
78804   ** can handle (i.e. not CURRENT_TIME etc.)
78805   */
78806   if( pDflt ){
78807     sqlcipher3_value *pVal;
78808     if( sqlcipher3ValueFromExpr(db, pDflt, SQLCIPHER_UTF8, SQLCIPHER_AFF_NONE, &pVal) ){
78809       db->mallocFailed = 1;
78810       return;
78811     }
78812     if( !pVal ){
78813       sqlcipher3ErrorMsg(pParse, "Cannot add a column with non-constant default");
78814       return;
78815     }
78816     sqlcipher3ValueFree(pVal);
78817   }
78818
78819   /* Modify the CREATE TABLE statement. */
78820   zCol = sqlcipher3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
78821   if( zCol ){
78822     char *zEnd = &zCol[pColDef->n-1];
78823     int savedDbFlags = db->flags;
78824     while( zEnd>zCol && (*zEnd==';' || sqlcipher3Isspace(*zEnd)) ){
78825       *zEnd-- = '\0';
78826     }
78827     db->flags |= SQLCIPHER_PreferBuiltin;
78828     sqlcipher3NestedParse(pParse, 
78829         "UPDATE \"%w\".%s SET "
78830           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
78831         "WHERE type = 'table' AND name = %Q", 
78832       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
78833       zTab
78834     );
78835     sqlcipher3DbFree(db, zCol);
78836     db->flags = savedDbFlags;
78837   }
78838
78839   /* If the default value of the new column is NULL, then set the file
78840   ** format to 2. If the default value of the new column is not NULL,
78841   ** the file format becomes 3.
78842   */
78843   sqlcipher3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
78844
78845   /* Reload the schema of the modified table. */
78846   reloadTableSchema(pParse, pTab, pTab->zName);
78847 }
78848
78849 /*
78850 ** This function is called by the parser after the table-name in
78851 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
78852 ** pSrc is the full-name of the table being altered.
78853 **
78854 ** This routine makes a (partial) copy of the Table structure
78855 ** for the table being altered and sets Parse.pNewTable to point
78856 ** to it. Routines called by the parser as the column definition
78857 ** is parsed (i.e. sqlcipher3AddColumn()) add the new Column data to 
78858 ** the copy. The copy of the Table structure is deleted by tokenize.c 
78859 ** after parsing is finished.
78860 **
78861 ** Routine sqlcipher3AlterFinishAddColumn() will be called to complete
78862 ** coding the "ALTER TABLE ... ADD" statement.
78863 */
78864 SQLCIPHER_PRIVATE void sqlcipher3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
78865   Table *pNew;
78866   Table *pTab;
78867   Vdbe *v;
78868   int iDb;
78869   int i;
78870   int nAlloc;
78871   sqlcipher3 *db = pParse->db;
78872
78873   /* Look up the table being altered. */
78874   assert( pParse->pNewTable==0 );
78875   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
78876   if( db->mallocFailed ) goto exit_begin_add_column;
78877   pTab = sqlcipher3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78878   if( !pTab ) goto exit_begin_add_column;
78879
78880 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
78881   if( IsVirtual(pTab) ){
78882     sqlcipher3ErrorMsg(pParse, "virtual tables may not be altered");
78883     goto exit_begin_add_column;
78884   }
78885 #endif
78886
78887   /* Make sure this is not an attempt to ALTER a view. */
78888   if( pTab->pSelect ){
78889     sqlcipher3ErrorMsg(pParse, "Cannot add a column to a view");
78890     goto exit_begin_add_column;
78891   }
78892   if( SQLCIPHER_OK!=isSystemTable(pParse, pTab->zName) ){
78893     goto exit_begin_add_column;
78894   }
78895
78896   assert( pTab->addColOffset>0 );
78897   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
78898
78899   /* Put a copy of the Table struct in Parse.pNewTable for the
78900   ** sqlcipher3AddColumn() function and friends to modify.  But modify
78901   ** the name by adding an "sqlcipher_altertab_" prefix.  By adding this
78902   ** prefix, we insure that the name will not collide with an existing
78903   ** table because user table are not allowed to have the "sqlcipher_"
78904   ** prefix on their name.
78905   */
78906   pNew = (Table*)sqlcipher3DbMallocZero(db, sizeof(Table));
78907   if( !pNew ) goto exit_begin_add_column;
78908   pParse->pNewTable = pNew;
78909   pNew->nRef = 1;
78910   pNew->nCol = pTab->nCol;
78911   assert( pNew->nCol>0 );
78912   nAlloc = (((pNew->nCol-1)/8)*8)+8;
78913   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
78914   pNew->aCol = (Column*)sqlcipher3DbMallocZero(db, sizeof(Column)*nAlloc);
78915   pNew->zName = sqlcipher3MPrintf(db, "sqlcipher_altertab_%s", pTab->zName);
78916   if( !pNew->aCol || !pNew->zName ){
78917     db->mallocFailed = 1;
78918     goto exit_begin_add_column;
78919   }
78920   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
78921   for(i=0; i<pNew->nCol; i++){
78922     Column *pCol = &pNew->aCol[i];
78923     pCol->zName = sqlcipher3DbStrDup(db, pCol->zName);
78924     pCol->zColl = 0;
78925     pCol->zType = 0;
78926     pCol->pDflt = 0;
78927     pCol->zDflt = 0;
78928   }
78929   pNew->pSchema = db->aDb[iDb].pSchema;
78930   pNew->addColOffset = pTab->addColOffset;
78931   pNew->nRef = 1;
78932
78933   /* Begin a transaction and increment the schema cookie.  */
78934   sqlcipher3BeginWriteOperation(pParse, 0, iDb);
78935   v = sqlcipher3GetVdbe(pParse);
78936   if( !v ) goto exit_begin_add_column;
78937   sqlcipher3ChangeCookie(pParse, iDb);
78938
78939 exit_begin_add_column:
78940   sqlcipher3SrcListDelete(db, pSrc);
78941   return;
78942 }
78943 #endif  /* SQLCIPHER_ALTER_TABLE */
78944
78945 /************** End of alter.c ***********************************************/
78946 /************** Begin file analyze.c *****************************************/
78947 /*
78948 ** 2005 July 8
78949 **
78950 ** The author disclaims copyright to this source code.  In place of
78951 ** a legal notice, here is a blessing:
78952 **
78953 **    May you do good and not evil.
78954 **    May you find forgiveness for yourself and forgive others.
78955 **    May you share freely, never taking more than you give.
78956 **
78957 *************************************************************************
78958 ** This file contains code associated with the ANALYZE command.
78959 **
78960 ** The ANALYZE command gather statistics about the content of tables
78961 ** and indices.  These statistics are made available to the query planner
78962 ** to help it make better decisions about how to perform queries.
78963 **
78964 ** The following system tables are or have been supported:
78965 **
78966 **    CREATE TABLE sqlcipher_stat1(tbl, idx, stat);
78967 **    CREATE TABLE sqlcipher_stat2(tbl, idx, sampleno, sample);
78968 **    CREATE TABLE sqlcipher_stat3(tbl, idx, nEq, nLt, nDLt, sample);
78969 **
78970 ** Additional tables might be added in future releases of SQLite.
78971 ** The sqlcipher_stat2 table is not created or used unless the SQLite version
78972 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
78973 ** with SQLCIPHER_ENABLE_STAT2.  The sqlcipher_stat2 table is deprecated.
78974 ** The sqlcipher_stat2 table is superceded by sqlcipher_stat3, which is only
78975 ** created and used by SQLite versions 3.7.9 and later and with
78976 ** SQLCIPHER_ENABLE_STAT3 defined.  The fucntionality of sqlcipher_stat3
78977 ** is a superset of sqlcipher_stat2.  
78978 **
78979 ** Format of sqlcipher_stat1:
78980 **
78981 ** There is normally one row per index, with the index identified by the
78982 ** name in the idx column.  The tbl column is the name of the table to
78983 ** which the index belongs.  In each such row, the stat column will be
78984 ** a string consisting of a list of integers.  The first integer in this
78985 ** list is the number of rows in the index and in the table.  The second
78986 ** integer is the average number of rows in the index that have the same
78987 ** value in the first column of the index.  The third integer is the average
78988 ** number of rows in the index that have the same value for the first two
78989 ** columns.  The N-th integer (for N>1) is the average number of rows in 
78990 ** the index which have the same value for the first N-1 columns.  For
78991 ** a K-column index, there will be K+1 integers in the stat column.  If
78992 ** the index is unique, then the last integer will be 1.
78993 **
78994 ** The list of integers in the stat column can optionally be followed
78995 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
78996 ** must be separated from the last integer by a single space.  If the
78997 ** "unordered" keyword is present, then the query planner assumes that
78998 ** the index is unordered and will not use the index for a range query.
78999 ** 
79000 ** If the sqlcipher_stat1.idx column is NULL, then the sqlcipher_stat1.stat
79001 ** column contains a single integer which is the (estimated) number of
79002 ** rows in the table identified by sqlcipher_stat1.tbl.
79003 **
79004 ** Format of sqlcipher_stat2:
79005 **
79006 ** The sqlcipher_stat2 is only created and is only used if SQLite is compiled
79007 ** with SQLCIPHER_ENABLE_STAT2 and if the SQLite version number is between
79008 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
79009 ** about the distribution of keys within an index.  The index is identified by
79010 ** the "idx" column and the "tbl" column is the name of the table to which
79011 ** the index belongs.  There are usually 10 rows in the sqlcipher_stat2
79012 ** table for each index.
79013 **
79014 ** The sqlcipher_stat2 entries for an index that have sampleno between 0 and 9
79015 ** inclusive are samples of the left-most key value in the index taken at
79016 ** evenly spaced points along the index.  Let the number of samples be S
79017 ** (10 in the standard build) and let C be the number of rows in the index.
79018 ** Then the sampled rows are given by:
79019 **
79020 **     rownumber = (i*C*2 + C)/(S*2)
79021 **
79022 ** For i between 0 and S-1.  Conceptually, the index space is divided into
79023 ** S uniform buckets and the samples are the middle row from each bucket.
79024 **
79025 ** The format for sqlcipher_stat2 is recorded here for legacy reference.  This
79026 ** version of SQLite does not support sqlcipher_stat2.  It neither reads nor
79027 ** writes the sqlcipher_stat2 table.  This version of SQLite only supports
79028 ** sqlcipher_stat3.
79029 **
79030 ** Format for sqlcipher_stat3:
79031 **
79032 ** The sqlcipher_stat3 is an enhancement to sqlcipher_stat2.  A new name is
79033 ** used to avoid compatibility problems.  
79034 **
79035 ** The format of the sqlcipher_stat3 table is similar to the format of
79036 ** the sqlcipher_stat2 table.  There are multiple entries for each index.
79037 ** The idx column names the index and the tbl column is the table of the
79038 ** index.  If the idx and tbl columns are the same, then the sample is
79039 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
79040 ** the left-most column of the index.  The nEq column is the approximate
79041 ** number of entires in the index whose left-most column exactly matches
79042 ** the sample.  nLt is the approximate number of entires whose left-most
79043 ** column is less than the sample.  The nDLt column is the approximate
79044 ** number of distinct left-most entries in the index that are less than
79045 ** the sample.
79046 **
79047 ** Future versions of SQLite might change to store a string containing
79048 ** multiple integers values in the nDLt column of sqlcipher_stat3.  The first
79049 ** integer will be the number of prior index entires that are distinct in
79050 ** the left-most column.  The second integer will be the number of prior index
79051 ** entries that are distinct in the first two columns.  The third integer
79052 ** will be the number of prior index entries that are distinct in the first
79053 ** three columns.  And so forth.  With that extension, the nDLt field is
79054 ** similar in function to the sqlcipher_stat1.stat field.
79055 **
79056 ** There can be an arbitrary number of sqlcipher_stat3 entries per index.
79057 ** The ANALYZE command will typically generate sqlcipher_stat3 tables
79058 ** that contain between 10 and 40 samples which are distributed across
79059 ** the key space, though not uniformly, and which include samples with
79060 ** largest possible nEq values.
79061 */
79062 #ifndef SQLCIPHER_OMIT_ANALYZE
79063
79064 /*
79065 ** This routine generates code that opens the sqlcipher_stat1 table for
79066 ** writing with cursor iStatCur. If the library was built with the
79067 ** SQLCIPHER_ENABLE_STAT3 macro defined, then the sqlcipher_stat3 table is
79068 ** opened for writing using cursor (iStatCur+1)
79069 **
79070 ** If the sqlcipher_stat1 tables does not previously exist, it is created.
79071 ** Similarly, if the sqlcipher_stat3 table does not exist and the library
79072 ** is compiled with SQLCIPHER_ENABLE_STAT3 defined, it is created. 
79073 **
79074 ** Argument zWhere may be a pointer to a buffer containing a table name,
79075 ** or it may be a NULL pointer. If it is not NULL, then all entries in
79076 ** the sqlcipher_stat1 and (if applicable) sqlcipher_stat3 tables associated
79077 ** with the named table are deleted. If zWhere==0, then code is generated
79078 ** to delete all stat table entries.
79079 */
79080 static void openStatTable(
79081   Parse *pParse,          /* Parsing context */
79082   int iDb,                /* The database we are looking in */
79083   int iStatCur,           /* Open the sqlcipher_stat1 table on this cursor */
79084   const char *zWhere,     /* Delete entries for this table or index */
79085   const char *zWhereType  /* Either "tbl" or "idx" */
79086 ){
79087   static const struct {
79088     const char *zName;
79089     const char *zCols;
79090   } aTable[] = {
79091     { "sqlcipher_stat1", "tbl,idx,stat" },
79092 #ifdef SQLCIPHER_ENABLE_STAT3
79093     { "sqlcipher_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
79094 #endif
79095   };
79096
79097   int aRoot[] = {0, 0};
79098   u8 aCreateTbl[] = {0, 0};
79099
79100   int i;
79101   sqlcipher3 *db = pParse->db;
79102   Db *pDb;
79103   Vdbe *v = sqlcipher3GetVdbe(pParse);
79104   if( v==0 ) return;
79105   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
79106   assert( sqlcipher3VdbeDb(v)==db );
79107   pDb = &db->aDb[iDb];
79108
79109   /* Create new statistic tables if they do not exist, or clear them
79110   ** if they do already exist.
79111   */
79112   for(i=0; i<ArraySize(aTable); i++){
79113     const char *zTab = aTable[i].zName;
79114     Table *pStat;
79115     if( (pStat = sqlcipher3FindTable(db, zTab, pDb->zName))==0 ){
79116       /* The sqlcipher_stat[12] table does not exist. Create it. Note that a 
79117       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
79118       ** of the new table in register pParse->regRoot. This is important 
79119       ** because the OpenWrite opcode below will be needing it. */
79120       sqlcipher3NestedParse(pParse,
79121           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
79122       );
79123       aRoot[i] = pParse->regRoot;
79124       aCreateTbl[i] = 1;
79125     }else{
79126       /* The table already exists. If zWhere is not NULL, delete all entries 
79127       ** associated with the table zWhere. If zWhere is NULL, delete the
79128       ** entire contents of the table. */
79129       aRoot[i] = pStat->tnum;
79130       sqlcipher3TableLock(pParse, iDb, aRoot[i], 1, zTab);
79131       if( zWhere ){
79132         sqlcipher3NestedParse(pParse,
79133            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
79134         );
79135       }else{
79136         /* The sqlcipher_stat[12] table already exists.  Delete all rows. */
79137         sqlcipher3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
79138       }
79139     }
79140   }
79141
79142   /* Open the sqlcipher_stat[13] tables for writing. */
79143   for(i=0; i<ArraySize(aTable); i++){
79144     sqlcipher3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
79145     sqlcipher3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
79146     sqlcipher3VdbeChangeP5(v, aCreateTbl[i]);
79147   }
79148 }
79149
79150 /*
79151 ** Recommended number of samples for sqlcipher_stat3
79152 */
79153 #ifndef SQLCIPHER_STAT3_SAMPLES
79154 # define SQLCIPHER_STAT3_SAMPLES 24
79155 #endif
79156
79157 /*
79158 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79159 ** share an instance of the following structure to hold their state
79160 ** information.
79161 */
79162 typedef struct Stat3Accum Stat3Accum;
79163 struct Stat3Accum {
79164   tRowcnt nRow;             /* Number of rows in the entire table */
79165   tRowcnt nPSample;         /* How often to do a periodic sample */
79166   int iMin;                 /* Index of entry with minimum nEq and hash */
79167   int mxSample;             /* Maximum number of samples to accumulate */
79168   int nSample;              /* Current number of samples */
79169   u32 iPrn;                 /* Pseudo-random number used for sampling */
79170   struct Stat3Sample {
79171     i64 iRowid;                /* Rowid in main table of the key */
79172     tRowcnt nEq;               /* sqlcipher_stat3.nEq */
79173     tRowcnt nLt;               /* sqlcipher_stat3.nLt */
79174     tRowcnt nDLt;              /* sqlcipher_stat3.nDLt */
79175     u8 isPSample;              /* True if a periodic sample */
79176     u32 iHash;                 /* Tiebreaker hash */
79177   } *a;                     /* An array of samples */
79178 };
79179
79180 #ifdef SQLCIPHER_ENABLE_STAT3
79181 /*
79182 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79183 ** are the number of rows in the table or index (C) and the number of samples
79184 ** to accumulate (S).
79185 **
79186 ** This routine allocates the Stat3Accum object.
79187 **
79188 ** The return value is the Stat3Accum object (P).
79189 */
79190 static void stat3Init(
79191   sqlcipher3_context *context,
79192   int argc,
79193   sqlcipher3_value **argv
79194 ){
79195   Stat3Accum *p;
79196   tRowcnt nRow;
79197   int mxSample;
79198   int n;
79199
79200   UNUSED_PARAMETER(argc);
79201   nRow = (tRowcnt)sqlcipher3_value_int64(argv[0]);
79202   mxSample = sqlcipher3_value_int(argv[1]);
79203   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79204   p = sqlcipher3_malloc( n );
79205   if( p==0 ){
79206     sqlcipher3_result_error_nomem(context);
79207     return;
79208   }
79209   memset(p, 0, n);
79210   p->a = (struct Stat3Sample*)&p[1];
79211   p->nRow = nRow;
79212   p->mxSample = mxSample;
79213   p->nPSample = p->nRow/(mxSample/3+1) + 1;
79214   sqlcipher3_randomness(sizeof(p->iPrn), &p->iPrn);
79215   sqlcipher3_result_blob(context, p, sizeof(p), sqlcipher3_free);
79216 }
79217 static const FuncDef stat3InitFuncdef = {
79218   2,                /* nArg */
79219   SQLCIPHER_UTF8,      /* iPrefEnc */
79220   0,                /* flags */
79221   0,                /* pUserData */
79222   0,                /* pNext */
79223   stat3Init,        /* xFunc */
79224   0,                /* xStep */
79225   0,                /* xFinalize */
79226   "stat3_init",     /* zName */
79227   0,                /* pHash */
79228   0                 /* pDestructor */
79229 };
79230
79231
79232 /*
79233 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79234 ** arguments describe a single key instance.  This routine makes the 
79235 ** decision about whether or not to retain this key for the sqlcipher_stat3
79236 ** table.
79237 **
79238 ** The return value is NULL.
79239 */
79240 static void stat3Push(
79241   sqlcipher3_context *context,
79242   int argc,
79243   sqlcipher3_value **argv
79244 ){
79245   Stat3Accum *p = (Stat3Accum*)sqlcipher3_value_blob(argv[4]);
79246   tRowcnt nEq = sqlcipher3_value_int64(argv[0]);
79247   tRowcnt nLt = sqlcipher3_value_int64(argv[1]);
79248   tRowcnt nDLt = sqlcipher3_value_int64(argv[2]);
79249   i64 rowid = sqlcipher3_value_int64(argv[3]);
79250   u8 isPSample = 0;
79251   u8 doInsert = 0;
79252   int iMin = p->iMin;
79253   struct Stat3Sample *pSample;
79254   int i;
79255   u32 h;
79256
79257   UNUSED_PARAMETER(context);
79258   UNUSED_PARAMETER(argc);
79259   if( nEq==0 ) return;
79260   h = p->iPrn = p->iPrn*1103515245 + 12345;
79261   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79262     doInsert = isPSample = 1;
79263   }else if( p->nSample<p->mxSample ){
79264     doInsert = 1;
79265   }else{
79266     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79267       doInsert = 1;
79268     }
79269   }
79270   if( !doInsert ) return;
79271   if( p->nSample==p->mxSample ){
79272     assert( p->nSample - iMin - 1 >= 0 );
79273     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79274     pSample = &p->a[p->nSample-1];
79275   }else{
79276     pSample = &p->a[p->nSample++];
79277   }
79278   pSample->iRowid = rowid;
79279   pSample->nEq = nEq;
79280   pSample->nLt = nLt;
79281   pSample->nDLt = nDLt;
79282   pSample->iHash = h;
79283   pSample->isPSample = isPSample;
79284
79285   /* Find the new minimum */
79286   if( p->nSample==p->mxSample ){
79287     pSample = p->a;
79288     i = 0;
79289     while( pSample->isPSample ){
79290       i++;
79291       pSample++;
79292       assert( i<p->nSample );
79293     }
79294     nEq = pSample->nEq;
79295     h = pSample->iHash;
79296     iMin = i;
79297     for(i++, pSample++; i<p->nSample; i++, pSample++){
79298       if( pSample->isPSample ) continue;
79299       if( pSample->nEq<nEq
79300        || (pSample->nEq==nEq && pSample->iHash<h)
79301       ){
79302         iMin = i;
79303         nEq = pSample->nEq;
79304         h = pSample->iHash;
79305       }
79306     }
79307     p->iMin = iMin;
79308   }
79309 }
79310 static const FuncDef stat3PushFuncdef = {
79311   5,                /* nArg */
79312   SQLCIPHER_UTF8,      /* iPrefEnc */
79313   0,                /* flags */
79314   0,                /* pUserData */
79315   0,                /* pNext */
79316   stat3Push,        /* xFunc */
79317   0,                /* xStep */
79318   0,                /* xFinalize */
79319   "stat3_push",     /* zName */
79320   0,                /* pHash */
79321   0                 /* pDestructor */
79322 };
79323
79324 /*
79325 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79326 ** used to query the results.  Content is returned for the Nth sqlcipher_stat3
79327 ** row where N is between 0 and S-1 and S is the number of samples.  The
79328 ** value returned depends on the number of arguments.
79329 **
79330 **   argc==2    result:  rowid
79331 **   argc==3    result:  nEq
79332 **   argc==4    result:  nLt
79333 **   argc==5    result:  nDLt
79334 */
79335 static void stat3Get(
79336   sqlcipher3_context *context,
79337   int argc,
79338   sqlcipher3_value **argv
79339 ){
79340   int n = sqlcipher3_value_int(argv[1]);
79341   Stat3Accum *p = (Stat3Accum*)sqlcipher3_value_blob(argv[0]);
79342
79343   assert( p!=0 );
79344   if( p->nSample<=n ) return;
79345   switch( argc ){
79346     case 2:  sqlcipher3_result_int64(context, p->a[n].iRowid); break;
79347     case 3:  sqlcipher3_result_int64(context, p->a[n].nEq);    break;
79348     case 4:  sqlcipher3_result_int64(context, p->a[n].nLt);    break;
79349     default: sqlcipher3_result_int64(context, p->a[n].nDLt);   break;
79350   }
79351 }
79352 static const FuncDef stat3GetFuncdef = {
79353   -1,               /* nArg */
79354   SQLCIPHER_UTF8,      /* iPrefEnc */
79355   0,                /* flags */
79356   0,                /* pUserData */
79357   0,                /* pNext */
79358   stat3Get,         /* xFunc */
79359   0,                /* xStep */
79360   0,                /* xFinalize */
79361   "stat3_get",     /* zName */
79362   0,                /* pHash */
79363   0                 /* pDestructor */
79364 };
79365 #endif /* SQLCIPHER_ENABLE_STAT3 */
79366
79367
79368
79369
79370 /*
79371 ** Generate code to do an analysis of all indices associated with
79372 ** a single table.
79373 */
79374 static void analyzeOneTable(
79375   Parse *pParse,   /* Parser context */
79376   Table *pTab,     /* Table whose indices are to be analyzed */
79377   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79378   int iStatCur,    /* Index of VdbeCursor that writes the sqlcipher_stat1 table */
79379   int iMem         /* Available memory locations begin here */
79380 ){
79381   sqlcipher3 *db = pParse->db;    /* Database handle */
79382   Index *pIdx;                 /* An index to being analyzed */
79383   int iIdxCur;                 /* Cursor open on index being analyzed */
79384   Vdbe *v;                     /* The virtual machine being built up */
79385   int i;                       /* Loop counter */
79386   int topOfLoop;               /* The top of the loop */
79387   int endOfLoop;               /* The end of the loop */
79388   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79389   int iDb;                     /* Index of database containing pTab */
79390   int regTabname = iMem++;     /* Register containing table name */
79391   int regIdxname = iMem++;     /* Register containing index name */
79392   int regStat1 = iMem++;       /* The stat column of sqlcipher_stat1 */
79393 #ifdef SQLCIPHER_ENABLE_STAT3
79394   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79395   int regNumLt = iMem++;       /* Number of keys less than regSample */
79396   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79397   int regSample = iMem++;      /* The next sample value */
79398   int regRowid = regSample;    /* Rowid of a sample */
79399   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79400   int regLoop = iMem++;        /* Loop counter */
79401   int regCount = iMem++;       /* Number of rows in the table or index */
79402   int regTemp1 = iMem++;       /* Intermediate register */
79403   int regTemp2 = iMem++;       /* Intermediate register */
79404   int once = 1;                /* One-time initialization */
79405   int shortJump = 0;           /* Instruction address */
79406   int iTabCur = pParse->nTab++; /* Table cursor */
79407 #endif
79408   int regCol = iMem++;         /* Content of a column in analyzed table */
79409   int regRec = iMem++;         /* Register holding completed record */
79410   int regTemp = iMem++;        /* Temporary use register */
79411   int regNewRowid = iMem++;    /* Rowid for the inserted record */
79412
79413
79414   v = sqlcipher3GetVdbe(pParse);
79415   if( v==0 || NEVER(pTab==0) ){
79416     return;
79417   }
79418   if( pTab->tnum==0 ){
79419     /* Do not gather statistics on views or virtual tables */
79420     return;
79421   }
79422   if( memcmp(pTab->zName, "sqlcipher_", 7)==0 ){
79423     /* Do not gather statistics on system tables */
79424     return;
79425   }
79426   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
79427   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
79428   assert( iDb>=0 );
79429   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
79430 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
79431   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_ANALYZE, pTab->zName, 0,
79432       db->aDb[iDb].zName ) ){
79433     return;
79434   }
79435 #endif
79436
79437   /* Establish a read-lock on the table at the shared-cache level. */
79438   sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79439
79440   iIdxCur = pParse->nTab++;
79441   sqlcipher3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79442   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79443     int nCol;
79444     KeyInfo *pKey;
79445     int addrIfNot = 0;           /* address of OP_IfNot */
79446     int *aChngAddr;              /* Array of jump instruction addresses */
79447
79448     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79449     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79450     nCol = pIdx->nColumn;
79451     aChngAddr = sqlcipher3DbMallocRaw(db, sizeof(int)*nCol);
79452     if( aChngAddr==0 ) continue;
79453     pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
79454     if( iMem+1+(nCol*2)>pParse->nMem ){
79455       pParse->nMem = iMem+1+(nCol*2);
79456     }
79457
79458     /* Open a cursor to the index to be analyzed. */
79459     assert( iDb==sqlcipher3SchemaToIndex(db, pIdx->pSchema) );
79460     sqlcipher3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79461         (char *)pKey, P4_KEYINFO_HANDOFF);
79462     VdbeComment((v, "%s", pIdx->zName));
79463
79464     /* Populate the register containing the index name. */
79465     sqlcipher3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79466
79467 #ifdef SQLCIPHER_ENABLE_STAT3
79468     if( once ){
79469       once = 0;
79470       sqlcipher3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79471     }
79472     sqlcipher3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79473     sqlcipher3VdbeAddOp2(v, OP_Integer, SQLCIPHER_STAT3_SAMPLES, regTemp1);
79474     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79475     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79476     sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79477     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79478                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
79479     sqlcipher3VdbeChangeP5(v, 2);
79480 #endif /* SQLCIPHER_ENABLE_STAT3 */
79481
79482     /* The block of memory cells initialized here is used as follows.
79483     **
79484     **    iMem:                
79485     **        The total number of rows in the table.
79486     **
79487     **    iMem+1 .. iMem+nCol: 
79488     **        Number of distinct entries in index considering the 
79489     **        left-most N columns only, where N is between 1 and nCol, 
79490     **        inclusive.
79491     **
79492     **    iMem+nCol+1 .. Mem+2*nCol:  
79493     **        Previous value of indexed columns, from left to right.
79494     **
79495     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
79496     ** initialized to contain an SQL NULL.
79497     */
79498     for(i=0; i<=nCol; i++){
79499       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79500     }
79501     for(i=0; i<nCol; i++){
79502       sqlcipher3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79503     }
79504
79505     /* Start the analysis loop. This loop runs through all the entries in
79506     ** the index b-tree.  */
79507     endOfLoop = sqlcipher3VdbeMakeLabel(v);
79508     sqlcipher3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79509     topOfLoop = sqlcipher3VdbeCurrentAddr(v);
79510     sqlcipher3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79511
79512     for(i=0; i<nCol; i++){
79513       CollSeq *pColl;
79514       sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79515       if( i==0 ){
79516         /* Always record the very first row */
79517         addrIfNot = sqlcipher3VdbeAddOp1(v, OP_IfNot, iMem+1);
79518       }
79519       assert( pIdx->azColl!=0 );
79520       assert( pIdx->azColl[i]!=0 );
79521       pColl = sqlcipher3LocateCollSeq(pParse, pIdx->azColl[i]);
79522       aChngAddr[i] = sqlcipher3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79523                                       (char*)pColl, P4_COLLSEQ);
79524       sqlcipher3VdbeChangeP5(v, SQLCIPHER_NULLEQ);
79525       VdbeComment((v, "jump if column %d changed", i));
79526 #ifdef SQLCIPHER_ENABLE_STAT3
79527       if( i==0 ){
79528         sqlcipher3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79529         VdbeComment((v, "incr repeat count"));
79530       }
79531 #endif
79532     }
79533     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79534     for(i=0; i<nCol; i++){
79535       sqlcipher3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79536       if( i==0 ){
79537         sqlcipher3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79538 #ifdef SQLCIPHER_ENABLE_STAT3
79539         sqlcipher3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79540                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
79541         sqlcipher3VdbeChangeP5(v, 5);
79542         sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79543         sqlcipher3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79544         sqlcipher3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79545         sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79546 #endif        
79547       }
79548       sqlcipher3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79549       sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79550     }
79551     sqlcipher3DbFree(db, aChngAddr);
79552
79553     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79554     sqlcipher3VdbeResolveLabel(v, endOfLoop);
79555
79556     sqlcipher3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79557     sqlcipher3VdbeAddOp1(v, OP_Close, iIdxCur);
79558 #ifdef SQLCIPHER_ENABLE_STAT3
79559     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79560                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
79561     sqlcipher3VdbeChangeP5(v, 5);
79562     sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79563     shortJump = 
79564     sqlcipher3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79565     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79566                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79567     sqlcipher3VdbeChangeP5(v, 2);
79568     sqlcipher3VdbeAddOp1(v, OP_IsNull, regTemp1);
79569     sqlcipher3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79570     sqlcipher3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79571     sqlcipher3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79572     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79573                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79574     sqlcipher3VdbeChangeP5(v, 3);
79575     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79576                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79577     sqlcipher3VdbeChangeP5(v, 4);
79578     sqlcipher3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79579                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79580     sqlcipher3VdbeChangeP5(v, 5);
79581     sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79582     sqlcipher3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79583     sqlcipher3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79584     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79585     sqlcipher3VdbeJumpHere(v, shortJump+2);
79586 #endif        
79587
79588     /* Store the results in sqlcipher_stat1.
79589     **
79590     ** The result is a single row of the sqlcipher_stat1 table.  The first
79591     ** two columns are the names of the table and index.  The third column
79592     ** is a string composed of a list of integer statistics about the
79593     ** index.  The first integer in the list is the total number of entries
79594     ** in the index.  There is one additional integer in the list for each
79595     ** column of the table.  This additional integer is a guess of how many
79596     ** rows of the table the index will select.  If D is the count of distinct
79597     ** values and K is the total number of rows, then the integer is computed
79598     ** as:
79599     **
79600     **        I = (K+D-1)/D
79601     **
79602     ** If K==0 then no entry is made into the sqlcipher_stat1 table.  
79603     ** If K>0 then it is always the case the D>0 so division by zero
79604     ** is never possible.
79605     */
79606     sqlcipher3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79607     if( jZeroRows<0 ){
79608       jZeroRows = sqlcipher3VdbeAddOp1(v, OP_IfNot, iMem);
79609     }
79610     for(i=0; i<nCol; i++){
79611       sqlcipher3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79612       sqlcipher3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79613       sqlcipher3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79614       sqlcipher3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79615       sqlcipher3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79616       sqlcipher3VdbeAddOp1(v, OP_ToInt, regTemp);
79617       sqlcipher3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79618     }
79619     sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79620     sqlcipher3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79621     sqlcipher3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79622     sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
79623   }
79624
79625   /* If the table has no indices, create a single sqlcipher_stat1 entry
79626   ** containing NULL as the index name and the row count as the content.
79627   */
79628   if( pTab->pIndex==0 ){
79629     sqlcipher3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79630     VdbeComment((v, "%s", pTab->zName));
79631     sqlcipher3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79632     sqlcipher3VdbeAddOp1(v, OP_Close, iIdxCur);
79633     jZeroRows = sqlcipher3VdbeAddOp1(v, OP_IfNot, regStat1);
79634   }else{
79635     sqlcipher3VdbeJumpHere(v, jZeroRows);
79636     jZeroRows = sqlcipher3VdbeAddOp0(v, OP_Goto);
79637   }
79638   sqlcipher3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79639   sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79640   sqlcipher3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79641   sqlcipher3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79642   sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
79643   if( pParse->nMem<regRec ) pParse->nMem = regRec;
79644   sqlcipher3VdbeJumpHere(v, jZeroRows);
79645 }
79646
79647
79648 /*
79649 ** Generate code that will cause the most recent index analysis to
79650 ** be loaded into internal hash tables where is can be used.
79651 */
79652 static void loadAnalysis(Parse *pParse, int iDb){
79653   Vdbe *v = sqlcipher3GetVdbe(pParse);
79654   if( v ){
79655     sqlcipher3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79656   }
79657 }
79658
79659 /*
79660 ** Generate code that will do an analysis of an entire database
79661 */
79662 static void analyzeDatabase(Parse *pParse, int iDb){
79663   sqlcipher3 *db = pParse->db;
79664   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79665   HashElem *k;
79666   int iStatCur;
79667   int iMem;
79668
79669   sqlcipher3BeginWriteOperation(pParse, 0, iDb);
79670   iStatCur = pParse->nTab;
79671   pParse->nTab += 3;
79672   openStatTable(pParse, iDb, iStatCur, 0, 0);
79673   iMem = pParse->nMem+1;
79674   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
79675   for(k=sqlcipherHashFirst(&pSchema->tblHash); k; k=sqlcipherHashNext(k)){
79676     Table *pTab = (Table*)sqlcipherHashData(k);
79677     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
79678   }
79679   loadAnalysis(pParse, iDb);
79680 }
79681
79682 /*
79683 ** Generate code that will do an analysis of a single table in
79684 ** a database.  If pOnlyIdx is not NULL then it is a single index
79685 ** in pTab that should be analyzed.
79686 */
79687 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
79688   int iDb;
79689   int iStatCur;
79690
79691   assert( pTab!=0 );
79692   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
79693   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
79694   sqlcipher3BeginWriteOperation(pParse, 0, iDb);
79695   iStatCur = pParse->nTab;
79696   pParse->nTab += 3;
79697   if( pOnlyIdx ){
79698     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
79699   }else{
79700     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
79701   }
79702   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
79703   loadAnalysis(pParse, iDb);
79704 }
79705
79706 /*
79707 ** Generate code for the ANALYZE command.  The parser calls this routine
79708 ** when it recognizes an ANALYZE command.
79709 **
79710 **        ANALYZE                            -- 1
79711 **        ANALYZE  <database>                -- 2
79712 **        ANALYZE  ?<database>.?<tablename>  -- 3
79713 **
79714 ** Form 1 causes all indices in all attached databases to be analyzed.
79715 ** Form 2 analyzes all indices the single database named.
79716 ** Form 3 analyzes all indices associated with the named table.
79717 */
79718 SQLCIPHER_PRIVATE void sqlcipher3Analyze(Parse *pParse, Token *pName1, Token *pName2){
79719   sqlcipher3 *db = pParse->db;
79720   int iDb;
79721   int i;
79722   char *z, *zDb;
79723   Table *pTab;
79724   Index *pIdx;
79725   Token *pTableName;
79726
79727   /* Read the database schema. If an error occurs, leave an error message
79728   ** and code in pParse and return NULL. */
79729   assert( sqlcipher3BtreeHoldsAllMutexes(pParse->db) );
79730   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
79731     return;
79732   }
79733
79734   assert( pName2!=0 || pName1==0 );
79735   if( pName1==0 ){
79736     /* Form 1:  Analyze everything */
79737     for(i=0; i<db->nDb; i++){
79738       if( i==1 ) continue;  /* Do not analyze the TEMP database */
79739       analyzeDatabase(pParse, i);
79740     }
79741   }else if( pName2->n==0 ){
79742     /* Form 2:  Analyze the database or table named */
79743     iDb = sqlcipher3FindDb(db, pName1);
79744     if( iDb>=0 ){
79745       analyzeDatabase(pParse, iDb);
79746     }else{
79747       z = sqlcipher3NameFromToken(db, pName1);
79748       if( z ){
79749         if( (pIdx = sqlcipher3FindIndex(db, z, 0))!=0 ){
79750           analyzeTable(pParse, pIdx->pTable, pIdx);
79751         }else if( (pTab = sqlcipher3LocateTable(pParse, 0, z, 0))!=0 ){
79752           analyzeTable(pParse, pTab, 0);
79753         }
79754         sqlcipher3DbFree(db, z);
79755       }
79756     }
79757   }else{
79758     /* Form 3: Analyze the fully qualified table name */
79759     iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pTableName);
79760     if( iDb>=0 ){
79761       zDb = db->aDb[iDb].zName;
79762       z = sqlcipher3NameFromToken(db, pTableName);
79763       if( z ){
79764         if( (pIdx = sqlcipher3FindIndex(db, z, zDb))!=0 ){
79765           analyzeTable(pParse, pIdx->pTable, pIdx);
79766         }else if( (pTab = sqlcipher3LocateTable(pParse, 0, z, zDb))!=0 ){
79767           analyzeTable(pParse, pTab, 0);
79768         }
79769         sqlcipher3DbFree(db, z);
79770       }
79771     }   
79772   }
79773 }
79774
79775 /*
79776 ** Used to pass information from the analyzer reader through to the
79777 ** callback routine.
79778 */
79779 typedef struct analysisInfo analysisInfo;
79780 struct analysisInfo {
79781   sqlcipher3 *db;
79782   const char *zDatabase;
79783 };
79784
79785 /*
79786 ** This callback is invoked once for each index when reading the
79787 ** sqlcipher_stat1 table.  
79788 **
79789 **     argv[0] = name of the table
79790 **     argv[1] = name of the index (might be NULL)
79791 **     argv[2] = results of analysis - on integer for each column
79792 **
79793 ** Entries for which argv[1]==NULL simply record the number of rows in
79794 ** the table.
79795 */
79796 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
79797   analysisInfo *pInfo = (analysisInfo*)pData;
79798   Index *pIndex;
79799   Table *pTable;
79800   int i, c, n;
79801   tRowcnt v;
79802   const char *z;
79803
79804   assert( argc==3 );
79805   UNUSED_PARAMETER2(NotUsed, argc);
79806
79807   if( argv==0 || argv[0]==0 || argv[2]==0 ){
79808     return 0;
79809   }
79810   pTable = sqlcipher3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
79811   if( pTable==0 ){
79812     return 0;
79813   }
79814   if( argv[1] ){
79815     pIndex = sqlcipher3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
79816   }else{
79817     pIndex = 0;
79818   }
79819   n = pIndex ? pIndex->nColumn : 0;
79820   z = argv[2];
79821   for(i=0; *z && i<=n; i++){
79822     v = 0;
79823     while( (c=z[0])>='0' && c<='9' ){
79824       v = v*10 + c - '0';
79825       z++;
79826     }
79827     if( i==0 ) pTable->nRowEst = v;
79828     if( pIndex==0 ) break;
79829     pIndex->aiRowEst[i] = v;
79830     if( *z==' ' ) z++;
79831     if( memcmp(z, "unordered", 10)==0 ){
79832       pIndex->bUnordered = 1;
79833       break;
79834     }
79835   }
79836   return 0;
79837 }
79838
79839 /*
79840 ** If the Index.aSample variable is not NULL, delete the aSample[] array
79841 ** and its contents.
79842 */
79843 SQLCIPHER_PRIVATE void sqlcipher3DeleteIndexSamples(sqlcipher3 *db, Index *pIdx){
79844 #ifdef SQLCIPHER_ENABLE_STAT3
79845   if( pIdx->aSample ){
79846     int j;
79847     for(j=0; j<pIdx->nSample; j++){
79848       IndexSample *p = &pIdx->aSample[j];
79849       if( p->eType==SQLCIPHER_TEXT || p->eType==SQLCIPHER_BLOB ){
79850         sqlcipher3DbFree(db, p->u.z);
79851       }
79852     }
79853     sqlcipher3DbFree(db, pIdx->aSample);
79854   }
79855   if( db && db->pnBytesFreed==0 ){
79856     pIdx->nSample = 0;
79857     pIdx->aSample = 0;
79858   }
79859 #else
79860   UNUSED_PARAMETER(db);
79861   UNUSED_PARAMETER(pIdx);
79862 #endif
79863 }
79864
79865 #ifdef SQLCIPHER_ENABLE_STAT3
79866 /*
79867 ** Load content from the sqlcipher_stat3 table into the Index.aSample[]
79868 ** arrays of all indices.
79869 */
79870 static int loadStat3(sqlcipher3 *db, const char *zDb){
79871   int rc;                       /* Result codes from subroutines */
79872   sqlcipher3_stmt *pStmt = 0;      /* An SQL statement being run */
79873   char *zSql;                   /* Text of the SQL statement */
79874   Index *pPrevIdx = 0;          /* Previous index in the loop */
79875   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
79876   int eType;                    /* Datatype of a sample */
79877   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
79878
79879   if( !sqlcipher3FindTable(db, "sqlcipher_stat3", zDb) ){
79880     return SQLCIPHER_OK;
79881   }
79882
79883   zSql = sqlcipher3MPrintf(db, 
79884       "SELECT idx,count(*) FROM %Q.sqlcipher_stat3"
79885       " GROUP BY idx", zDb);
79886   if( !zSql ){
79887     return SQLCIPHER_NOMEM;
79888   }
79889   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
79890   sqlcipher3DbFree(db, zSql);
79891   if( rc ) return rc;
79892
79893   while( sqlcipher3_step(pStmt)==SQLCIPHER_ROW ){
79894     char *zIndex;   /* Index name */
79895     Index *pIdx;    /* Pointer to the index object */
79896     int nSample;    /* Number of samples */
79897
79898     zIndex = (char *)sqlcipher3_column_text(pStmt, 0);
79899     if( zIndex==0 ) continue;
79900     nSample = sqlcipher3_column_int(pStmt, 1);
79901     pIdx = sqlcipher3FindIndex(db, zIndex, zDb);
79902     if( pIdx==0 ) continue;
79903     assert( pIdx->nSample==0 );
79904     pIdx->nSample = nSample;
79905     pIdx->aSample = sqlcipher3MallocZero( nSample*sizeof(IndexSample) );
79906     pIdx->avgEq = pIdx->aiRowEst[1];
79907     if( pIdx->aSample==0 ){
79908       db->mallocFailed = 1;
79909       sqlcipher3_finalize(pStmt);
79910       return SQLCIPHER_NOMEM;
79911     }
79912   }
79913   rc = sqlcipher3_finalize(pStmt);
79914   if( rc ) return rc;
79915
79916   zSql = sqlcipher3MPrintf(db, 
79917       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlcipher_stat3", zDb);
79918   if( !zSql ){
79919     return SQLCIPHER_NOMEM;
79920   }
79921   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
79922   sqlcipher3DbFree(db, zSql);
79923   if( rc ) return rc;
79924
79925   while( sqlcipher3_step(pStmt)==SQLCIPHER_ROW ){
79926     char *zIndex;   /* Index name */
79927     Index *pIdx;    /* Pointer to the index object */
79928     int i;          /* Loop counter */
79929     tRowcnt sumEq;  /* Sum of the nEq values */
79930
79931     zIndex = (char *)sqlcipher3_column_text(pStmt, 0);
79932     if( zIndex==0 ) continue;
79933     pIdx = sqlcipher3FindIndex(db, zIndex, zDb);
79934     if( pIdx==0 ) continue;
79935     if( pIdx==pPrevIdx ){
79936       idx++;
79937     }else{
79938       pPrevIdx = pIdx;
79939       idx = 0;
79940     }
79941     assert( idx<pIdx->nSample );
79942     pSample = &pIdx->aSample[idx];
79943     pSample->nEq = (tRowcnt)sqlcipher3_column_int64(pStmt, 1);
79944     pSample->nLt = (tRowcnt)sqlcipher3_column_int64(pStmt, 2);
79945     pSample->nDLt = (tRowcnt)sqlcipher3_column_int64(pStmt, 3);
79946     if( idx==pIdx->nSample-1 ){
79947       if( pSample->nDLt>0 ){
79948         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
79949         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
79950       }
79951       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
79952     }
79953     eType = sqlcipher3_column_type(pStmt, 4);
79954     pSample->eType = (u8)eType;
79955     switch( eType ){
79956       case SQLCIPHER_INTEGER: {
79957         pSample->u.i = sqlcipher3_column_int64(pStmt, 4);
79958         break;
79959       }
79960       case SQLCIPHER_FLOAT: {
79961         pSample->u.r = sqlcipher3_column_double(pStmt, 4);
79962         break;
79963       }
79964       case SQLCIPHER_NULL: {
79965         break;
79966       }
79967       default: assert( eType==SQLCIPHER_TEXT || eType==SQLCIPHER_BLOB ); {
79968         const char *z = (const char *)(
79969               (eType==SQLCIPHER_BLOB) ?
79970               sqlcipher3_column_blob(pStmt, 4):
79971               sqlcipher3_column_text(pStmt, 4)
79972            );
79973         int n = z ? sqlcipher3_column_bytes(pStmt, 4) : 0;
79974         pSample->nByte = n;
79975         if( n < 1){
79976           pSample->u.z = 0;
79977         }else{
79978           pSample->u.z = sqlcipher3Malloc(n);
79979           if( pSample->u.z==0 ){
79980             db->mallocFailed = 1;
79981             sqlcipher3_finalize(pStmt);
79982             return SQLCIPHER_NOMEM;
79983           }
79984           memcpy(pSample->u.z, z, n);
79985         }
79986       }
79987     }
79988   }
79989   return sqlcipher3_finalize(pStmt);
79990 }
79991 #endif /* SQLCIPHER_ENABLE_STAT3 */
79992
79993 /*
79994 ** Load the content of the sqlcipher_stat1 and sqlcipher_stat3 tables. The
79995 ** contents of sqlcipher_stat1 are used to populate the Index.aiRowEst[]
79996 ** arrays. The contents of sqlcipher_stat3 are used to populate the
79997 ** Index.aSample[] arrays.
79998 **
79999 ** If the sqlcipher_stat1 table is not present in the database, SQLCIPHER_ERROR
80000 ** is returned. In this case, even if SQLCIPHER_ENABLE_STAT3 was defined 
80001 ** during compilation and the sqlcipher_stat3 table is present, no data is 
80002 ** read from it.
80003 **
80004 ** If SQLCIPHER_ENABLE_STAT3 was defined during compilation and the 
80005 ** sqlcipher_stat3 table is not present in the database, SQLCIPHER_ERROR is
80006 ** returned. However, in this case, data is read from the sqlcipher_stat1
80007 ** table (if it is present) before returning.
80008 **
80009 ** If an OOM error occurs, this function always sets db->mallocFailed.
80010 ** This means if the caller does not care about other errors, the return
80011 ** code may be ignored.
80012 */
80013 SQLCIPHER_PRIVATE int sqlcipher3AnalysisLoad(sqlcipher3 *db, int iDb){
80014   analysisInfo sInfo;
80015   HashElem *i;
80016   char *zSql;
80017   int rc;
80018
80019   assert( iDb>=0 && iDb<db->nDb );
80020   assert( db->aDb[iDb].pBt!=0 );
80021
80022   /* Clear any prior statistics */
80023   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
80024   for(i=sqlcipherHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqlcipherHashNext(i)){
80025     Index *pIdx = sqlcipherHashData(i);
80026     sqlcipher3DefaultRowEst(pIdx);
80027 #ifdef SQLCIPHER_ENABLE_STAT3
80028     sqlcipher3DeleteIndexSamples(db, pIdx);
80029     pIdx->aSample = 0;
80030 #endif
80031   }
80032
80033   /* Check to make sure the sqlcipher_stat1 table exists */
80034   sInfo.db = db;
80035   sInfo.zDatabase = db->aDb[iDb].zName;
80036   if( sqlcipher3FindTable(db, "sqlcipher_stat1", sInfo.zDatabase)==0 ){
80037     return SQLCIPHER_ERROR;
80038   }
80039
80040   /* Load new statistics out of the sqlcipher_stat1 table */
80041   zSql = sqlcipher3MPrintf(db, 
80042       "SELECT tbl,idx,stat FROM %Q.sqlcipher_stat1", sInfo.zDatabase);
80043   if( zSql==0 ){
80044     rc = SQLCIPHER_NOMEM;
80045   }else{
80046     rc = sqlcipher3_exec(db, zSql, analysisLoader, &sInfo, 0);
80047     sqlcipher3DbFree(db, zSql);
80048   }
80049
80050
80051   /* Load the statistics from the sqlcipher_stat3 table. */
80052 #ifdef SQLCIPHER_ENABLE_STAT3
80053   if( rc==SQLCIPHER_OK ){
80054     rc = loadStat3(db, sInfo.zDatabase);
80055   }
80056 #endif
80057
80058   if( rc==SQLCIPHER_NOMEM ){
80059     db->mallocFailed = 1;
80060   }
80061   return rc;
80062 }
80063
80064
80065 #endif /* SQLCIPHER_OMIT_ANALYZE */
80066
80067 /************** End of analyze.c *********************************************/
80068 /************** Begin file attach.c ******************************************/
80069 /*
80070 ** 2003 April 6
80071 **
80072 ** The author disclaims copyright to this source code.  In place of
80073 ** a legal notice, here is a blessing:
80074 **
80075 **    May you do good and not evil.
80076 **    May you find forgiveness for yourself and forgive others.
80077 **    May you share freely, never taking more than you give.
80078 **
80079 *************************************************************************
80080 ** This file contains code used to implement the ATTACH and DETACH commands.
80081 */
80082
80083 #ifndef SQLCIPHER_OMIT_ATTACH
80084 /*
80085 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
80086 ** is slightly different from resolving a normal SQL expression, because simple
80087 ** identifiers are treated as strings, not possible column names or aliases.
80088 **
80089 ** i.e. if the parser sees:
80090 **
80091 **     ATTACH DATABASE abc AS def
80092 **
80093 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
80094 ** looking for columns of the same name.
80095 **
80096 ** This only applies to the root node of pExpr, so the statement:
80097 **
80098 **     ATTACH DATABASE abc||def AS 'db2'
80099 **
80100 ** will fail because neither abc or def can be resolved.
80101 */
80102 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
80103 {
80104   int rc = SQLCIPHER_OK;
80105   if( pExpr ){
80106     if( pExpr->op!=TK_ID ){
80107       rc = sqlcipher3ResolveExprNames(pName, pExpr);
80108       if( rc==SQLCIPHER_OK && !sqlcipher3ExprIsConstant(pExpr) ){
80109         sqlcipher3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
80110         return SQLCIPHER_ERROR;
80111       }
80112     }else{
80113       pExpr->op = TK_STRING;
80114     }
80115   }
80116   return rc;
80117 }
80118
80119 /*
80120 ** An SQL user-function registered to do the work of an ATTACH statement. The
80121 ** three arguments to the function come directly from an attach statement:
80122 **
80123 **     ATTACH DATABASE x AS y KEY z
80124 **
80125 **     SELECT sqlcipher_attach(x, y, z)
80126 **
80127 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
80128 ** third argument.
80129 */
80130 static void attachFunc(
80131   sqlcipher3_context *context,
80132   int NotUsed,
80133   sqlcipher3_value **argv
80134 ){
80135   int i;
80136   int rc = 0;
80137   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
80138   const char *zName;
80139   const char *zFile;
80140   char *zPath = 0;
80141   char *zErr = 0;
80142   unsigned int flags;
80143   Db *aNew;
80144   char *zErrDyn = 0;
80145   sqlcipher3_vfs *pVfs;
80146
80147   UNUSED_PARAMETER(NotUsed);
80148
80149   zFile = (const char *)sqlcipher3_value_text(argv[0]);
80150   zName = (const char *)sqlcipher3_value_text(argv[1]);
80151   if( zFile==0 ) zFile = "";
80152   if( zName==0 ) zName = "";
80153
80154   /* Check for the following errors:
80155   **
80156   **     * Too many attached databases,
80157   **     * Transaction currently open
80158   **     * Specified database name already being used.
80159   */
80160   if( db->nDb>=db->aLimit[SQLCIPHER_LIMIT_ATTACHED]+2 ){
80161     zErrDyn = sqlcipher3MPrintf(db, "too many attached databases - max %d", 
80162       db->aLimit[SQLCIPHER_LIMIT_ATTACHED]
80163     );
80164     goto attach_error;
80165   }
80166   if( !db->autoCommit ){
80167     zErrDyn = sqlcipher3MPrintf(db, "cannot ATTACH database within transaction");
80168     goto attach_error;
80169   }
80170   for(i=0; i<db->nDb; i++){
80171     char *z = db->aDb[i].zName;
80172     assert( z && zName );
80173     if( sqlcipher3StrICmp(z, zName)==0 ){
80174       zErrDyn = sqlcipher3MPrintf(db, "database %s is already in use", zName);
80175       goto attach_error;
80176     }
80177   }
80178
80179   /* Allocate the new entry in the db->aDb[] array and initialise the schema
80180   ** hash tables.
80181   */
80182   if( db->aDb==db->aDbStatic ){
80183     aNew = sqlcipher3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80184     if( aNew==0 ) return;
80185     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80186   }else{
80187     aNew = sqlcipher3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80188     if( aNew==0 ) return;
80189   }
80190   db->aDb = aNew;
80191   aNew = &db->aDb[db->nDb];
80192   memset(aNew, 0, sizeof(*aNew));
80193
80194   /* Open the database file. If the btree is successfully opened, use
80195   ** it to obtain the database schema. At this point the schema may
80196   ** or may not be initialised.
80197   */
80198   flags = db->openFlags;
80199   rc = sqlcipher3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80200   if( rc!=SQLCIPHER_OK ){
80201     if( rc==SQLCIPHER_NOMEM ) db->mallocFailed = 1;
80202     sqlcipher3_result_error(context, zErr, -1);
80203     sqlcipher3_free(zErr);
80204     return;
80205   }
80206   assert( pVfs );
80207   flags |= SQLCIPHER_OPEN_MAIN_DB;
80208   rc = sqlcipher3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80209   sqlcipher3_free( zPath );
80210   db->nDb++;
80211   if( rc==SQLCIPHER_CONSTRAINT ){
80212     rc = SQLCIPHER_ERROR;
80213     zErrDyn = sqlcipher3MPrintf(db, "database is already attached");
80214   }else if( rc==SQLCIPHER_OK ){
80215     Pager *pPager;
80216     aNew->pSchema = sqlcipher3SchemaGet(db, aNew->pBt);
80217     if( !aNew->pSchema ){
80218       rc = SQLCIPHER_NOMEM;
80219     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80220       zErrDyn = sqlcipher3MPrintf(db, 
80221         "attached databases must use the same text encoding as main database");
80222       rc = SQLCIPHER_ERROR;
80223     }
80224     pPager = sqlcipher3BtreePager(aNew->pBt);
80225     sqlcipher3PagerLockingMode(pPager, db->dfltLockMode);
80226     sqlcipher3BtreeSecureDelete(aNew->pBt,
80227                              sqlcipher3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80228   }
80229   aNew->safety_level = 3;
80230   aNew->zName = sqlcipher3DbStrDup(db, zName);
80231   if( rc==SQLCIPHER_OK && aNew->zName==0 ){
80232     rc = SQLCIPHER_NOMEM;
80233   }
80234
80235
80236 #ifdef SQLCIPHER_HAS_CODEC
80237   if( rc==SQLCIPHER_OK ){
80238     extern int sqlcipher3CodecAttach(sqlcipher3*, int, const void*, int);
80239     extern void sqlcipher3CodecGetKey(sqlcipher3*, int, void**, int*);
80240     int nKey = 0;
80241     char *zKey = NULL;
80242     int t = sqlcipher3_value_type(argv[2]);
80243     switch( t ){
80244       case SQLCIPHER_INTEGER:
80245       case SQLCIPHER_FLOAT:
80246         zErrDyn = sqlcipher3DbStrDup(db, "Invalid key value");
80247         rc = SQLCIPHER_ERROR;
80248         break;
80249         
80250       case SQLCIPHER_TEXT:
80251       case SQLCIPHER_BLOB:
80252         nKey = sqlcipher3_value_bytes(argv[2]);
80253         zKey = (char *)sqlcipher3_value_blob(argv[2]);
80254         rc = sqlcipher3CodecAttach(db, db->nDb-1, zKey, nKey);
80255         break;
80256
80257       case SQLCIPHER_NULL:
80258         /* No key specified.  Use the key from the main database */
80259         sqlcipher3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80260         if( nKey>0 || sqlcipher3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80261           rc = sqlcipher3CodecAttach(db, db->nDb-1, zKey, nKey);
80262         }
80263         break;
80264     }
80265   }
80266 #endif
80267
80268   /* If the file was opened successfully, read the schema for the new database.
80269   ** If this fails, or if opening the file failed, then close the file and 
80270   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80271   ** we found it.
80272   */
80273   if( rc==SQLCIPHER_OK ){
80274     sqlcipher3BtreeEnterAll(db);
80275     rc = sqlcipher3Init(db, &zErrDyn);
80276     sqlcipher3BtreeLeaveAll(db);
80277   }
80278   if( rc ){
80279     int iDb = db->nDb - 1;
80280     assert( iDb>=2 );
80281     if( db->aDb[iDb].pBt ){
80282       sqlcipher3BtreeClose(db->aDb[iDb].pBt);
80283       db->aDb[iDb].pBt = 0;
80284       db->aDb[iDb].pSchema = 0;
80285     }
80286     sqlcipher3ResetInternalSchema(db, -1);
80287     db->nDb = iDb;
80288     if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ){
80289       db->mallocFailed = 1;
80290       sqlcipher3DbFree(db, zErrDyn);
80291       zErrDyn = sqlcipher3MPrintf(db, "out of memory");
80292     }else if( zErrDyn==0 ){
80293       zErrDyn = sqlcipher3MPrintf(db, "unable to open database: %s", zFile);
80294     }
80295     goto attach_error;
80296   }
80297   
80298   return;
80299
80300 attach_error:
80301   /* Return an error if we get here */
80302   if( zErrDyn ){
80303     sqlcipher3_result_error(context, zErrDyn, -1);
80304     sqlcipher3DbFree(db, zErrDyn);
80305   }
80306   if( rc ) sqlcipher3_result_error_code(context, rc);
80307 }
80308
80309 /*
80310 ** An SQL user-function registered to do the work of an DETACH statement. The
80311 ** three arguments to the function come directly from a detach statement:
80312 **
80313 **     DETACH DATABASE x
80314 **
80315 **     SELECT sqlcipher_detach(x)
80316 */
80317 static void detachFunc(
80318   sqlcipher3_context *context,
80319   int NotUsed,
80320   sqlcipher3_value **argv
80321 ){
80322   const char *zName = (const char *)sqlcipher3_value_text(argv[0]);
80323   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
80324   int i;
80325   Db *pDb = 0;
80326   char zErr[128];
80327
80328   UNUSED_PARAMETER(NotUsed);
80329
80330   if( zName==0 ) zName = "";
80331   for(i=0; i<db->nDb; i++){
80332     pDb = &db->aDb[i];
80333     if( pDb->pBt==0 ) continue;
80334     if( sqlcipher3StrICmp(pDb->zName, zName)==0 ) break;
80335   }
80336
80337   if( i>=db->nDb ){
80338     sqlcipher3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80339     goto detach_error;
80340   }
80341   if( i<2 ){
80342     sqlcipher3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80343     goto detach_error;
80344   }
80345   if( !db->autoCommit ){
80346     sqlcipher3_snprintf(sizeof(zErr), zErr,
80347                      "cannot DETACH database within transaction");
80348     goto detach_error;
80349   }
80350   if( sqlcipher3BtreeIsInReadTrans(pDb->pBt) || sqlcipher3BtreeIsInBackup(pDb->pBt) ){
80351     sqlcipher3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80352     goto detach_error;
80353   }
80354
80355   sqlcipher3BtreeClose(pDb->pBt);
80356   pDb->pBt = 0;
80357   pDb->pSchema = 0;
80358   sqlcipher3ResetInternalSchema(db, -1);
80359   return;
80360
80361 detach_error:
80362   sqlcipher3_result_error(context, zErr, -1);
80363 }
80364
80365 /*
80366 ** This procedure generates VDBE code for a single invocation of either the
80367 ** sqlcipher_detach() or sqlcipher_attach() SQL user functions.
80368 */
80369 static void codeAttach(
80370   Parse *pParse,       /* The parser context */
80371   int type,            /* Either SQLCIPHER_ATTACH or SQLCIPHER_DETACH */
80372   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80373   Expr *pAuthArg,      /* Expression to pass to authorization callback */
80374   Expr *pFilename,     /* Name of database file */
80375   Expr *pDbname,       /* Name of the database to use internally */
80376   Expr *pKey           /* Database key for encryption extension */
80377 ){
80378   int rc;
80379   NameContext sName;
80380   Vdbe *v;
80381   sqlcipher3* db = pParse->db;
80382   int regArgs;
80383
80384   memset(&sName, 0, sizeof(NameContext));
80385   sName.pParse = pParse;
80386
80387   if( 
80388       SQLCIPHER_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80389       SQLCIPHER_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80390       SQLCIPHER_OK!=(rc = resolveAttachExpr(&sName, pKey))
80391   ){
80392     pParse->nErr++;
80393     goto attach_end;
80394   }
80395
80396 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
80397   if( pAuthArg ){
80398     char *zAuthArg;
80399     if( pAuthArg->op==TK_STRING ){
80400       zAuthArg = pAuthArg->u.zToken;
80401     }else{
80402       zAuthArg = 0;
80403     }
80404     rc = sqlcipher3AuthCheck(pParse, type, zAuthArg, 0, 0);
80405     if(rc!=SQLCIPHER_OK ){
80406       goto attach_end;
80407     }
80408   }
80409 #endif /* SQLCIPHER_OMIT_AUTHORIZATION */
80410
80411
80412   v = sqlcipher3GetVdbe(pParse);
80413   regArgs = sqlcipher3GetTempRange(pParse, 4);
80414   sqlcipher3ExprCode(pParse, pFilename, regArgs);
80415   sqlcipher3ExprCode(pParse, pDbname, regArgs+1);
80416   sqlcipher3ExprCode(pParse, pKey, regArgs+2);
80417
80418   assert( v || db->mallocFailed );
80419   if( v ){
80420     sqlcipher3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80421     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80422     sqlcipher3VdbeChangeP5(v, (u8)(pFunc->nArg));
80423     sqlcipher3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80424
80425     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80426     ** statement only). For DETACH, set it to false (expire all existing
80427     ** statements).
80428     */
80429     sqlcipher3VdbeAddOp1(v, OP_Expire, (type==SQLCIPHER_ATTACH));
80430   }
80431   
80432 attach_end:
80433   sqlcipher3ExprDelete(db, pFilename);
80434   sqlcipher3ExprDelete(db, pDbname);
80435   sqlcipher3ExprDelete(db, pKey);
80436 }
80437
80438 /*
80439 ** Called by the parser to compile a DETACH statement.
80440 **
80441 **     DETACH pDbname
80442 */
80443 SQLCIPHER_PRIVATE void sqlcipher3Detach(Parse *pParse, Expr *pDbname){
80444   static const FuncDef detach_func = {
80445     1,                /* nArg */
80446     SQLCIPHER_UTF8,      /* iPrefEnc */
80447     0,                /* flags */
80448     0,                /* pUserData */
80449     0,                /* pNext */
80450     detachFunc,       /* xFunc */
80451     0,                /* xStep */
80452     0,                /* xFinalize */
80453     "sqlcipher_detach",  /* zName */
80454     0,                /* pHash */
80455     0                 /* pDestructor */
80456   };
80457   codeAttach(pParse, SQLCIPHER_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80458 }
80459
80460 /*
80461 ** Called by the parser to compile an ATTACH statement.
80462 **
80463 **     ATTACH p AS pDbname KEY pKey
80464 */
80465 SQLCIPHER_PRIVATE void sqlcipher3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80466   static const FuncDef attach_func = {
80467     3,                /* nArg */
80468     SQLCIPHER_UTF8,      /* iPrefEnc */
80469     0,                /* flags */
80470     0,                /* pUserData */
80471     0,                /* pNext */
80472     attachFunc,       /* xFunc */
80473     0,                /* xStep */
80474     0,                /* xFinalize */
80475     "sqlcipher_attach",  /* zName */
80476     0,                /* pHash */
80477     0                 /* pDestructor */
80478   };
80479   codeAttach(pParse, SQLCIPHER_ATTACH, &attach_func, p, p, pDbname, pKey);
80480 }
80481 #endif /* SQLCIPHER_OMIT_ATTACH */
80482
80483 /*
80484 ** Initialize a DbFixer structure.  This routine must be called prior
80485 ** to passing the structure to one of the sqlcipherFixAAAA() routines below.
80486 **
80487 ** The return value indicates whether or not fixation is required.  TRUE
80488 ** means we do need to fix the database references, FALSE means we do not.
80489 */
80490 SQLCIPHER_PRIVATE int sqlcipher3FixInit(
80491   DbFixer *pFix,      /* The fixer to be initialized */
80492   Parse *pParse,      /* Error messages will be written here */
80493   int iDb,            /* This is the database that must be used */
80494   const char *zType,  /* "view", "trigger", or "index" */
80495   const Token *pName  /* Name of the view, trigger, or index */
80496 ){
80497   sqlcipher3 *db;
80498
80499   if( NEVER(iDb<0) || iDb==1 ) return 0;
80500   db = pParse->db;
80501   assert( db->nDb>iDb );
80502   pFix->pParse = pParse;
80503   pFix->zDb = db->aDb[iDb].zName;
80504   pFix->zType = zType;
80505   pFix->pName = pName;
80506   return 1;
80507 }
80508
80509 /*
80510 ** The following set of routines walk through the parse tree and assign
80511 ** a specific database to all table references where the database name
80512 ** was left unspecified in the original SQL statement.  The pFix structure
80513 ** must have been initialized by a prior call to sqlcipher3FixInit().
80514 **
80515 ** These routines are used to make sure that an index, trigger, or
80516 ** view in one database does not refer to objects in a different database.
80517 ** (Exception: indices, triggers, and views in the TEMP database are
80518 ** allowed to refer to anything.)  If a reference is explicitly made
80519 ** to an object in a different database, an error message is added to
80520 ** pParse->zErrMsg and these routines return non-zero.  If everything
80521 ** checks out, these routines return 0.
80522 */
80523 SQLCIPHER_PRIVATE int sqlcipher3FixSrcList(
80524   DbFixer *pFix,       /* Context of the fixation */
80525   SrcList *pList       /* The Source list to check and modify */
80526 ){
80527   int i;
80528   const char *zDb;
80529   struct SrcList_item *pItem;
80530
80531   if( NEVER(pList==0) ) return 0;
80532   zDb = pFix->zDb;
80533   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80534     if( pItem->zDatabase==0 ){
80535       pItem->zDatabase = sqlcipher3DbStrDup(pFix->pParse->db, zDb);
80536     }else if( sqlcipher3StrICmp(pItem->zDatabase,zDb)!=0 ){
80537       sqlcipher3ErrorMsg(pFix->pParse,
80538          "%s %T cannot reference objects in database %s",
80539          pFix->zType, pFix->pName, pItem->zDatabase);
80540       return 1;
80541     }
80542 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_TRIGGER)
80543     if( sqlcipher3FixSelect(pFix, pItem->pSelect) ) return 1;
80544     if( sqlcipher3FixExpr(pFix, pItem->pOn) ) return 1;
80545 #endif
80546   }
80547   return 0;
80548 }
80549 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_TRIGGER)
80550 SQLCIPHER_PRIVATE int sqlcipher3FixSelect(
80551   DbFixer *pFix,       /* Context of the fixation */
80552   Select *pSelect      /* The SELECT statement to be fixed to one database */
80553 ){
80554   while( pSelect ){
80555     if( sqlcipher3FixExprList(pFix, pSelect->pEList) ){
80556       return 1;
80557     }
80558     if( sqlcipher3FixSrcList(pFix, pSelect->pSrc) ){
80559       return 1;
80560     }
80561     if( sqlcipher3FixExpr(pFix, pSelect->pWhere) ){
80562       return 1;
80563     }
80564     if( sqlcipher3FixExpr(pFix, pSelect->pHaving) ){
80565       return 1;
80566     }
80567     pSelect = pSelect->pPrior;
80568   }
80569   return 0;
80570 }
80571 SQLCIPHER_PRIVATE int sqlcipher3FixExpr(
80572   DbFixer *pFix,     /* Context of the fixation */
80573   Expr *pExpr        /* The expression to be fixed to one database */
80574 ){
80575   while( pExpr ){
80576     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80577     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80578       if( sqlcipher3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80579     }else{
80580       if( sqlcipher3FixExprList(pFix, pExpr->x.pList) ) return 1;
80581     }
80582     if( sqlcipher3FixExpr(pFix, pExpr->pRight) ){
80583       return 1;
80584     }
80585     pExpr = pExpr->pLeft;
80586   }
80587   return 0;
80588 }
80589 SQLCIPHER_PRIVATE int sqlcipher3FixExprList(
80590   DbFixer *pFix,     /* Context of the fixation */
80591   ExprList *pList    /* The expression to be fixed to one database */
80592 ){
80593   int i;
80594   struct ExprList_item *pItem;
80595   if( pList==0 ) return 0;
80596   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80597     if( sqlcipher3FixExpr(pFix, pItem->pExpr) ){
80598       return 1;
80599     }
80600   }
80601   return 0;
80602 }
80603 #endif
80604
80605 #ifndef SQLCIPHER_OMIT_TRIGGER
80606 SQLCIPHER_PRIVATE int sqlcipher3FixTriggerStep(
80607   DbFixer *pFix,     /* Context of the fixation */
80608   TriggerStep *pStep /* The trigger step be fixed to one database */
80609 ){
80610   while( pStep ){
80611     if( sqlcipher3FixSelect(pFix, pStep->pSelect) ){
80612       return 1;
80613     }
80614     if( sqlcipher3FixExpr(pFix, pStep->pWhere) ){
80615       return 1;
80616     }
80617     if( sqlcipher3FixExprList(pFix, pStep->pExprList) ){
80618       return 1;
80619     }
80620     pStep = pStep->pNext;
80621   }
80622   return 0;
80623 }
80624 #endif
80625
80626 /************** End of attach.c **********************************************/
80627 /************** Begin file auth.c ********************************************/
80628 /*
80629 ** 2003 January 11
80630 **
80631 ** The author disclaims copyright to this source code.  In place of
80632 ** a legal notice, here is a blessing:
80633 **
80634 **    May you do good and not evil.
80635 **    May you find forgiveness for yourself and forgive others.
80636 **    May you share freely, never taking more than you give.
80637 **
80638 *************************************************************************
80639 ** This file contains code used to implement the sqlcipher3_set_authorizer()
80640 ** API.  This facility is an optional feature of the library.  Embedded
80641 ** systems that do not need this facility may omit it by recompiling
80642 ** the library with -DSQLCIPHER_OMIT_AUTHORIZATION=1
80643 */
80644
80645 /*
80646 ** All of the code in this file may be omitted by defining a single
80647 ** macro.
80648 */
80649 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
80650
80651 /*
80652 ** Set or clear the access authorization function.
80653 **
80654 ** The access authorization function is be called during the compilation
80655 ** phase to verify that the user has read and/or write access permission on
80656 ** various fields of the database.  The first argument to the auth function
80657 ** is a copy of the 3rd argument to this routine.  The second argument
80658 ** to the auth function is one of these constants:
80659 **
80660 **       SQLCIPHER_CREATE_INDEX
80661 **       SQLCIPHER_CREATE_TABLE
80662 **       SQLCIPHER_CREATE_TEMP_INDEX
80663 **       SQLCIPHER_CREATE_TEMP_TABLE
80664 **       SQLCIPHER_CREATE_TEMP_TRIGGER
80665 **       SQLCIPHER_CREATE_TEMP_VIEW
80666 **       SQLCIPHER_CREATE_TRIGGER
80667 **       SQLCIPHER_CREATE_VIEW
80668 **       SQLCIPHER_DELETE
80669 **       SQLCIPHER_DROP_INDEX
80670 **       SQLCIPHER_DROP_TABLE
80671 **       SQLCIPHER_DROP_TEMP_INDEX
80672 **       SQLCIPHER_DROP_TEMP_TABLE
80673 **       SQLCIPHER_DROP_TEMP_TRIGGER
80674 **       SQLCIPHER_DROP_TEMP_VIEW
80675 **       SQLCIPHER_DROP_TRIGGER
80676 **       SQLCIPHER_DROP_VIEW
80677 **       SQLCIPHER_INSERT
80678 **       SQLCIPHER_PRAGMA
80679 **       SQLCIPHER_READ
80680 **       SQLCIPHER_SELECT
80681 **       SQLCIPHER_TRANSACTION
80682 **       SQLCIPHER_UPDATE
80683 **
80684 ** The third and fourth arguments to the auth function are the name of
80685 ** the table and the column that are being accessed.  The auth function
80686 ** should return either SQLCIPHER_OK, SQLCIPHER_DENY, or SQLCIPHER_IGNORE.  If
80687 ** SQLCIPHER_OK is returned, it means that access is allowed.  SQLCIPHER_DENY
80688 ** means that the SQL statement will never-run - the sqlcipher3_exec() call
80689 ** will return with an error.  SQLCIPHER_IGNORE means that the SQL statement
80690 ** should run but attempts to read the specified column will return NULL
80691 ** and attempts to write the column will be ignored.
80692 **
80693 ** Setting the auth function to NULL disables this hook.  The default
80694 ** setting of the auth function is NULL.
80695 */
80696 SQLCIPHER_API int sqlcipher3_set_authorizer(
80697   sqlcipher3 *db,
80698   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
80699   void *pArg
80700 ){
80701   sqlcipher3_mutex_enter(db->mutex);
80702   db->xAuth = xAuth;
80703   db->pAuthArg = pArg;
80704   sqlcipher3ExpirePreparedStatements(db);
80705   sqlcipher3_mutex_leave(db->mutex);
80706   return SQLCIPHER_OK;
80707 }
80708
80709 /*
80710 ** Write an error message into pParse->zErrMsg that explains that the
80711 ** user-supplied authorization function returned an illegal value.
80712 */
80713 static void sqlcipherAuthBadReturnCode(Parse *pParse){
80714   sqlcipher3ErrorMsg(pParse, "authorizer malfunction");
80715   pParse->rc = SQLCIPHER_ERROR;
80716 }
80717
80718 /*
80719 ** Invoke the authorization callback for permission to read column zCol from
80720 ** table zTab in database zDb. This function assumes that an authorization
80721 ** callback has been registered (i.e. that sqlcipher3.xAuth is not NULL).
80722 **
80723 ** If SQLCIPHER_IGNORE is returned and pExpr is not NULL, then pExpr is changed
80724 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLCIPHER_IGNORE
80725 ** is treated as SQLCIPHER_DENY. In this case an error is left in pParse.
80726 */
80727 SQLCIPHER_PRIVATE int sqlcipher3AuthReadCol(
80728   Parse *pParse,                  /* The parser context */
80729   const char *zTab,               /* Table name */
80730   const char *zCol,               /* Column name */
80731   int iDb                         /* Index of containing database. */
80732 ){
80733   sqlcipher3 *db = pParse->db;       /* Database handle */
80734   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
80735   int rc;                         /* Auth callback return code */
80736
80737   rc = db->xAuth(db->pAuthArg, SQLCIPHER_READ, zTab,zCol,zDb,pParse->zAuthContext);
80738   if( rc==SQLCIPHER_DENY ){
80739     if( db->nDb>2 || iDb!=0 ){
80740       sqlcipher3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
80741     }else{
80742       sqlcipher3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
80743     }
80744     pParse->rc = SQLCIPHER_AUTH;
80745   }else if( rc!=SQLCIPHER_IGNORE && rc!=SQLCIPHER_OK ){
80746     sqlcipherAuthBadReturnCode(pParse);
80747   }
80748   return rc;
80749 }
80750
80751 /*
80752 ** The pExpr should be a TK_COLUMN expression.  The table referred to
80753 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
80754 ** Check to see if it is OK to read this particular column.
80755 **
80756 ** If the auth function returns SQLCIPHER_IGNORE, change the TK_COLUMN 
80757 ** instruction into a TK_NULL.  If the auth function returns SQLCIPHER_DENY,
80758 ** then generate an error.
80759 */
80760 SQLCIPHER_PRIVATE void sqlcipher3AuthRead(
80761   Parse *pParse,        /* The parser context */
80762   Expr *pExpr,          /* The expression to check authorization on */
80763   Schema *pSchema,      /* The schema of the expression */
80764   SrcList *pTabList     /* All table that pExpr might refer to */
80765 ){
80766   sqlcipher3 *db = pParse->db;
80767   Table *pTab = 0;      /* The table being read */
80768   const char *zCol;     /* Name of the column of the table */
80769   int iSrc;             /* Index in pTabList->a[] of table being read */
80770   int iDb;              /* The index of the database the expression refers to */
80771   int iCol;             /* Index of column in table */
80772
80773   if( db->xAuth==0 ) return;
80774   iDb = sqlcipher3SchemaToIndex(pParse->db, pSchema);
80775   if( iDb<0 ){
80776     /* An attempt to read a column out of a subquery or other
80777     ** temporary table. */
80778     return;
80779   }
80780
80781   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
80782   if( pExpr->op==TK_TRIGGER ){
80783     pTab = pParse->pTriggerTab;
80784   }else{
80785     assert( pTabList );
80786     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
80787       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
80788         pTab = pTabList->a[iSrc].pTab;
80789         break;
80790       }
80791     }
80792   }
80793   iCol = pExpr->iColumn;
80794   if( NEVER(pTab==0) ) return;
80795
80796   if( iCol>=0 ){
80797     assert( iCol<pTab->nCol );
80798     zCol = pTab->aCol[iCol].zName;
80799   }else if( pTab->iPKey>=0 ){
80800     assert( pTab->iPKey<pTab->nCol );
80801     zCol = pTab->aCol[pTab->iPKey].zName;
80802   }else{
80803     zCol = "ROWID";
80804   }
80805   assert( iDb>=0 && iDb<db->nDb );
80806   if( SQLCIPHER_IGNORE==sqlcipher3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
80807     pExpr->op = TK_NULL;
80808   }
80809 }
80810
80811 /*
80812 ** Do an authorization check using the code and arguments given.  Return
80813 ** either SQLCIPHER_OK (zero) or SQLCIPHER_IGNORE or SQLCIPHER_DENY.  If SQLCIPHER_DENY
80814 ** is returned, then the error count and error message in pParse are
80815 ** modified appropriately.
80816 */
80817 SQLCIPHER_PRIVATE int sqlcipher3AuthCheck(
80818   Parse *pParse,
80819   int code,
80820   const char *zArg1,
80821   const char *zArg2,
80822   const char *zArg3
80823 ){
80824   sqlcipher3 *db = pParse->db;
80825   int rc;
80826
80827   /* Don't do any authorization checks if the database is initialising
80828   ** or if the parser is being invoked from within sqlcipher3_declare_vtab.
80829   */
80830   if( db->init.busy || IN_DECLARE_VTAB ){
80831     return SQLCIPHER_OK;
80832   }
80833
80834   if( db->xAuth==0 ){
80835     return SQLCIPHER_OK;
80836   }
80837   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
80838   if( rc==SQLCIPHER_DENY ){
80839     sqlcipher3ErrorMsg(pParse, "not authorized");
80840     pParse->rc = SQLCIPHER_AUTH;
80841   }else if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_IGNORE ){
80842     rc = SQLCIPHER_DENY;
80843     sqlcipherAuthBadReturnCode(pParse);
80844   }
80845   return rc;
80846 }
80847
80848 /*
80849 ** Push an authorization context.  After this routine is called, the
80850 ** zArg3 argument to authorization callbacks will be zContext until
80851 ** popped.  Or if pParse==0, this routine is a no-op.
80852 */
80853 SQLCIPHER_PRIVATE void sqlcipher3AuthContextPush(
80854   Parse *pParse,
80855   AuthContext *pContext, 
80856   const char *zContext
80857 ){
80858   assert( pParse );
80859   pContext->pParse = pParse;
80860   pContext->zAuthContext = pParse->zAuthContext;
80861   pParse->zAuthContext = zContext;
80862 }
80863
80864 /*
80865 ** Pop an authorization context that was previously pushed
80866 ** by sqlcipher3AuthContextPush
80867 */
80868 SQLCIPHER_PRIVATE void sqlcipher3AuthContextPop(AuthContext *pContext){
80869   if( pContext->pParse ){
80870     pContext->pParse->zAuthContext = pContext->zAuthContext;
80871     pContext->pParse = 0;
80872   }
80873 }
80874
80875 #endif /* SQLCIPHER_OMIT_AUTHORIZATION */
80876
80877 /************** End of auth.c ************************************************/
80878 /************** Begin file build.c *******************************************/
80879 /*
80880 ** 2001 September 15
80881 **
80882 ** The author disclaims copyright to this source code.  In place of
80883 ** a legal notice, here is a blessing:
80884 **
80885 **    May you do good and not evil.
80886 **    May you find forgiveness for yourself and forgive others.
80887 **    May you share freely, never taking more than you give.
80888 **
80889 *************************************************************************
80890 ** This file contains C code routines that are called by the SQLite parser
80891 ** when syntax rules are reduced.  The routines in this file handle the
80892 ** following kinds of SQL syntax:
80893 **
80894 **     CREATE TABLE
80895 **     DROP TABLE
80896 **     CREATE INDEX
80897 **     DROP INDEX
80898 **     creating ID lists
80899 **     BEGIN TRANSACTION
80900 **     COMMIT
80901 **     ROLLBACK
80902 */
80903
80904 /*
80905 ** This routine is called when a new SQL statement is beginning to
80906 ** be parsed.  Initialize the pParse structure as needed.
80907 */
80908 SQLCIPHER_PRIVATE void sqlcipher3BeginParse(Parse *pParse, int explainFlag){
80909   pParse->explain = (u8)explainFlag;
80910   pParse->nVar = 0;
80911 }
80912
80913 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
80914 /*
80915 ** The TableLock structure is only used by the sqlcipher3TableLock() and
80916 ** codeTableLocks() functions.
80917 */
80918 struct TableLock {
80919   int iDb;             /* The database containing the table to be locked */
80920   int iTab;            /* The root page of the table to be locked */
80921   u8 isWriteLock;      /* True for write lock.  False for a read lock */
80922   const char *zName;   /* Name of the table */
80923 };
80924
80925 /*
80926 ** Record the fact that we want to lock a table at run-time.  
80927 **
80928 ** The table to be locked has root page iTab and is found in database iDb.
80929 ** A read or a write lock can be taken depending on isWritelock.
80930 **
80931 ** This routine just records the fact that the lock is desired.  The
80932 ** code to make the lock occur is generated by a later call to
80933 ** codeTableLocks() which occurs during sqlcipher3FinishCoding().
80934 */
80935 SQLCIPHER_PRIVATE void sqlcipher3TableLock(
80936   Parse *pParse,     /* Parsing context */
80937   int iDb,           /* Index of the database containing the table to lock */
80938   int iTab,          /* Root page number of the table to be locked */
80939   u8 isWriteLock,    /* True for a write lock */
80940   const char *zName  /* Name of the table to be locked */
80941 ){
80942   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
80943   int i;
80944   int nBytes;
80945   TableLock *p;
80946   assert( iDb>=0 );
80947
80948   for(i=0; i<pToplevel->nTableLock; i++){
80949     p = &pToplevel->aTableLock[i];
80950     if( p->iDb==iDb && p->iTab==iTab ){
80951       p->isWriteLock = (p->isWriteLock || isWriteLock);
80952       return;
80953     }
80954   }
80955
80956   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80957   pToplevel->aTableLock =
80958       sqlcipher3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
80959   if( pToplevel->aTableLock ){
80960     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
80961     p->iDb = iDb;
80962     p->iTab = iTab;
80963     p->isWriteLock = isWriteLock;
80964     p->zName = zName;
80965   }else{
80966     pToplevel->nTableLock = 0;
80967     pToplevel->db->mallocFailed = 1;
80968   }
80969 }
80970
80971 /*
80972 ** Code an OP_TableLock instruction for each table locked by the
80973 ** statement (configured by calls to sqlcipher3TableLock()).
80974 */
80975 static void codeTableLocks(Parse *pParse){
80976   int i;
80977   Vdbe *pVdbe; 
80978
80979   pVdbe = sqlcipher3GetVdbe(pParse);
80980   assert( pVdbe!=0 ); /* sqlcipher3GetVdbe cannot fail: VDBE already allocated */
80981
80982   for(i=0; i<pParse->nTableLock; i++){
80983     TableLock *p = &pParse->aTableLock[i];
80984     int p1 = p->iDb;
80985     sqlcipher3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
80986                       p->zName, P4_STATIC);
80987   }
80988 }
80989 #else
80990   #define codeTableLocks(x)
80991 #endif
80992
80993 /*
80994 ** This routine is called after a single SQL statement has been
80995 ** parsed and a VDBE program to execute that statement has been
80996 ** prepared.  This routine puts the finishing touches on the
80997 ** VDBE program and resets the pParse structure for the next
80998 ** parse.
80999 **
81000 ** Note that if an error occurred, it might be the case that
81001 ** no VDBE code was generated.
81002 */
81003 SQLCIPHER_PRIVATE void sqlcipher3FinishCoding(Parse *pParse){
81004   sqlcipher3 *db;
81005   Vdbe *v;
81006
81007   db = pParse->db;
81008   if( db->mallocFailed ) return;
81009   if( pParse->nested ) return;
81010   if( pParse->nErr ) return;
81011
81012   /* Begin by generating some termination code at the end of the
81013   ** vdbe program
81014   */
81015   v = sqlcipher3GetVdbe(pParse);
81016   assert( !pParse->isMultiWrite 
81017        || sqlcipher3VdbeAssertMayAbort(v, pParse->mayAbort));
81018   if( v ){
81019     sqlcipher3VdbeAddOp0(v, OP_Halt);
81020
81021     /* The cookie mask contains one bit for each database file open.
81022     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
81023     ** set for each database that is used.  Generate code to start a
81024     ** transaction on each used database and to verify the schema cookie
81025     ** on each used database.
81026     */
81027     if( pParse->cookieGoto>0 ){
81028       yDbMask mask;
81029       int iDb;
81030       sqlcipher3VdbeJumpHere(v, pParse->cookieGoto-1);
81031       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81032         if( (mask & pParse->cookieMask)==0 ) continue;
81033         sqlcipher3VdbeUsesBtree(v, iDb);
81034         sqlcipher3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
81035         if( db->init.busy==0 ){
81036           assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81037           sqlcipher3VdbeAddOp3(v, OP_VerifyCookie,
81038                             iDb, pParse->cookieValue[iDb],
81039                             db->aDb[iDb].pSchema->iGeneration);
81040         }
81041       }
81042 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
81043       {
81044         int i;
81045         for(i=0; i<pParse->nVtabLock; i++){
81046           char *vtab = (char *)sqlcipher3GetVTable(db, pParse->apVtabLock[i]);
81047           sqlcipher3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
81048         }
81049         pParse->nVtabLock = 0;
81050       }
81051 #endif
81052
81053       /* Once all the cookies have been verified and transactions opened, 
81054       ** obtain the required table-locks. This is a no-op unless the 
81055       ** shared-cache feature is enabled.
81056       */
81057       codeTableLocks(pParse);
81058
81059       /* Initialize any AUTOINCREMENT data structures required.
81060       */
81061       sqlcipher3AutoincrementBegin(pParse);
81062
81063       /* Finally, jump back to the beginning of the executable code. */
81064       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
81065     }
81066   }
81067
81068
81069   /* Get the VDBE program ready for execution
81070   */
81071   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
81072 #ifdef SQLCIPHER_DEBUG
81073     FILE *trace = (db->flags & SQLCIPHER_VdbeTrace)!=0 ? stdout : 0;
81074     sqlcipher3VdbeTrace(v, trace);
81075 #endif
81076     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
81077     /* A minimum of one cursor is required if autoincrement is used
81078     *  See ticket [a696379c1f08866] */
81079     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
81080     sqlcipher3VdbeMakeReady(v, pParse);
81081     pParse->rc = SQLCIPHER_DONE;
81082     pParse->colNamesSet = 0;
81083   }else{
81084     pParse->rc = SQLCIPHER_ERROR;
81085   }
81086   pParse->nTab = 0;
81087   pParse->nMem = 0;
81088   pParse->nSet = 0;
81089   pParse->nVar = 0;
81090   pParse->cookieMask = 0;
81091   pParse->cookieGoto = 0;
81092 }
81093
81094 /*
81095 ** Run the parser and code generator recursively in order to generate
81096 ** code for the SQL statement given onto the end of the pParse context
81097 ** currently under construction.  When the parser is run recursively
81098 ** this way, the final OP_Halt is not appended and other initialization
81099 ** and finalization steps are omitted because those are handling by the
81100 ** outermost parser.
81101 **
81102 ** Not everything is nestable.  This facility is designed to permit
81103 ** INSERT, UPDATE, and DELETE operations against SQLCIPHER_MASTER.  Use
81104 ** care if you decide to try to use this routine for some other purposes.
81105 */
81106 SQLCIPHER_PRIVATE void sqlcipher3NestedParse(Parse *pParse, const char *zFormat, ...){
81107   va_list ap;
81108   char *zSql;
81109   char *zErrMsg = 0;
81110   sqlcipher3 *db = pParse->db;
81111 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
81112   char saveBuf[SAVE_SZ];
81113
81114   if( pParse->nErr ) return;
81115   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
81116   va_start(ap, zFormat);
81117   zSql = sqlcipher3VMPrintf(db, zFormat, ap);
81118   va_end(ap);
81119   if( zSql==0 ){
81120     return;   /* A malloc must have failed */
81121   }
81122   pParse->nested++;
81123   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
81124   memset(&pParse->nVar, 0, SAVE_SZ);
81125   sqlcipher3RunParser(pParse, zSql, &zErrMsg);
81126   sqlcipher3DbFree(db, zErrMsg);
81127   sqlcipher3DbFree(db, zSql);
81128   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
81129   pParse->nested--;
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.
81136 **
81137 ** If zDatabase is 0, all databases are searched for the table and the
81138 ** first matching table is returned.  (No checking for duplicate table
81139 ** names is done.)  The search order is TEMP first, then MAIN, then any
81140 ** auxiliary databases added using the ATTACH command.
81141 **
81142 ** See also sqlcipher3LocateTable().
81143 */
81144 SQLCIPHER_PRIVATE Table *sqlcipher3FindTable(sqlcipher3 *db, const char *zName, const char *zDatabase){
81145   Table *p = 0;
81146   int i;
81147   int nName;
81148   assert( zName!=0 );
81149   nName = sqlcipher3Strlen30(zName);
81150   /* All mutexes are required for schema access.  Make sure we hold them. */
81151   assert( zDatabase!=0 || sqlcipher3BtreeHoldsAllMutexes(db) );
81152   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81153     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81154     if( zDatabase!=0 && sqlcipher3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81155     assert( sqlcipher3SchemaMutexHeld(db, j, 0) );
81156     p = sqlcipher3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81157     if( p ) break;
81158   }
81159   return p;
81160 }
81161
81162 /*
81163 ** Locate the in-memory structure that describes a particular database
81164 ** table given the name of that table and (optionally) the name of the
81165 ** database containing the table.  Return NULL if not found.  Also leave an
81166 ** error message in pParse->zErrMsg.
81167 **
81168 ** The difference between this routine and sqlcipher3FindTable() is that this
81169 ** routine leaves an error message in pParse->zErrMsg where
81170 ** sqlcipher3FindTable() does not.
81171 */
81172 SQLCIPHER_PRIVATE Table *sqlcipher3LocateTable(
81173   Parse *pParse,         /* context in which to report errors */
81174   int isView,            /* True if looking for a VIEW rather than a TABLE */
81175   const char *zName,     /* Name of the table we are looking for */
81176   const char *zDbase     /* Name of the database.  Might be NULL */
81177 ){
81178   Table *p;
81179
81180   /* Read the database schema. If an error occurs, leave an error message
81181   ** and code in pParse and return NULL. */
81182   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
81183     return 0;
81184   }
81185
81186   p = sqlcipher3FindTable(pParse->db, zName, zDbase);
81187   if( p==0 ){
81188     const char *zMsg = isView ? "no such view" : "no such table";
81189     if( zDbase ){
81190       sqlcipher3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81191     }else{
81192       sqlcipher3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81193     }
81194     pParse->checkSchema = 1;
81195   }
81196   return p;
81197 }
81198
81199 /*
81200 ** Locate the in-memory structure that describes 
81201 ** a particular index given the name of that index
81202 ** and the name of the database that contains the index.
81203 ** Return NULL if not found.
81204 **
81205 ** If zDatabase is 0, all databases are searched for the
81206 ** table and the first matching index is returned.  (No checking
81207 ** for duplicate index names is done.)  The search order is
81208 ** TEMP first, then MAIN, then any auxiliary databases added
81209 ** using the ATTACH command.
81210 */
81211 SQLCIPHER_PRIVATE Index *sqlcipher3FindIndex(sqlcipher3 *db, const char *zName, const char *zDb){
81212   Index *p = 0;
81213   int i;
81214   int nName = sqlcipher3Strlen30(zName);
81215   /* All mutexes are required for schema access.  Make sure we hold them. */
81216   assert( zDb!=0 || sqlcipher3BtreeHoldsAllMutexes(db) );
81217   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81218     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81219     Schema *pSchema = db->aDb[j].pSchema;
81220     assert( pSchema );
81221     if( zDb && sqlcipher3StrICmp(zDb, db->aDb[j].zName) ) continue;
81222     assert( sqlcipher3SchemaMutexHeld(db, j, 0) );
81223     p = sqlcipher3HashFind(&pSchema->idxHash, zName, nName);
81224     if( p ) break;
81225   }
81226   return p;
81227 }
81228
81229 /*
81230 ** Reclaim the memory used by an index
81231 */
81232 static void freeIndex(sqlcipher3 *db, Index *p){
81233 #ifndef SQLCIPHER_OMIT_ANALYZE
81234   sqlcipher3DeleteIndexSamples(db, p);
81235 #endif
81236   sqlcipher3DbFree(db, p->zColAff);
81237   sqlcipher3DbFree(db, p);
81238 }
81239
81240 /*
81241 ** For the index called zIdxName which is found in the database iDb,
81242 ** unlike that index from its Table then remove the index from
81243 ** the index hash table and free all memory structures associated
81244 ** with the index.
81245 */
81246 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteIndex(sqlcipher3 *db, int iDb, const char *zIdxName){
81247   Index *pIndex;
81248   int len;
81249   Hash *pHash;
81250
81251   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81252   pHash = &db->aDb[iDb].pSchema->idxHash;
81253   len = sqlcipher3Strlen30(zIdxName);
81254   pIndex = sqlcipher3HashInsert(pHash, zIdxName, len, 0);
81255   if( ALWAYS(pIndex) ){
81256     if( pIndex->pTable->pIndex==pIndex ){
81257       pIndex->pTable->pIndex = pIndex->pNext;
81258     }else{
81259       Index *p;
81260       /* Justification of ALWAYS();  The index must be on the list of
81261       ** indices. */
81262       p = pIndex->pTable->pIndex;
81263       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81264       if( ALWAYS(p && p->pNext==pIndex) ){
81265         p->pNext = pIndex->pNext;
81266       }
81267     }
81268     freeIndex(db, pIndex);
81269   }
81270   db->flags |= SQLCIPHER_InternChanges;
81271 }
81272
81273 /*
81274 ** Erase all schema information from the in-memory hash tables of
81275 ** a single database.  This routine is called to reclaim memory
81276 ** before the database closes.  It is also called during a rollback
81277 ** if there were schema changes during the transaction or if a
81278 ** schema-cookie mismatch occurs.
81279 **
81280 ** If iDb<0 then reset the internal schema tables for all database
81281 ** files.  If iDb>=0 then reset the internal schema for only the
81282 ** single file indicated.
81283 */
81284 SQLCIPHER_PRIVATE void sqlcipher3ResetInternalSchema(sqlcipher3 *db, int iDb){
81285   int i, j;
81286   assert( iDb<db->nDb );
81287
81288   if( iDb>=0 ){
81289     /* Case 1:  Reset the single schema identified by iDb */
81290     Db *pDb = &db->aDb[iDb];
81291     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81292     assert( pDb->pSchema!=0 );
81293     sqlcipher3SchemaClear(pDb->pSchema);
81294
81295     /* If any database other than TEMP is reset, then also reset TEMP
81296     ** since TEMP might be holding triggers that reference tables in the
81297     ** other database.
81298     */
81299     if( iDb!=1 ){
81300       pDb = &db->aDb[1];
81301       assert( pDb->pSchema!=0 );
81302       sqlcipher3SchemaClear(pDb->pSchema);
81303     }
81304     return;
81305   }
81306   /* Case 2 (from here to the end): Reset all schemas for all attached
81307   ** databases. */
81308   assert( iDb<0 );
81309   sqlcipher3BtreeEnterAll(db);
81310   for(i=0; i<db->nDb; i++){
81311     Db *pDb = &db->aDb[i];
81312     if( pDb->pSchema ){
81313       sqlcipher3SchemaClear(pDb->pSchema);
81314     }
81315   }
81316   db->flags &= ~SQLCIPHER_InternChanges;
81317   sqlcipher3VtabUnlockList(db);
81318   sqlcipher3BtreeLeaveAll(db);
81319
81320   /* If one or more of the auxiliary database files has been closed,
81321   ** then remove them from the auxiliary database list.  We take the
81322   ** opportunity to do this here since we have just deleted all of the
81323   ** schema hash tables and therefore do not have to make any changes
81324   ** to any of those tables.
81325   */
81326   for(i=j=2; i<db->nDb; i++){
81327     struct Db *pDb = &db->aDb[i];
81328     if( pDb->pBt==0 ){
81329       sqlcipher3DbFree(db, pDb->zName);
81330       pDb->zName = 0;
81331       continue;
81332     }
81333     if( j<i ){
81334       db->aDb[j] = db->aDb[i];
81335     }
81336     j++;
81337   }
81338   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81339   db->nDb = j;
81340   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81341     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81342     sqlcipher3DbFree(db, db->aDb);
81343     db->aDb = db->aDbStatic;
81344   }
81345 }
81346
81347 /*
81348 ** This routine is called when a commit occurs.
81349 */
81350 SQLCIPHER_PRIVATE void sqlcipher3CommitInternalChanges(sqlcipher3 *db){
81351   db->flags &= ~SQLCIPHER_InternChanges;
81352 }
81353
81354 /*
81355 ** Delete memory allocated for the column names of a table or view (the
81356 ** Table.aCol[] array).
81357 */
81358 static void sqlcipherDeleteColumnNames(sqlcipher3 *db, Table *pTable){
81359   int i;
81360   Column *pCol;
81361   assert( pTable!=0 );
81362   if( (pCol = pTable->aCol)!=0 ){
81363     for(i=0; i<pTable->nCol; i++, pCol++){
81364       sqlcipher3DbFree(db, pCol->zName);
81365       sqlcipher3ExprDelete(db, pCol->pDflt);
81366       sqlcipher3DbFree(db, pCol->zDflt);
81367       sqlcipher3DbFree(db, pCol->zType);
81368       sqlcipher3DbFree(db, pCol->zColl);
81369     }
81370     sqlcipher3DbFree(db, pTable->aCol);
81371   }
81372 }
81373
81374 /*
81375 ** Remove the memory data structures associated with the given
81376 ** Table.  No changes are made to disk by this routine.
81377 **
81378 ** This routine just deletes the data structure.  It does not unlink
81379 ** the table data structure from the hash table.  But it does destroy
81380 ** memory structures of the indices and foreign keys associated with 
81381 ** the table.
81382 */
81383 SQLCIPHER_PRIVATE void sqlcipher3DeleteTable(sqlcipher3 *db, Table *pTable){
81384   Index *pIndex, *pNext;
81385
81386   assert( !pTable || pTable->nRef>0 );
81387
81388   /* Do not delete the table until the reference count reaches zero. */
81389   if( !pTable ) return;
81390   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81391
81392   /* Delete all indices associated with this table. */
81393   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81394     pNext = pIndex->pNext;
81395     assert( pIndex->pSchema==pTable->pSchema );
81396     if( !db || db->pnBytesFreed==0 ){
81397       char *zName = pIndex->zName; 
81398       TESTONLY ( Index *pOld = ) sqlcipher3HashInsert(
81399           &pIndex->pSchema->idxHash, zName, sqlcipher3Strlen30(zName), 0
81400       );
81401       assert( db==0 || sqlcipher3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81402       assert( pOld==pIndex || pOld==0 );
81403     }
81404     freeIndex(db, pIndex);
81405   }
81406
81407   /* Delete any foreign keys attached to this table. */
81408   sqlcipher3FkDelete(db, pTable);
81409
81410   /* Delete the Table structure itself.
81411   */
81412   sqlcipherDeleteColumnNames(db, pTable);
81413   sqlcipher3DbFree(db, pTable->zName);
81414   sqlcipher3DbFree(db, pTable->zColAff);
81415   sqlcipher3SelectDelete(db, pTable->pSelect);
81416 #ifndef SQLCIPHER_OMIT_CHECK
81417   sqlcipher3ExprDelete(db, pTable->pCheck);
81418 #endif
81419 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
81420   sqlcipher3VtabClear(db, pTable);
81421 #endif
81422   sqlcipher3DbFree(db, pTable);
81423 }
81424
81425 /*
81426 ** Unlink the given table from the hash tables and the delete the
81427 ** table structure with all its indices and foreign keys.
81428 */
81429 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteTable(sqlcipher3 *db, int iDb, const char *zTabName){
81430   Table *p;
81431   Db *pDb;
81432
81433   assert( db!=0 );
81434   assert( iDb>=0 && iDb<db->nDb );
81435   assert( zTabName );
81436   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81437   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81438   pDb = &db->aDb[iDb];
81439   p = sqlcipher3HashInsert(&pDb->pSchema->tblHash, zTabName,
81440                         sqlcipher3Strlen30(zTabName),0);
81441   sqlcipher3DeleteTable(db, p);
81442   db->flags |= SQLCIPHER_InternChanges;
81443 }
81444
81445 /*
81446 ** Given a token, return a string that consists of the text of that
81447 ** token.  Space to hold the returned string
81448 ** is obtained from sqlcipherMalloc() and must be freed by the calling
81449 ** function.
81450 **
81451 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81452 ** surround the body of the token are removed.
81453 **
81454 ** Tokens are often just pointers into the original SQL text and so
81455 ** are not \000 terminated and are not persistent.  The returned string
81456 ** is \000 terminated and is persistent.
81457 */
81458 SQLCIPHER_PRIVATE char *sqlcipher3NameFromToken(sqlcipher3 *db, Token *pName){
81459   char *zName;
81460   if( pName ){
81461     zName = sqlcipher3DbStrNDup(db, (char*)pName->z, pName->n);
81462     sqlcipher3Dequote(zName);
81463   }else{
81464     zName = 0;
81465   }
81466   return zName;
81467 }
81468
81469 /*
81470 ** Open the sqlcipher_master table stored in database number iDb for
81471 ** writing. The table is opened using cursor 0.
81472 */
81473 SQLCIPHER_PRIVATE void sqlcipher3OpenMasterTable(Parse *p, int iDb){
81474   Vdbe *v = sqlcipher3GetVdbe(p);
81475   sqlcipher3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81476   sqlcipher3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81477   sqlcipher3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81478   if( p->nTab==0 ){
81479     p->nTab = 1;
81480   }
81481 }
81482
81483 /*
81484 ** Parameter zName points to a nul-terminated buffer containing the name
81485 ** of a database ("main", "temp" or the name of an attached db). This
81486 ** function returns the index of the named database in db->aDb[], or
81487 ** -1 if the named db cannot be found.
81488 */
81489 SQLCIPHER_PRIVATE int sqlcipher3FindDbName(sqlcipher3 *db, const char *zName){
81490   int i = -1;         /* Database number */
81491   if( zName ){
81492     Db *pDb;
81493     int n = sqlcipher3Strlen30(zName);
81494     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81495       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlcipher3Strlen30(pDb->zName) && 
81496           0==sqlcipher3StrICmp(pDb->zName, zName) ){
81497         break;
81498       }
81499     }
81500   }
81501   return i;
81502 }
81503
81504 /*
81505 ** The token *pName contains the name of a database (either "main" or
81506 ** "temp" or the name of an attached db). This routine returns the
81507 ** index of the named database in db->aDb[], or -1 if the named db 
81508 ** does not exist.
81509 */
81510 SQLCIPHER_PRIVATE int sqlcipher3FindDb(sqlcipher3 *db, Token *pName){
81511   int i;                               /* Database number */
81512   char *zName;                         /* Name we are searching for */
81513   zName = sqlcipher3NameFromToken(db, pName);
81514   i = sqlcipher3FindDbName(db, zName);
81515   sqlcipher3DbFree(db, zName);
81516   return i;
81517 }
81518
81519 /* The table or view or trigger name is passed to this routine via tokens
81520 ** pName1 and pName2. If the table name was fully qualified, for example:
81521 **
81522 ** CREATE TABLE xxx.yyy (...);
81523 ** 
81524 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81525 ** the table name is not fully qualified, i.e.:
81526 **
81527 ** CREATE TABLE yyy(...);
81528 **
81529 ** Then pName1 is set to "yyy" and pName2 is "".
81530 **
81531 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81532 ** pName2) that stores the unqualified table name.  The index of the
81533 ** database "xxx" is returned.
81534 */
81535 SQLCIPHER_PRIVATE int sqlcipher3TwoPartName(
81536   Parse *pParse,      /* Parsing and code generating context */
81537   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81538   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81539   Token **pUnqual     /* Write the unqualified object name here */
81540 ){
81541   int iDb;                    /* Database holding the object */
81542   sqlcipher3 *db = pParse->db;
81543
81544   if( ALWAYS(pName2!=0) && pName2->n>0 ){
81545     if( db->init.busy ) {
81546       sqlcipher3ErrorMsg(pParse, "corrupt database");
81547       pParse->nErr++;
81548       return -1;
81549     }
81550     *pUnqual = pName2;
81551     iDb = sqlcipher3FindDb(db, pName1);
81552     if( iDb<0 ){
81553       sqlcipher3ErrorMsg(pParse, "unknown database %T", pName1);
81554       pParse->nErr++;
81555       return -1;
81556     }
81557   }else{
81558     assert( db->init.iDb==0 || db->init.busy );
81559     iDb = db->init.iDb;
81560     *pUnqual = pName1;
81561   }
81562   return iDb;
81563 }
81564
81565 /*
81566 ** This routine is used to check if the UTF-8 string zName is a legal
81567 ** unqualified name for a new schema object (table, index, view or
81568 ** trigger). All names are legal except those that begin with the string
81569 ** "sqlcipher_" (in upper, lower or mixed case). This portion of the namespace
81570 ** is reserved for internal use.
81571 */
81572 SQLCIPHER_PRIVATE int sqlcipher3CheckObjectName(Parse *pParse, const char *zName){
81573   if( !pParse->db->init.busy && pParse->nested==0 
81574           && (pParse->db->flags & SQLCIPHER_WriteSchema)==0
81575           && 0==sqlcipher3StrNICmp(zName, "sqlcipher_", 7) ){
81576     sqlcipher3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81577     return SQLCIPHER_ERROR;
81578   }
81579   return SQLCIPHER_OK;
81580 }
81581
81582 /*
81583 ** Begin constructing a new table representation in memory.  This is
81584 ** the first of several action routines that get called in response
81585 ** to a CREATE TABLE statement.  In particular, this routine is called
81586 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81587 ** flag is true if the table should be stored in the auxiliary database
81588 ** file instead of in the main database file.  This is normally the case
81589 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
81590 ** CREATE and TABLE.
81591 **
81592 ** The new table record is initialized and put in pParse->pNewTable.
81593 ** As more of the CREATE TABLE statement is parsed, additional action
81594 ** routines will be called to add more information to this record.
81595 ** At the end of the CREATE TABLE statement, the sqlcipher3EndTable() routine
81596 ** is called to complete the construction of the new table record.
81597 */
81598 SQLCIPHER_PRIVATE void sqlcipher3StartTable(
81599   Parse *pParse,   /* Parser context */
81600   Token *pName1,   /* First part of the name of the table or view */
81601   Token *pName2,   /* Second part of the name of the table or view */
81602   int isTemp,      /* True if this is a TEMP table */
81603   int isView,      /* True if this is a VIEW */
81604   int isVirtual,   /* True if this is a VIRTUAL table */
81605   int noErr        /* Do nothing if table already exists */
81606 ){
81607   Table *pTable;
81608   char *zName = 0; /* The name of the new table */
81609   sqlcipher3 *db = pParse->db;
81610   Vdbe *v;
81611   int iDb;         /* Database number to create the table in */
81612   Token *pName;    /* Unqualified name of the table to create */
81613
81614   /* The table or view name to create is passed to this routine via tokens
81615   ** pName1 and pName2. If the table name was fully qualified, for example:
81616   **
81617   ** CREATE TABLE xxx.yyy (...);
81618   ** 
81619   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81620   ** the table name is not fully qualified, i.e.:
81621   **
81622   ** CREATE TABLE yyy(...);
81623   **
81624   ** Then pName1 is set to "yyy" and pName2 is "".
81625   **
81626   ** The call below sets the pName pointer to point at the token (pName1 or
81627   ** pName2) that stores the unqualified table name. The variable iDb is
81628   ** set to the index of the database that the table or view is to be
81629   ** created in.
81630   */
81631   iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
81632   if( iDb<0 ) return;
81633   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81634     /* If creating a temp table, the name may not be qualified. Unless 
81635     ** the database name is "temp" anyway.  */
81636     sqlcipher3ErrorMsg(pParse, "temporary table name must be unqualified");
81637     return;
81638   }
81639   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81640
81641   pParse->sNameToken = *pName;
81642   zName = sqlcipher3NameFromToken(db, pName);
81643   if( zName==0 ) return;
81644   if( SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){
81645     goto begin_table_error;
81646   }
81647   if( db->init.iDb==1 ) isTemp = 1;
81648 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
81649   assert( (isTemp & 1)==isTemp );
81650   {
81651     int code;
81652     char *zDb = db->aDb[iDb].zName;
81653     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81654       goto begin_table_error;
81655     }
81656     if( isView ){
81657       if( !OMIT_TEMPDB && isTemp ){
81658         code = SQLCIPHER_CREATE_TEMP_VIEW;
81659       }else{
81660         code = SQLCIPHER_CREATE_VIEW;
81661       }
81662     }else{
81663       if( !OMIT_TEMPDB && isTemp ){
81664         code = SQLCIPHER_CREATE_TEMP_TABLE;
81665       }else{
81666         code = SQLCIPHER_CREATE_TABLE;
81667       }
81668     }
81669     if( !isVirtual && sqlcipher3AuthCheck(pParse, code, zName, 0, zDb) ){
81670       goto begin_table_error;
81671     }
81672   }
81673 #endif
81674
81675   /* Make sure the new table name does not collide with an existing
81676   ** index or table name in the same database.  Issue an error message if
81677   ** it does. The exception is if the statement being parsed was passed
81678   ** to an sqlcipher3_declare_vtab() call. In that case only the column names
81679   ** and types will be used, so there is no need to test for namespace
81680   ** collisions.
81681   */
81682   if( !IN_DECLARE_VTAB ){
81683     char *zDb = db->aDb[iDb].zName;
81684     if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
81685       goto begin_table_error;
81686     }
81687     pTable = sqlcipher3FindTable(db, zName, zDb);
81688     if( pTable ){
81689       if( !noErr ){
81690         sqlcipher3ErrorMsg(pParse, "table %T already exists", pName);
81691       }else{
81692         assert( !db->init.busy );
81693         sqlcipher3CodeVerifySchema(pParse, iDb);
81694       }
81695       goto begin_table_error;
81696     }
81697     if( sqlcipher3FindIndex(db, zName, zDb)!=0 ){
81698       sqlcipher3ErrorMsg(pParse, "there is already an index named %s", zName);
81699       goto begin_table_error;
81700     }
81701   }
81702
81703   pTable = sqlcipher3DbMallocZero(db, sizeof(Table));
81704   if( pTable==0 ){
81705     db->mallocFailed = 1;
81706     pParse->rc = SQLCIPHER_NOMEM;
81707     pParse->nErr++;
81708     goto begin_table_error;
81709   }
81710   pTable->zName = zName;
81711   pTable->iPKey = -1;
81712   pTable->pSchema = db->aDb[iDb].pSchema;
81713   pTable->nRef = 1;
81714   pTable->nRowEst = 1000000;
81715   assert( pParse->pNewTable==0 );
81716   pParse->pNewTable = pTable;
81717
81718   /* If this is the magic sqlcipher_sequence table used by autoincrement,
81719   ** then record a pointer to this table in the main database structure
81720   ** so that INSERT can find the table easily.
81721   */
81722 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
81723   if( !pParse->nested && strcmp(zName, "sqlcipher_sequence")==0 ){
81724     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
81725     pTable->pSchema->pSeqTab = pTable;
81726   }
81727 #endif
81728
81729   /* Begin generating the code that will insert the table record into
81730   ** the SQLCIPHER_MASTER table.  Note in particular that we must go ahead
81731   ** and allocate the record number for the table entry now.  Before any
81732   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
81733   ** indices to be created and the table record must come before the 
81734   ** indices.  Hence, the record number for the table must be allocated
81735   ** now.
81736   */
81737   if( !db->init.busy && (v = sqlcipher3GetVdbe(pParse))!=0 ){
81738     int j1;
81739     int fileFormat;
81740     int reg1, reg2, reg3;
81741     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
81742
81743 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
81744     if( isVirtual ){
81745       sqlcipher3VdbeAddOp0(v, OP_VBegin);
81746     }
81747 #endif
81748
81749     /* If the file format and encoding in the database have not been set, 
81750     ** set them now.
81751     */
81752     reg1 = pParse->regRowid = ++pParse->nMem;
81753     reg2 = pParse->regRoot = ++pParse->nMem;
81754     reg3 = ++pParse->nMem;
81755     sqlcipher3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
81756     sqlcipher3VdbeUsesBtree(v, iDb);
81757     j1 = sqlcipher3VdbeAddOp1(v, OP_If, reg3);
81758     fileFormat = (db->flags & SQLCIPHER_LegacyFileFmt)!=0 ?
81759                   1 : SQLCIPHER_MAX_FILE_FORMAT;
81760     sqlcipher3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
81761     sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
81762     sqlcipher3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
81763     sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
81764     sqlcipher3VdbeJumpHere(v, j1);
81765
81766     /* This just creates a place-holder record in the sqlcipher_master table.
81767     ** The record created does not contain anything yet.  It will be replaced
81768     ** by the real entry in code generated at sqlcipher3EndTable().
81769     **
81770     ** The rowid for the new entry is left in register pParse->regRowid.
81771     ** The root page number of the new table is left in reg pParse->regRoot.
81772     ** The rowid and root page number values are needed by the code that
81773     ** sqlcipher3EndTable will generate.
81774     */
81775 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE)
81776     if( isView || isVirtual ){
81777       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, reg2);
81778     }else
81779 #endif
81780     {
81781       sqlcipher3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
81782     }
81783     sqlcipher3OpenMasterTable(pParse, iDb);
81784     sqlcipher3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
81785     sqlcipher3VdbeAddOp2(v, OP_Null, 0, reg3);
81786     sqlcipher3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
81787     sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
81788     sqlcipher3VdbeAddOp0(v, OP_Close);
81789   }
81790
81791   /* Normal (non-error) return. */
81792   return;
81793
81794   /* If an error occurs, we jump here */
81795 begin_table_error:
81796   sqlcipher3DbFree(db, zName);
81797   return;
81798 }
81799
81800 /*
81801 ** This macro is used to compare two strings in a case-insensitive manner.
81802 ** It is slightly faster than calling sqlcipher3StrICmp() directly, but
81803 ** produces larger code.
81804 **
81805 ** WARNING: This macro is not compatible with the strcmp() family. It
81806 ** returns true if the two strings are equal, otherwise false.
81807 */
81808 #define STRICMP(x, y) (\
81809 sqlcipher3UpperToLower[*(unsigned char *)(x)]==   \
81810 sqlcipher3UpperToLower[*(unsigned char *)(y)]     \
81811 && sqlcipher3StrICmp((x)+1,(y)+1)==0 )
81812
81813 /*
81814 ** Add a new column to the table currently being constructed.
81815 **
81816 ** The parser calls this routine once for each column declaration
81817 ** in a CREATE TABLE statement.  sqlcipher3StartTable() gets called
81818 ** first to get things going.  Then this routine is called for each
81819 ** column.
81820 */
81821 SQLCIPHER_PRIVATE void sqlcipher3AddColumn(Parse *pParse, Token *pName){
81822   Table *p;
81823   int i;
81824   char *z;
81825   Column *pCol;
81826   sqlcipher3 *db = pParse->db;
81827   if( (p = pParse->pNewTable)==0 ) return;
81828 #if SQLCIPHER_MAX_COLUMN
81829   if( p->nCol+1>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
81830     sqlcipher3ErrorMsg(pParse, "too many columns on %s", p->zName);
81831     return;
81832   }
81833 #endif
81834   z = sqlcipher3NameFromToken(db, pName);
81835   if( z==0 ) return;
81836   for(i=0; i<p->nCol; i++){
81837     if( STRICMP(z, p->aCol[i].zName) ){
81838       sqlcipher3ErrorMsg(pParse, "duplicate column name: %s", z);
81839       sqlcipher3DbFree(db, z);
81840       return;
81841     }
81842   }
81843   if( (p->nCol & 0x7)==0 ){
81844     Column *aNew;
81845     aNew = sqlcipher3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
81846     if( aNew==0 ){
81847       sqlcipher3DbFree(db, z);
81848       return;
81849     }
81850     p->aCol = aNew;
81851   }
81852   pCol = &p->aCol[p->nCol];
81853   memset(pCol, 0, sizeof(p->aCol[0]));
81854   pCol->zName = z;
81855  
81856   /* If there is no type specified, columns have the default affinity
81857   ** 'NONE'. If there is a type specified, then sqlcipher3AddColumnType() will
81858   ** be called next to set pCol->affinity correctly.
81859   */
81860   pCol->affinity = SQLCIPHER_AFF_NONE;
81861   p->nCol++;
81862 }
81863
81864 /*
81865 ** This routine is called by the parser while in the middle of
81866 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
81867 ** been seen on a column.  This routine sets the notNull flag on
81868 ** the column currently under construction.
81869 */
81870 SQLCIPHER_PRIVATE void sqlcipher3AddNotNull(Parse *pParse, int onError){
81871   Table *p;
81872   p = pParse->pNewTable;
81873   if( p==0 || NEVER(p->nCol<1) ) return;
81874   p->aCol[p->nCol-1].notNull = (u8)onError;
81875 }
81876
81877 /*
81878 ** Scan the column type name zType (length nType) and return the
81879 ** associated affinity type.
81880 **
81881 ** This routine does a case-independent search of zType for the 
81882 ** substrings in the following table. If one of the substrings is
81883 ** found, the corresponding affinity is returned. If zType contains
81884 ** more than one of the substrings, entries toward the top of 
81885 ** the table take priority. For example, if zType is 'BLOBINT', 
81886 ** SQLCIPHER_AFF_INTEGER is returned.
81887 **
81888 ** Substring     | Affinity
81889 ** --------------------------------
81890 ** 'INT'         | SQLCIPHER_AFF_INTEGER
81891 ** 'CHAR'        | SQLCIPHER_AFF_TEXT
81892 ** 'CLOB'        | SQLCIPHER_AFF_TEXT
81893 ** 'TEXT'        | SQLCIPHER_AFF_TEXT
81894 ** 'BLOB'        | SQLCIPHER_AFF_NONE
81895 ** 'REAL'        | SQLCIPHER_AFF_REAL
81896 ** 'FLOA'        | SQLCIPHER_AFF_REAL
81897 ** 'DOUB'        | SQLCIPHER_AFF_REAL
81898 **
81899 ** If none of the substrings in the above table are found,
81900 ** SQLCIPHER_AFF_NUMERIC is returned.
81901 */
81902 SQLCIPHER_PRIVATE char sqlcipher3AffinityType(const char *zIn){
81903   u32 h = 0;
81904   char aff = SQLCIPHER_AFF_NUMERIC;
81905
81906   if( zIn ) while( zIn[0] ){
81907     h = (h<<8) + sqlcipher3UpperToLower[(*zIn)&0xff];
81908     zIn++;
81909     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
81910       aff = SQLCIPHER_AFF_TEXT; 
81911     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
81912       aff = SQLCIPHER_AFF_TEXT;
81913     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
81914       aff = SQLCIPHER_AFF_TEXT;
81915     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
81916         && (aff==SQLCIPHER_AFF_NUMERIC || aff==SQLCIPHER_AFF_REAL) ){
81917       aff = SQLCIPHER_AFF_NONE;
81918 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
81919     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
81920         && aff==SQLCIPHER_AFF_NUMERIC ){
81921       aff = SQLCIPHER_AFF_REAL;
81922     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
81923         && aff==SQLCIPHER_AFF_NUMERIC ){
81924       aff = SQLCIPHER_AFF_REAL;
81925     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
81926         && aff==SQLCIPHER_AFF_NUMERIC ){
81927       aff = SQLCIPHER_AFF_REAL;
81928 #endif
81929     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
81930       aff = SQLCIPHER_AFF_INTEGER;
81931       break;
81932     }
81933   }
81934
81935   return aff;
81936 }
81937
81938 /*
81939 ** This routine is called by the parser while in the middle of
81940 ** parsing a CREATE TABLE statement.  The pFirst token is the first
81941 ** token in the sequence of tokens that describe the type of the
81942 ** column currently under construction.   pLast is the last token
81943 ** in the sequence.  Use this information to construct a string
81944 ** that contains the typename of the column and store that string
81945 ** in zType.
81946 */ 
81947 SQLCIPHER_PRIVATE void sqlcipher3AddColumnType(Parse *pParse, Token *pType){
81948   Table *p;
81949   Column *pCol;
81950
81951   p = pParse->pNewTable;
81952   if( p==0 || NEVER(p->nCol<1) ) return;
81953   pCol = &p->aCol[p->nCol-1];
81954   assert( pCol->zType==0 );
81955   pCol->zType = sqlcipher3NameFromToken(pParse->db, pType);
81956   pCol->affinity = sqlcipher3AffinityType(pCol->zType);
81957 }
81958
81959 /*
81960 ** The expression is the default value for the most recently added column
81961 ** of the table currently under construction.
81962 **
81963 ** Default value expressions must be constant.  Raise an exception if this
81964 ** is not the case.
81965 **
81966 ** This routine is called by the parser while in the middle of
81967 ** parsing a CREATE TABLE statement.
81968 */
81969 SQLCIPHER_PRIVATE void sqlcipher3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
81970   Table *p;
81971   Column *pCol;
81972   sqlcipher3 *db = pParse->db;
81973   p = pParse->pNewTable;
81974   if( p!=0 ){
81975     pCol = &(p->aCol[p->nCol-1]);
81976     if( !sqlcipher3ExprIsConstantOrFunction(pSpan->pExpr) ){
81977       sqlcipher3ErrorMsg(pParse, "default value of column [%s] is not constant",
81978           pCol->zName);
81979     }else{
81980       /* A copy of pExpr is used instead of the original, as pExpr contains
81981       ** tokens that point to volatile memory. The 'span' of the expression
81982       ** is required by pragma table_info.
81983       */
81984       sqlcipher3ExprDelete(db, pCol->pDflt);
81985       pCol->pDflt = sqlcipher3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
81986       sqlcipher3DbFree(db, pCol->zDflt);
81987       pCol->zDflt = sqlcipher3DbStrNDup(db, (char*)pSpan->zStart,
81988                                      (int)(pSpan->zEnd - pSpan->zStart));
81989     }
81990   }
81991   sqlcipher3ExprDelete(db, pSpan->pExpr);
81992 }
81993
81994 /*
81995 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
81996 ** of columns that form the primary key.  If pList is NULL, then the
81997 ** most recently added column of the table is the primary key.
81998 **
81999 ** A table can have at most one primary key.  If the table already has
82000 ** a primary key (and this is the second primary key) then create an
82001 ** error.
82002 **
82003 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
82004 ** then we will try to use that column as the rowid.  Set the Table.iPKey
82005 ** field of the table under construction to be the index of the
82006 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
82007 ** no INTEGER PRIMARY KEY.
82008 **
82009 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
82010 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
82011 */
82012 SQLCIPHER_PRIVATE void sqlcipher3AddPrimaryKey(
82013   Parse *pParse,    /* Parsing context */
82014   ExprList *pList,  /* List of field names to be indexed */
82015   int onError,      /* What to do with a uniqueness conflict */
82016   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
82017   int sortOrder     /* SQLCIPHER_SO_ASC or SQLCIPHER_SO_DESC */
82018 ){
82019   Table *pTab = pParse->pNewTable;
82020   char *zType = 0;
82021   int iCol = -1, i;
82022   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
82023   if( pTab->tabFlags & TF_HasPrimaryKey ){
82024     sqlcipher3ErrorMsg(pParse, 
82025       "table \"%s\" has more than one primary key", pTab->zName);
82026     goto primary_key_exit;
82027   }
82028   pTab->tabFlags |= TF_HasPrimaryKey;
82029   if( pList==0 ){
82030     iCol = pTab->nCol - 1;
82031     pTab->aCol[iCol].isPrimKey = 1;
82032   }else{
82033     for(i=0; i<pList->nExpr; i++){
82034       for(iCol=0; iCol<pTab->nCol; iCol++){
82035         if( sqlcipher3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
82036           break;
82037         }
82038       }
82039       if( iCol<pTab->nCol ){
82040         pTab->aCol[iCol].isPrimKey = 1;
82041       }
82042     }
82043     if( pList->nExpr>1 ) iCol = -1;
82044   }
82045   if( iCol>=0 && iCol<pTab->nCol ){
82046     zType = pTab->aCol[iCol].zType;
82047   }
82048   if( zType && sqlcipher3StrICmp(zType, "INTEGER")==0
82049         && sortOrder==SQLCIPHER_SO_ASC ){
82050     pTab->iPKey = iCol;
82051     pTab->keyConf = (u8)onError;
82052     assert( autoInc==0 || autoInc==1 );
82053     pTab->tabFlags |= autoInc*TF_Autoincrement;
82054   }else if( autoInc ){
82055 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
82056     sqlcipher3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
82057        "INTEGER PRIMARY KEY");
82058 #endif
82059   }else{
82060     Index *p;
82061     p = sqlcipher3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
82062     if( p ){
82063       p->autoIndex = 2;
82064     }
82065     pList = 0;
82066   }
82067
82068 primary_key_exit:
82069   sqlcipher3ExprListDelete(pParse->db, pList);
82070   return;
82071 }
82072
82073 /*
82074 ** Add a new CHECK constraint to the table currently under construction.
82075 */
82076 SQLCIPHER_PRIVATE void sqlcipher3AddCheckConstraint(
82077   Parse *pParse,    /* Parsing context */
82078   Expr *pCheckExpr  /* The check expression */
82079 ){
82080   sqlcipher3 *db = pParse->db;
82081 #ifndef SQLCIPHER_OMIT_CHECK
82082   Table *pTab = pParse->pNewTable;
82083   if( pTab && !IN_DECLARE_VTAB ){
82084     pTab->pCheck = sqlcipher3ExprAnd(db, pTab->pCheck, pCheckExpr);
82085   }else
82086 #endif
82087   {
82088     sqlcipher3ExprDelete(db, pCheckExpr);
82089   }
82090 }
82091
82092 /*
82093 ** Set the collation function of the most recently parsed table column
82094 ** to the CollSeq given.
82095 */
82096 SQLCIPHER_PRIVATE void sqlcipher3AddCollateType(Parse *pParse, Token *pToken){
82097   Table *p;
82098   int i;
82099   char *zColl;              /* Dequoted name of collation sequence */
82100   sqlcipher3 *db;
82101
82102   if( (p = pParse->pNewTable)==0 ) return;
82103   i = p->nCol-1;
82104   db = pParse->db;
82105   zColl = sqlcipher3NameFromToken(db, pToken);
82106   if( !zColl ) return;
82107
82108   if( sqlcipher3LocateCollSeq(pParse, zColl) ){
82109     Index *pIdx;
82110     p->aCol[i].zColl = zColl;
82111   
82112     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82113     ** then an index may have been created on this column before the
82114     ** collation type was added. Correct this if it is the case.
82115     */
82116     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82117       assert( pIdx->nColumn==1 );
82118       if( pIdx->aiColumn[0]==i ){
82119         pIdx->azColl[0] = p->aCol[i].zColl;
82120       }
82121     }
82122   }else{
82123     sqlcipher3DbFree(db, zColl);
82124   }
82125 }
82126
82127 /*
82128 ** This function returns the collation sequence for database native text
82129 ** encoding identified by the string zName, length nName.
82130 **
82131 ** If the requested collation sequence is not available, or not available
82132 ** in the database native encoding, the collation factory is invoked to
82133 ** request it. If the collation factory does not supply such a sequence,
82134 ** and the sequence is available in another text encoding, then that is
82135 ** returned instead.
82136 **
82137 ** If no versions of the requested collations sequence are available, or
82138 ** another error occurs, NULL is returned and an error message written into
82139 ** pParse.
82140 **
82141 ** This routine is a wrapper around sqlcipher3FindCollSeq().  This routine
82142 ** invokes the collation factory if the named collation cannot be found
82143 ** and generates an error message.
82144 **
82145 ** See also: sqlcipher3FindCollSeq(), sqlcipher3GetCollSeq()
82146 */
82147 SQLCIPHER_PRIVATE CollSeq *sqlcipher3LocateCollSeq(Parse *pParse, const char *zName){
82148   sqlcipher3 *db = pParse->db;
82149   u8 enc = ENC(db);
82150   u8 initbusy = db->init.busy;
82151   CollSeq *pColl;
82152
82153   pColl = sqlcipher3FindCollSeq(db, enc, zName, initbusy);
82154   if( !initbusy && (!pColl || !pColl->xCmp) ){
82155     pColl = sqlcipher3GetCollSeq(db, enc, pColl, zName);
82156     if( !pColl ){
82157       sqlcipher3ErrorMsg(pParse, "no such collation sequence: %s", zName);
82158     }
82159   }
82160
82161   return pColl;
82162 }
82163
82164
82165 /*
82166 ** Generate code that will increment the schema cookie.
82167 **
82168 ** The schema cookie is used to determine when the schema for the
82169 ** database changes.  After each schema change, the cookie value
82170 ** changes.  When a process first reads the schema it records the
82171 ** cookie.  Thereafter, whenever it goes to access the database,
82172 ** it checks the cookie to make sure the schema has not changed
82173 ** since it was last read.
82174 **
82175 ** This plan is not completely bullet-proof.  It is possible for
82176 ** the schema to change multiple times and for the cookie to be
82177 ** set back to prior value.  But schema changes are infrequent
82178 ** and the probability of hitting the same cookie value is only
82179 ** 1 chance in 2^32.  So we're safe enough.
82180 */
82181 SQLCIPHER_PRIVATE void sqlcipher3ChangeCookie(Parse *pParse, int iDb){
82182   int r1 = sqlcipher3GetTempReg(pParse);
82183   sqlcipher3 *db = pParse->db;
82184   Vdbe *v = pParse->pVdbe;
82185   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82186   sqlcipher3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82187   sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82188   sqlcipher3ReleaseTempReg(pParse, r1);
82189 }
82190
82191 /*
82192 ** Measure the number of characters needed to output the given
82193 ** identifier.  The number returned includes any quotes used
82194 ** but does not include the null terminator.
82195 **
82196 ** The estimate is conservative.  It might be larger that what is
82197 ** really needed.
82198 */
82199 static int identLength(const char *z){
82200   int n;
82201   for(n=0; *z; n++, z++){
82202     if( *z=='"' ){ n++; }
82203   }
82204   return n + 2;
82205 }
82206
82207 /*
82208 ** The first parameter is a pointer to an output buffer. The second 
82209 ** parameter is a pointer to an integer that contains the offset at
82210 ** which to write into the output buffer. This function copies the
82211 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
82212 ** to the specified offset in the buffer and updates *pIdx to refer
82213 ** to the first byte after the last byte written before returning.
82214 ** 
82215 ** If the string zSignedIdent consists entirely of alpha-numeric
82216 ** characters, does not begin with a digit and is not an SQL keyword,
82217 ** then it is copied to the output buffer exactly as it is. Otherwise,
82218 ** it is quoted using double-quotes.
82219 */
82220 static void identPut(char *z, int *pIdx, char *zSignedIdent){
82221   unsigned char *zIdent = (unsigned char*)zSignedIdent;
82222   int i, j, needQuote;
82223   i = *pIdx;
82224
82225   for(j=0; zIdent[j]; j++){
82226     if( !sqlcipher3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82227   }
82228   needQuote = sqlcipher3Isdigit(zIdent[0]) || sqlcipher3KeywordCode(zIdent, j)!=TK_ID;
82229   if( !needQuote ){
82230     needQuote = zIdent[j];
82231   }
82232
82233   if( needQuote ) z[i++] = '"';
82234   for(j=0; zIdent[j]; j++){
82235     z[i++] = zIdent[j];
82236     if( zIdent[j]=='"' ) z[i++] = '"';
82237   }
82238   if( needQuote ) z[i++] = '"';
82239   z[i] = 0;
82240   *pIdx = i;
82241 }
82242
82243 /*
82244 ** Generate a CREATE TABLE statement appropriate for the given
82245 ** table.  Memory to hold the text of the statement is obtained
82246 ** from sqlcipherMalloc() and must be freed by the calling function.
82247 */
82248 static char *createTableStmt(sqlcipher3 *db, Table *p){
82249   int i, k, n;
82250   char *zStmt;
82251   char *zSep, *zSep2, *zEnd;
82252   Column *pCol;
82253   n = 0;
82254   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82255     n += identLength(pCol->zName) + 5;
82256   }
82257   n += identLength(p->zName);
82258   if( n<50 ){ 
82259     zSep = "";
82260     zSep2 = ",";
82261     zEnd = ")";
82262   }else{
82263     zSep = "\n  ";
82264     zSep2 = ",\n  ";
82265     zEnd = "\n)";
82266   }
82267   n += 35 + 6*p->nCol;
82268   zStmt = sqlcipher3DbMallocRaw(0, n);
82269   if( zStmt==0 ){
82270     db->mallocFailed = 1;
82271     return 0;
82272   }
82273   sqlcipher3_snprintf(n, zStmt, "CREATE TABLE ");
82274   k = sqlcipher3Strlen30(zStmt);
82275   identPut(zStmt, &k, p->zName);
82276   zStmt[k++] = '(';
82277   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82278     static const char * const azType[] = {
82279         /* SQLCIPHER_AFF_TEXT    */ " TEXT",
82280         /* SQLCIPHER_AFF_NONE    */ "",
82281         /* SQLCIPHER_AFF_NUMERIC */ " NUM",
82282         /* SQLCIPHER_AFF_INTEGER */ " INT",
82283         /* SQLCIPHER_AFF_REAL    */ " REAL"
82284     };
82285     int len;
82286     const char *zType;
82287
82288     sqlcipher3_snprintf(n-k, &zStmt[k], zSep);
82289     k += sqlcipher3Strlen30(&zStmt[k]);
82290     zSep = zSep2;
82291     identPut(zStmt, &k, pCol->zName);
82292     assert( pCol->affinity-SQLCIPHER_AFF_TEXT >= 0 );
82293     assert( pCol->affinity-SQLCIPHER_AFF_TEXT < ArraySize(azType) );
82294     testcase( pCol->affinity==SQLCIPHER_AFF_TEXT );
82295     testcase( pCol->affinity==SQLCIPHER_AFF_NONE );
82296     testcase( pCol->affinity==SQLCIPHER_AFF_NUMERIC );
82297     testcase( pCol->affinity==SQLCIPHER_AFF_INTEGER );
82298     testcase( pCol->affinity==SQLCIPHER_AFF_REAL );
82299     
82300     zType = azType[pCol->affinity - SQLCIPHER_AFF_TEXT];
82301     len = sqlcipher3Strlen30(zType);
82302     assert( pCol->affinity==SQLCIPHER_AFF_NONE 
82303             || pCol->affinity==sqlcipher3AffinityType(zType) );
82304     memcpy(&zStmt[k], zType, len);
82305     k += len;
82306     assert( k<=n );
82307   }
82308   sqlcipher3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82309   return zStmt;
82310 }
82311
82312 /*
82313 ** This routine is called to report the final ")" that terminates
82314 ** a CREATE TABLE statement.
82315 **
82316 ** The table structure that other action routines have been building
82317 ** is added to the internal hash tables, assuming no errors have
82318 ** occurred.
82319 **
82320 ** An entry for the table is made in the master table on disk, unless
82321 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82322 ** it means we are reading the sqlcipher_master table because we just
82323 ** connected to the database or because the sqlcipher_master table has
82324 ** recently changed, so the entry for this table already exists in
82325 ** the sqlcipher_master table.  We do not want to create it again.
82326 **
82327 ** If the pSelect argument is not NULL, it means that this routine
82328 ** was called to create a table generated from a 
82329 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82330 ** the new table will match the result set of the SELECT.
82331 */
82332 SQLCIPHER_PRIVATE void sqlcipher3EndTable(
82333   Parse *pParse,          /* Parse context */
82334   Token *pCons,           /* The ',' token after the last column defn. */
82335   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82336   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82337 ){
82338   Table *p;
82339   sqlcipher3 *db = pParse->db;
82340   int iDb;
82341
82342   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82343     return;
82344   }
82345   p = pParse->pNewTable;
82346   if( p==0 ) return;
82347
82348   assert( !db->init.busy || !pSelect );
82349
82350   iDb = sqlcipher3SchemaToIndex(db, p->pSchema);
82351
82352 #ifndef SQLCIPHER_OMIT_CHECK
82353   /* Resolve names in all CHECK constraint expressions.
82354   */
82355   if( p->pCheck ){
82356     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82357     NameContext sNC;                /* Name context for pParse->pNewTable */
82358
82359     memset(&sNC, 0, sizeof(sNC));
82360     memset(&sSrc, 0, sizeof(sSrc));
82361     sSrc.nSrc = 1;
82362     sSrc.a[0].zName = p->zName;
82363     sSrc.a[0].pTab = p;
82364     sSrc.a[0].iCursor = -1;
82365     sNC.pParse = pParse;
82366     sNC.pSrcList = &sSrc;
82367     sNC.isCheck = 1;
82368     if( sqlcipher3ResolveExprNames(&sNC, p->pCheck) ){
82369       return;
82370     }
82371   }
82372 #endif /* !defined(SQLCIPHER_OMIT_CHECK) */
82373
82374   /* If the db->init.busy is 1 it means we are reading the SQL off the
82375   ** "sqlcipher_master" or "sqlcipher_temp_master" table on the disk.
82376   ** So do not write to the disk again.  Extract the root page number
82377   ** for the table from the db->init.newTnum field.  (The page number
82378   ** should have been put there by the sqlcipherOpenCb routine.)
82379   */
82380   if( db->init.busy ){
82381     p->tnum = db->init.newTnum;
82382   }
82383
82384   /* If not initializing, then create a record for the new table
82385   ** in the SQLCIPHER_MASTER table of the database.
82386   **
82387   ** If this is a TEMPORARY table, write the entry into the auxiliary
82388   ** file instead of into the main database file.
82389   */
82390   if( !db->init.busy ){
82391     int n;
82392     Vdbe *v;
82393     char *zType;    /* "view" or "table" */
82394     char *zType2;   /* "VIEW" or "TABLE" */
82395     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82396
82397     v = sqlcipher3GetVdbe(pParse);
82398     if( NEVER(v==0) ) return;
82399
82400     sqlcipher3VdbeAddOp1(v, OP_Close, 0);
82401
82402     /* 
82403     ** Initialize zType for the new view or table.
82404     */
82405     if( p->pSelect==0 ){
82406       /* A regular table */
82407       zType = "table";
82408       zType2 = "TABLE";
82409 #ifndef SQLCIPHER_OMIT_VIEW
82410     }else{
82411       /* A view */
82412       zType = "view";
82413       zType2 = "VIEW";
82414 #endif
82415     }
82416
82417     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82418     ** statement to populate the new table. The root-page number for the
82419     ** new table is in register pParse->regRoot.
82420     **
82421     ** Once the SELECT has been coded by sqlcipher3Select(), it is in a
82422     ** suitable state to query for the column names and types to be used
82423     ** by the new table.
82424     **
82425     ** A shared-cache write-lock is not required to write to the new table,
82426     ** as a schema-lock must have already been obtained to create it. Since
82427     ** a schema-lock excludes all other database users, the write-lock would
82428     ** be redundant.
82429     */
82430     if( pSelect ){
82431       SelectDest dest;
82432       Table *pSelTab;
82433
82434       assert(pParse->nTab==1);
82435       sqlcipher3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82436       sqlcipher3VdbeChangeP5(v, 1);
82437       pParse->nTab = 2;
82438       sqlcipher3SelectDestInit(&dest, SRT_Table, 1);
82439       sqlcipher3Select(pParse, pSelect, &dest);
82440       sqlcipher3VdbeAddOp1(v, OP_Close, 1);
82441       if( pParse->nErr==0 ){
82442         pSelTab = sqlcipher3ResultSetOfSelect(pParse, pSelect);
82443         if( pSelTab==0 ) return;
82444         assert( p->aCol==0 );
82445         p->nCol = pSelTab->nCol;
82446         p->aCol = pSelTab->aCol;
82447         pSelTab->nCol = 0;
82448         pSelTab->aCol = 0;
82449         sqlcipher3DeleteTable(db, pSelTab);
82450       }
82451     }
82452
82453     /* Compute the complete text of the CREATE statement */
82454     if( pSelect ){
82455       zStmt = createTableStmt(db, p);
82456     }else{
82457       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82458       zStmt = sqlcipher3MPrintf(db, 
82459           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82460       );
82461     }
82462
82463     /* A slot for the record has already been allocated in the 
82464     ** SQLCIPHER_MASTER table.  We just need to update that slot with all
82465     ** the information we've collected.
82466     */
82467     sqlcipher3NestedParse(pParse,
82468       "UPDATE %Q.%s "
82469          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82470        "WHERE rowid=#%d",
82471       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82472       zType,
82473       p->zName,
82474       p->zName,
82475       pParse->regRoot,
82476       zStmt,
82477       pParse->regRowid
82478     );
82479     sqlcipher3DbFree(db, zStmt);
82480     sqlcipher3ChangeCookie(pParse, iDb);
82481
82482 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
82483     /* Check to see if we need to create an sqlcipher_sequence table for
82484     ** keeping track of autoincrement keys.
82485     */
82486     if( p->tabFlags & TF_Autoincrement ){
82487       Db *pDb = &db->aDb[iDb];
82488       assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82489       if( pDb->pSchema->pSeqTab==0 ){
82490         sqlcipher3NestedParse(pParse,
82491           "CREATE TABLE %Q.sqlcipher_sequence(name,seq)",
82492           pDb->zName
82493         );
82494       }
82495     }
82496 #endif
82497
82498     /* Reparse everything to update our internal data structures */
82499     sqlcipher3VdbeAddParseSchemaOp(v, iDb,
82500                sqlcipher3MPrintf(db, "tbl_name='%q'", p->zName));
82501   }
82502
82503
82504   /* Add the table to the in-memory representation of the database.
82505   */
82506   if( db->init.busy ){
82507     Table *pOld;
82508     Schema *pSchema = p->pSchema;
82509     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82510     pOld = sqlcipher3HashInsert(&pSchema->tblHash, p->zName,
82511                              sqlcipher3Strlen30(p->zName),p);
82512     if( pOld ){
82513       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82514       db->mallocFailed = 1;
82515       return;
82516     }
82517     pParse->pNewTable = 0;
82518     db->nTable++;
82519     db->flags |= SQLCIPHER_InternChanges;
82520
82521 #ifndef SQLCIPHER_OMIT_ALTERTABLE
82522     if( !p->pSelect ){
82523       const char *zName = (const char *)pParse->sNameToken.z;
82524       int nName;
82525       assert( !pSelect && pCons && pEnd );
82526       if( pCons->z==0 ){
82527         pCons = pEnd;
82528       }
82529       nName = (int)((const char *)pCons->z - zName);
82530       p->addColOffset = 13 + sqlcipher3Utf8CharLen(zName, nName);
82531     }
82532 #endif
82533   }
82534 }
82535
82536 #ifndef SQLCIPHER_OMIT_VIEW
82537 /*
82538 ** The parser calls this routine in order to create a new VIEW
82539 */
82540 SQLCIPHER_PRIVATE void sqlcipher3CreateView(
82541   Parse *pParse,     /* The parsing context */
82542   Token *pBegin,     /* The CREATE token that begins the statement */
82543   Token *pName1,     /* The token that holds the name of the view */
82544   Token *pName2,     /* The token that holds the name of the view */
82545   Select *pSelect,   /* A SELECT statement that will become the new view */
82546   int isTemp,        /* TRUE for a TEMPORARY view */
82547   int noErr          /* Suppress error messages if VIEW already exists */
82548 ){
82549   Table *p;
82550   int n;
82551   const char *z;
82552   Token sEnd;
82553   DbFixer sFix;
82554   Token *pName = 0;
82555   int iDb;
82556   sqlcipher3 *db = pParse->db;
82557
82558   if( pParse->nVar>0 ){
82559     sqlcipher3ErrorMsg(pParse, "parameters are not allowed in views");
82560     sqlcipher3SelectDelete(db, pSelect);
82561     return;
82562   }
82563   sqlcipher3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82564   p = pParse->pNewTable;
82565   if( p==0 || pParse->nErr ){
82566     sqlcipher3SelectDelete(db, pSelect);
82567     return;
82568   }
82569   sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
82570   iDb = sqlcipher3SchemaToIndex(db, p->pSchema);
82571   if( sqlcipher3FixInit(&sFix, pParse, iDb, "view", pName)
82572     && sqlcipher3FixSelect(&sFix, pSelect)
82573   ){
82574     sqlcipher3SelectDelete(db, pSelect);
82575     return;
82576   }
82577
82578   /* Make a copy of the entire SELECT statement that defines the view.
82579   ** This will force all the Expr.token.z values to be dynamically
82580   ** allocated rather than point to the input string - which means that
82581   ** they will persist after the current sqlcipher3_exec() call returns.
82582   */
82583   p->pSelect = sqlcipher3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82584   sqlcipher3SelectDelete(db, pSelect);
82585   if( db->mallocFailed ){
82586     return;
82587   }
82588   if( !db->init.busy ){
82589     sqlcipher3ViewGetColumnNames(pParse, p);
82590   }
82591
82592   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82593   ** the end.
82594   */
82595   sEnd = pParse->sLastToken;
82596   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82597     sEnd.z += sEnd.n;
82598   }
82599   sEnd.n = 0;
82600   n = (int)(sEnd.z - pBegin->z);
82601   z = pBegin->z;
82602   while( ALWAYS(n>0) && sqlcipher3Isspace(z[n-1]) ){ n--; }
82603   sEnd.z = &z[n-1];
82604   sEnd.n = 1;
82605
82606   /* Use sqlcipher3EndTable() to add the view to the SQLCIPHER_MASTER table */
82607   sqlcipher3EndTable(pParse, 0, &sEnd, 0);
82608   return;
82609 }
82610 #endif /* SQLCIPHER_OMIT_VIEW */
82611
82612 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE)
82613 /*
82614 ** The Table structure pTable is really a VIEW.  Fill in the names of
82615 ** the columns of the view in the pTable structure.  Return the number
82616 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82617 */
82618 SQLCIPHER_PRIVATE int sqlcipher3ViewGetColumnNames(Parse *pParse, Table *pTable){
82619   Table *pSelTab;   /* A fake table from which we get the result set */
82620   Select *pSel;     /* Copy of the SELECT that implements the view */
82621   int nErr = 0;     /* Number of errors encountered */
82622   int n;            /* Temporarily holds the number of cursors assigned */
82623   sqlcipher3 *db = pParse->db;  /* Database connection for malloc errors */
82624   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82625
82626   assert( pTable );
82627
82628 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
82629   if( sqlcipher3VtabCallConnect(pParse, pTable) ){
82630     return SQLCIPHER_ERROR;
82631   }
82632   if( IsVirtual(pTable) ) return 0;
82633 #endif
82634
82635 #ifndef SQLCIPHER_OMIT_VIEW
82636   /* A positive nCol means the columns names for this view are
82637   ** already known.
82638   */
82639   if( pTable->nCol>0 ) return 0;
82640
82641   /* A negative nCol is a special marker meaning that we are currently
82642   ** trying to compute the column names.  If we enter this routine with
82643   ** a negative nCol, it means two or more views form a loop, like this:
82644   **
82645   **     CREATE VIEW one AS SELECT * FROM two;
82646   **     CREATE VIEW two AS SELECT * FROM one;
82647   **
82648   ** Actually, the error above is now caught prior to reaching this point.
82649   ** But the following test is still important as it does come up
82650   ** in the following:
82651   ** 
82652   **     CREATE TABLE main.ex1(a);
82653   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82654   **     SELECT * FROM temp.ex1;
82655   */
82656   if( pTable->nCol<0 ){
82657     sqlcipher3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82658     return 1;
82659   }
82660   assert( pTable->nCol>=0 );
82661
82662   /* If we get this far, it means we need to compute the table names.
82663   ** Note that the call to sqlcipher3ResultSetOfSelect() will expand any
82664   ** "*" elements in the results set of the view and will assign cursors
82665   ** to the elements of the FROM clause.  But we do not want these changes
82666   ** to be permanent.  So the computation is done on a copy of the SELECT
82667   ** statement that defines the view.
82668   */
82669   assert( pTable->pSelect );
82670   pSel = sqlcipher3SelectDup(db, pTable->pSelect, 0);
82671   if( pSel ){
82672     u8 enableLookaside = db->lookaside.bEnabled;
82673     n = pParse->nTab;
82674     sqlcipher3SrcListAssignCursors(pParse, pSel->pSrc);
82675     pTable->nCol = -1;
82676     db->lookaside.bEnabled = 0;
82677 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
82678     xAuth = db->xAuth;
82679     db->xAuth = 0;
82680     pSelTab = sqlcipher3ResultSetOfSelect(pParse, pSel);
82681     db->xAuth = xAuth;
82682 #else
82683     pSelTab = sqlcipher3ResultSetOfSelect(pParse, pSel);
82684 #endif
82685     db->lookaside.bEnabled = enableLookaside;
82686     pParse->nTab = n;
82687     if( pSelTab ){
82688       assert( pTable->aCol==0 );
82689       pTable->nCol = pSelTab->nCol;
82690       pTable->aCol = pSelTab->aCol;
82691       pSelTab->nCol = 0;
82692       pSelTab->aCol = 0;
82693       sqlcipher3DeleteTable(db, pSelTab);
82694       assert( sqlcipher3SchemaMutexHeld(db, 0, pTable->pSchema) );
82695       pTable->pSchema->flags |= DB_UnresetViews;
82696     }else{
82697       pTable->nCol = 0;
82698       nErr++;
82699     }
82700     sqlcipher3SelectDelete(db, pSel);
82701   } else {
82702     nErr++;
82703   }
82704 #endif /* SQLCIPHER_OMIT_VIEW */
82705   return nErr;  
82706 }
82707 #endif /* !defined(SQLCIPHER_OMIT_VIEW) || !defined(SQLCIPHER_OMIT_VIRTUALTABLE) */
82708
82709 #ifndef SQLCIPHER_OMIT_VIEW
82710 /*
82711 ** Clear the column names from every VIEW in database idx.
82712 */
82713 static void sqlcipherViewResetAll(sqlcipher3 *db, int idx){
82714   HashElem *i;
82715   assert( sqlcipher3SchemaMutexHeld(db, idx, 0) );
82716   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
82717   for(i=sqlcipherHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqlcipherHashNext(i)){
82718     Table *pTab = sqlcipherHashData(i);
82719     if( pTab->pSelect ){
82720       sqlcipherDeleteColumnNames(db, pTab);
82721       pTab->aCol = 0;
82722       pTab->nCol = 0;
82723     }
82724   }
82725   DbClearProperty(db, idx, DB_UnresetViews);
82726 }
82727 #else
82728 # define sqlcipherViewResetAll(A,B)
82729 #endif /* SQLCIPHER_OMIT_VIEW */
82730
82731 /*
82732 ** This function is called by the VDBE to adjust the internal schema
82733 ** used by SQLite when the btree layer moves a table root page. The
82734 ** root-page of a table or index in database iDb has changed from iFrom
82735 ** to iTo.
82736 **
82737 ** Ticket #1728:  The symbol table might still contain information
82738 ** on tables and/or indices that are the process of being deleted.
82739 ** If you are unlucky, one of those deleted indices or tables might
82740 ** have the same rootpage number as the real table or index that is
82741 ** being moved.  So we cannot stop searching after the first match 
82742 ** because the first match might be for one of the deleted indices
82743 ** or tables and not the table/index that is actually being moved.
82744 ** We must continue looping until all tables and indices with
82745 ** rootpage==iFrom have been converted to have a rootpage of iTo
82746 ** in order to be certain that we got the right one.
82747 */
82748 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
82749 SQLCIPHER_PRIVATE void sqlcipher3RootPageMoved(sqlcipher3 *db, int iDb, int iFrom, int iTo){
82750   HashElem *pElem;
82751   Hash *pHash;
82752   Db *pDb;
82753
82754   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
82755   pDb = &db->aDb[iDb];
82756   pHash = &pDb->pSchema->tblHash;
82757   for(pElem=sqlcipherHashFirst(pHash); pElem; pElem=sqlcipherHashNext(pElem)){
82758     Table *pTab = sqlcipherHashData(pElem);
82759     if( pTab->tnum==iFrom ){
82760       pTab->tnum = iTo;
82761     }
82762   }
82763   pHash = &pDb->pSchema->idxHash;
82764   for(pElem=sqlcipherHashFirst(pHash); pElem; pElem=sqlcipherHashNext(pElem)){
82765     Index *pIdx = sqlcipherHashData(pElem);
82766     if( pIdx->tnum==iFrom ){
82767       pIdx->tnum = iTo;
82768     }
82769   }
82770 }
82771 #endif
82772
82773 /*
82774 ** Write code to erase the table with root-page iTable from database iDb.
82775 ** Also write code to modify the sqlcipher_master table and internal schema
82776 ** if a root-page of another table is moved by the btree-layer whilst
82777 ** erasing iTable (this can happen with an auto-vacuum database).
82778 */ 
82779 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
82780   Vdbe *v = sqlcipher3GetVdbe(pParse);
82781   int r1 = sqlcipher3GetTempReg(pParse);
82782   sqlcipher3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
82783   sqlcipher3MayAbort(pParse);
82784 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
82785   /* OP_Destroy stores an in integer r1. If this integer
82786   ** is non-zero, then it is the root page number of a table moved to
82787   ** location iTable. The following code modifies the sqlcipher_master table to
82788   ** reflect this.
82789   **
82790   ** The "#NNN" in the SQL is a special constant that means whatever value
82791   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
82792   ** token for additional information.
82793   */
82794   sqlcipher3NestedParse(pParse, 
82795      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
82796      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
82797 #endif
82798   sqlcipher3ReleaseTempReg(pParse, r1);
82799 }
82800
82801 /*
82802 ** Write VDBE code to erase table pTab and all associated indices on disk.
82803 ** Code to update the sqlcipher_master tables and internal schema definitions
82804 ** in case a root-page belonging to another table is moved by the btree layer
82805 ** is also added (this can happen with an auto-vacuum database).
82806 */
82807 static void destroyTable(Parse *pParse, Table *pTab){
82808 #ifdef SQLCIPHER_OMIT_AUTOVACUUM
82809   Index *pIdx;
82810   int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
82811   destroyRootPage(pParse, pTab->tnum, iDb);
82812   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82813     destroyRootPage(pParse, pIdx->tnum, iDb);
82814   }
82815 #else
82816   /* If the database may be auto-vacuum capable (if SQLCIPHER_OMIT_AUTOVACUUM
82817   ** is not defined), then it is important to call OP_Destroy on the
82818   ** table and index root-pages in order, starting with the numerically 
82819   ** largest root-page number. This guarantees that none of the root-pages
82820   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
82821   ** following were coded:
82822   **
82823   ** OP_Destroy 4 0
82824   ** ...
82825   ** OP_Destroy 5 0
82826   **
82827   ** and root page 5 happened to be the largest root-page number in the
82828   ** database, then root page 5 would be moved to page 4 by the 
82829   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
82830   ** a free-list page.
82831   */
82832   int iTab = pTab->tnum;
82833   int iDestroyed = 0;
82834
82835   while( 1 ){
82836     Index *pIdx;
82837     int iLargest = 0;
82838
82839     if( iDestroyed==0 || iTab<iDestroyed ){
82840       iLargest = iTab;
82841     }
82842     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82843       int iIdx = pIdx->tnum;
82844       assert( pIdx->pSchema==pTab->pSchema );
82845       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
82846         iLargest = iIdx;
82847       }
82848     }
82849     if( iLargest==0 ){
82850       return;
82851     }else{
82852       int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
82853       destroyRootPage(pParse, iLargest, iDb);
82854       iDestroyed = iLargest;
82855     }
82856   }
82857 #endif
82858 }
82859
82860 /*
82861 ** Remove entries from the sqlcipher_statN tables (for N in (1,2,3))
82862 ** after a DROP INDEX or DROP TABLE command.
82863 */
82864 static void sqlcipher3ClearStatTables(
82865   Parse *pParse,         /* The parsing context */
82866   int iDb,               /* The database number */
82867   const char *zType,     /* "idx" or "tbl" */
82868   const char *zName      /* Name of index or table */
82869 ){
82870   int i;
82871   const char *zDbName = pParse->db->aDb[iDb].zName;
82872   for(i=1; i<=3; i++){
82873     char zTab[24];
82874     sqlcipher3_snprintf(sizeof(zTab),zTab,"sqlcipher_stat%d",i);
82875     if( sqlcipher3FindTable(pParse->db, zTab, zDbName) ){
82876       sqlcipher3NestedParse(pParse,
82877         "DELETE FROM %Q.%s WHERE %s=%Q",
82878         zDbName, zTab, zType, zName
82879       );
82880     }
82881   }
82882 }
82883
82884 /*
82885 ** Generate code to drop a table.
82886 */
82887 SQLCIPHER_PRIVATE void sqlcipher3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
82888   Vdbe *v;
82889   sqlcipher3 *db = pParse->db;
82890   Trigger *pTrigger;
82891   Db *pDb = &db->aDb[iDb];
82892
82893   v = sqlcipher3GetVdbe(pParse);
82894   assert( v!=0 );
82895   sqlcipher3BeginWriteOperation(pParse, 1, iDb);
82896
82897 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
82898   if( IsVirtual(pTab) ){
82899     sqlcipher3VdbeAddOp0(v, OP_VBegin);
82900   }
82901 #endif
82902
82903   /* Drop all triggers associated with the table being dropped. Code
82904   ** is generated to remove entries from sqlcipher_master and/or
82905   ** sqlcipher_temp_master if required.
82906   */
82907   pTrigger = sqlcipher3TriggerList(pParse, pTab);
82908   while( pTrigger ){
82909     assert( pTrigger->pSchema==pTab->pSchema || 
82910         pTrigger->pSchema==db->aDb[1].pSchema );
82911     sqlcipher3DropTriggerPtr(pParse, pTrigger);
82912     pTrigger = pTrigger->pNext;
82913   }
82914
82915 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
82916   /* Remove any entries of the sqlcipher_sequence table associated with
82917   ** the table being dropped. This is done before the table is dropped
82918   ** at the btree level, in case the sqlcipher_sequence table needs to
82919   ** move as a result of the drop (can happen in auto-vacuum mode).
82920   */
82921   if( pTab->tabFlags & TF_Autoincrement ){
82922     sqlcipher3NestedParse(pParse,
82923       "DELETE FROM %Q.sqlcipher_sequence WHERE name=%Q",
82924       pDb->zName, pTab->zName
82925     );
82926   }
82927 #endif
82928
82929   /* Drop all SQLCIPHER_MASTER table and index entries that refer to the
82930   ** table. The program name loops through the master table and deletes
82931   ** every row that refers to a table of the same name as the one being
82932   ** dropped. Triggers are handled seperately because a trigger can be
82933   ** created in the temp database that refers to a table in another
82934   ** database.
82935   */
82936   sqlcipher3NestedParse(pParse, 
82937       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
82938       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
82939   if( !isView && !IsVirtual(pTab) ){
82940     destroyTable(pParse, pTab);
82941   }
82942
82943   /* Remove the table entry from SQLite's internal schema and modify
82944   ** the schema cookie.
82945   */
82946   if( IsVirtual(pTab) ){
82947     sqlcipher3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
82948   }
82949   sqlcipher3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
82950   sqlcipher3ChangeCookie(pParse, iDb);
82951   sqlcipherViewResetAll(db, iDb);
82952 }
82953
82954 /*
82955 ** This routine is called to do the work of a DROP TABLE statement.
82956 ** pName is the name of the table to be dropped.
82957 */
82958 SQLCIPHER_PRIVATE void sqlcipher3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
82959   Table *pTab;
82960   Vdbe *v;
82961   sqlcipher3 *db = pParse->db;
82962   int iDb;
82963
82964   if( db->mallocFailed ){
82965     goto exit_drop_table;
82966   }
82967   assert( pParse->nErr==0 );
82968   assert( pName->nSrc==1 );
82969   if( noErr ) db->suppressErr++;
82970   pTab = sqlcipher3LocateTable(pParse, isView, 
82971                             pName->a[0].zName, pName->a[0].zDatabase);
82972   if( noErr ) db->suppressErr--;
82973
82974   if( pTab==0 ){
82975     if( noErr ) sqlcipher3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
82976     goto exit_drop_table;
82977   }
82978   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
82979   assert( iDb>=0 && iDb<db->nDb );
82980
82981   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
82982   ** it is initialized.
82983   */
82984   if( IsVirtual(pTab) && sqlcipher3ViewGetColumnNames(pParse, pTab) ){
82985     goto exit_drop_table;
82986   }
82987 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
82988   {
82989     int code;
82990     const char *zTab = SCHEMA_TABLE(iDb);
82991     const char *zDb = db->aDb[iDb].zName;
82992     const char *zArg2 = 0;
82993     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, zTab, 0, zDb)){
82994       goto exit_drop_table;
82995     }
82996     if( isView ){
82997       if( !OMIT_TEMPDB && iDb==1 ){
82998         code = SQLCIPHER_DROP_TEMP_VIEW;
82999       }else{
83000         code = SQLCIPHER_DROP_VIEW;
83001       }
83002 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
83003     }else if( IsVirtual(pTab) ){
83004       code = SQLCIPHER_DROP_VTABLE;
83005       zArg2 = sqlcipher3GetVTable(db, pTab)->pMod->zName;
83006 #endif
83007     }else{
83008       if( !OMIT_TEMPDB && iDb==1 ){
83009         code = SQLCIPHER_DROP_TEMP_TABLE;
83010       }else{
83011         code = SQLCIPHER_DROP_TABLE;
83012       }
83013     }
83014     if( sqlcipher3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
83015       goto exit_drop_table;
83016     }
83017     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, pTab->zName, 0, zDb) ){
83018       goto exit_drop_table;
83019     }
83020   }
83021 #endif
83022   if( sqlcipher3StrNICmp(pTab->zName, "sqlcipher_", 7)==0 
83023     && sqlcipher3StrNICmp(pTab->zName, "sqlcipher_stat", 11)!=0 ){
83024     sqlcipher3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
83025     goto exit_drop_table;
83026   }
83027
83028 #ifndef SQLCIPHER_OMIT_VIEW
83029   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
83030   ** on a table.
83031   */
83032   if( isView && pTab->pSelect==0 ){
83033     sqlcipher3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
83034     goto exit_drop_table;
83035   }
83036   if( !isView && pTab->pSelect ){
83037     sqlcipher3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
83038     goto exit_drop_table;
83039   }
83040 #endif
83041
83042   /* Generate code to remove the table from the master table
83043   ** on disk.
83044   */
83045   v = sqlcipher3GetVdbe(pParse);
83046   if( v ){
83047     sqlcipher3BeginWriteOperation(pParse, 1, iDb);
83048     sqlcipher3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
83049     sqlcipher3FkDropTable(pParse, pName, pTab);
83050     sqlcipher3CodeDropTable(pParse, pTab, iDb, isView);
83051   }
83052
83053 exit_drop_table:
83054   sqlcipher3SrcListDelete(db, pName);
83055 }
83056
83057 /*
83058 ** This routine is called to create a new foreign key on the table
83059 ** currently under construction.  pFromCol determines which columns
83060 ** in the current table point to the foreign key.  If pFromCol==0 then
83061 ** connect the key to the last column inserted.  pTo is the name of
83062 ** the table referred to.  pToCol is a list of tables in the other
83063 ** pTo table that the foreign key points to.  flags contains all
83064 ** information about the conflict resolution algorithms specified
83065 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
83066 **
83067 ** An FKey structure is created and added to the table currently
83068 ** under construction in the pParse->pNewTable field.
83069 **
83070 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
83071 ** to sqlcipher3DeferForeignKey() might change this to DEFERRED.
83072 */
83073 SQLCIPHER_PRIVATE void sqlcipher3CreateForeignKey(
83074   Parse *pParse,       /* Parsing context */
83075   ExprList *pFromCol,  /* Columns in this table that point to other table */
83076   Token *pTo,          /* Name of the other table */
83077   ExprList *pToCol,    /* Columns in the other table */
83078   int flags            /* Conflict resolution algorithms. */
83079 ){
83080   sqlcipher3 *db = pParse->db;
83081 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
83082   FKey *pFKey = 0;
83083   FKey *pNextTo;
83084   Table *p = pParse->pNewTable;
83085   int nByte;
83086   int i;
83087   int nCol;
83088   char *z;
83089
83090   assert( pTo!=0 );
83091   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
83092   if( pFromCol==0 ){
83093     int iCol = p->nCol-1;
83094     if( NEVER(iCol<0) ) goto fk_end;
83095     if( pToCol && pToCol->nExpr!=1 ){
83096       sqlcipher3ErrorMsg(pParse, "foreign key on %s"
83097          " should reference only one column of table %T",
83098          p->aCol[iCol].zName, pTo);
83099       goto fk_end;
83100     }
83101     nCol = 1;
83102   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
83103     sqlcipher3ErrorMsg(pParse,
83104         "number of columns in foreign key does not match the number of "
83105         "columns in the referenced table");
83106     goto fk_end;
83107   }else{
83108     nCol = pFromCol->nExpr;
83109   }
83110   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83111   if( pToCol ){
83112     for(i=0; i<pToCol->nExpr; i++){
83113       nByte += sqlcipher3Strlen30(pToCol->a[i].zName) + 1;
83114     }
83115   }
83116   pFKey = sqlcipher3DbMallocZero(db, nByte );
83117   if( pFKey==0 ){
83118     goto fk_end;
83119   }
83120   pFKey->pFrom = p;
83121   pFKey->pNextFrom = p->pFKey;
83122   z = (char*)&pFKey->aCol[nCol];
83123   pFKey->zTo = z;
83124   memcpy(z, pTo->z, pTo->n);
83125   z[pTo->n] = 0;
83126   sqlcipher3Dequote(z);
83127   z += pTo->n+1;
83128   pFKey->nCol = nCol;
83129   if( pFromCol==0 ){
83130     pFKey->aCol[0].iFrom = p->nCol-1;
83131   }else{
83132     for(i=0; i<nCol; i++){
83133       int j;
83134       for(j=0; j<p->nCol; j++){
83135         if( sqlcipher3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83136           pFKey->aCol[i].iFrom = j;
83137           break;
83138         }
83139       }
83140       if( j>=p->nCol ){
83141         sqlcipher3ErrorMsg(pParse, 
83142           "unknown column \"%s\" in foreign key definition", 
83143           pFromCol->a[i].zName);
83144         goto fk_end;
83145       }
83146     }
83147   }
83148   if( pToCol ){
83149     for(i=0; i<nCol; i++){
83150       int n = sqlcipher3Strlen30(pToCol->a[i].zName);
83151       pFKey->aCol[i].zCol = z;
83152       memcpy(z, pToCol->a[i].zName, n);
83153       z[n] = 0;
83154       z += n+1;
83155     }
83156   }
83157   pFKey->isDeferred = 0;
83158   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83159   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83160
83161   assert( sqlcipher3SchemaMutexHeld(db, 0, p->pSchema) );
83162   pNextTo = (FKey *)sqlcipher3HashInsert(&p->pSchema->fkeyHash, 
83163       pFKey->zTo, sqlcipher3Strlen30(pFKey->zTo), (void *)pFKey
83164   );
83165   if( pNextTo==pFKey ){
83166     db->mallocFailed = 1;
83167     goto fk_end;
83168   }
83169   if( pNextTo ){
83170     assert( pNextTo->pPrevTo==0 );
83171     pFKey->pNextTo = pNextTo;
83172     pNextTo->pPrevTo = pFKey;
83173   }
83174
83175   /* Link the foreign key to the table as the last step.
83176   */
83177   p->pFKey = pFKey;
83178   pFKey = 0;
83179
83180 fk_end:
83181   sqlcipher3DbFree(db, pFKey);
83182 #endif /* !defined(SQLCIPHER_OMIT_FOREIGN_KEY) */
83183   sqlcipher3ExprListDelete(db, pFromCol);
83184   sqlcipher3ExprListDelete(db, pToCol);
83185 }
83186
83187 /*
83188 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83189 ** clause is seen as part of a foreign key definition.  The isDeferred
83190 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83191 ** The behavior of the most recently created foreign key is adjusted
83192 ** accordingly.
83193 */
83194 SQLCIPHER_PRIVATE void sqlcipher3DeferForeignKey(Parse *pParse, int isDeferred){
83195 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
83196   Table *pTab;
83197   FKey *pFKey;
83198   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83199   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83200   pFKey->isDeferred = (u8)isDeferred;
83201 #endif
83202 }
83203
83204 /*
83205 ** Generate code that will erase and refill index *pIdx.  This is
83206 ** used to initialize a newly created index or to recompute the
83207 ** content of an index in response to a REINDEX command.
83208 **
83209 ** if memRootPage is not negative, it means that the index is newly
83210 ** created.  The register specified by memRootPage contains the
83211 ** root page number of the index.  If memRootPage is negative, then
83212 ** the index already exists and must be cleared before being refilled and
83213 ** the root page number of the index is taken from pIndex->tnum.
83214 */
83215 static void sqlcipher3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83216   Table *pTab = pIndex->pTable;  /* The table that is indexed */
83217   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83218   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83219   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83220   int addr1;                     /* Address of top of loop */
83221   int addr2;                     /* Address to jump to for next iteration */
83222   int tnum;                      /* Root page of index */
83223   Vdbe *v;                       /* Generate code into this virtual machine */
83224   KeyInfo *pKey;                 /* KeyInfo for index */
83225 #ifdef SQLCIPHER_OMIT_MERGE_SORT
83226   int regIdxKey;                 /* Registers containing the index key */
83227 #endif
83228   int regRecord;                 /* Register holding assemblied index record */
83229   sqlcipher3 *db = pParse->db;      /* The database connection */
83230   int iDb = sqlcipher3SchemaToIndex(db, pIndex->pSchema);
83231
83232 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
83233   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_REINDEX, pIndex->zName, 0,
83234       db->aDb[iDb].zName ) ){
83235     return;
83236   }
83237 #endif
83238
83239   /* Require a write-lock on the table to perform this operation */
83240   sqlcipher3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83241
83242   v = sqlcipher3GetVdbe(pParse);
83243   if( v==0 ) return;
83244   if( memRootPage>=0 ){
83245     tnum = memRootPage;
83246   }else{
83247     tnum = pIndex->tnum;
83248     sqlcipher3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83249   }
83250   pKey = sqlcipher3IndexKeyinfo(pParse, pIndex);
83251   sqlcipher3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
83252                     (char *)pKey, P4_KEYINFO_HANDOFF);
83253   if( memRootPage>=0 ){
83254     sqlcipher3VdbeChangeP5(v, 1);
83255   }
83256
83257 #ifndef SQLCIPHER_OMIT_MERGE_SORT
83258   /* Open the sorter cursor if we are to use one. */
83259   iSorter = pParse->nTab++;
83260   sqlcipher3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83261 #else
83262   iSorter = iTab;
83263 #endif
83264
83265   /* Open the table. Loop through all rows of the table, inserting index
83266   ** records into the sorter. */
83267   sqlcipher3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83268   addr1 = sqlcipher3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83269   regRecord = sqlcipher3GetTempReg(pParse);
83270
83271 #ifndef SQLCIPHER_OMIT_MERGE_SORT
83272   sqlcipher3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83273   sqlcipher3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83274   sqlcipher3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83275   sqlcipher3VdbeJumpHere(v, addr1);
83276   addr1 = sqlcipher3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83277   if( pIndex->onError!=OE_None ){
83278     int j2 = sqlcipher3VdbeCurrentAddr(v) + 3;
83279     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, j2);
83280     addr2 = sqlcipher3VdbeCurrentAddr(v);
83281     sqlcipher3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83282     sqlcipher3HaltConstraint(
83283         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
83284     );
83285   }else{
83286     addr2 = sqlcipher3VdbeCurrentAddr(v);
83287   }
83288   sqlcipher3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83289   sqlcipher3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83290   sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83291 #else
83292   regIdxKey = sqlcipher3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83293   addr2 = addr1 + 1;
83294   if( pIndex->onError!=OE_None ){
83295     const int regRowid = regIdxKey + pIndex->nColumn;
83296     const int j2 = sqlcipher3VdbeCurrentAddr(v) + 2;
83297     void * const pRegKey = SQLCIPHER_INT_TO_PTR(regIdxKey);
83298
83299     /* The registers accessed by the OP_IsUnique opcode were allocated
83300     ** using sqlcipher3GetTempRange() inside of the sqlcipher3GenerateIndexKey()
83301     ** call above. Just before that function was freed they were released
83302     ** (made available to the compiler for reuse) using 
83303     ** sqlcipher3ReleaseTempRange(). So in some ways having the OP_IsUnique
83304     ** opcode use the values stored within seems dangerous. However, since
83305     ** we can be sure that no other temp registers have been allocated
83306     ** since sqlcipher3ReleaseTempRange() was called, it is safe to do so.
83307     */
83308     sqlcipher3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
83309     sqlcipher3HaltConstraint(
83310         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
83311   }
83312   sqlcipher3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
83313   sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83314 #endif
83315   sqlcipher3ReleaseTempReg(pParse, regRecord);
83316   sqlcipher3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83317   sqlcipher3VdbeJumpHere(v, addr1);
83318
83319   sqlcipher3VdbeAddOp1(v, OP_Close, iTab);
83320   sqlcipher3VdbeAddOp1(v, OP_Close, iIdx);
83321   sqlcipher3VdbeAddOp1(v, OP_Close, iSorter);
83322 }
83323
83324 /*
83325 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
83326 ** and pTblList is the name of the table that is to be indexed.  Both will 
83327 ** be NULL for a primary key or an index that is created to satisfy a
83328 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83329 ** as the table to be indexed.  pParse->pNewTable is a table that is
83330 ** currently being constructed by a CREATE TABLE statement.
83331 **
83332 ** pList is a list of columns to be indexed.  pList will be NULL if this
83333 ** is a primary key or unique-constraint on the most recent column added
83334 ** to the table currently under construction.  
83335 **
83336 ** If the index is created successfully, return a pointer to the new Index
83337 ** structure. This is used by sqlcipher3AddPrimaryKey() to mark the index
83338 ** as the tables primary key (Index.autoIndex==2).
83339 */
83340 SQLCIPHER_PRIVATE Index *sqlcipher3CreateIndex(
83341   Parse *pParse,     /* All information about this parse */
83342   Token *pName1,     /* First part of index name. May be NULL */
83343   Token *pName2,     /* Second part of index name. May be NULL */
83344   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83345   ExprList *pList,   /* A list of columns to be indexed */
83346   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83347   Token *pStart,     /* The CREATE token that begins this statement */
83348   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83349   int sortOrder,     /* Sort order of primary key when pList==NULL */
83350   int ifNotExist     /* Omit error if index already exists */
83351 ){
83352   Index *pRet = 0;     /* Pointer to return */
83353   Table *pTab = 0;     /* Table to be indexed */
83354   Index *pIndex = 0;   /* The index to be created */
83355   char *zName = 0;     /* Name of the index */
83356   int nName;           /* Number of characters in zName */
83357   int i, j;
83358   Token nullId;        /* Fake token for an empty ID list */
83359   DbFixer sFix;        /* For assigning database names to pTable */
83360   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83361   sqlcipher3 *db = pParse->db;
83362   Db *pDb;             /* The specific table containing the indexed database */
83363   int iDb;             /* Index of the database that is being written */
83364   Token *pName = 0;    /* Unqualified name of the index to create */
83365   struct ExprList_item *pListItem; /* For looping over pList */
83366   int nCol;
83367   int nExtra = 0;
83368   char *zExtra;
83369
83370   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83371   assert( pParse->nErr==0 );      /* Never called with prior errors */
83372   if( db->mallocFailed || IN_DECLARE_VTAB ){
83373     goto exit_create_index;
83374   }
83375   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
83376     goto exit_create_index;
83377   }
83378
83379   /*
83380   ** Find the table that is to be indexed.  Return early if not found.
83381   */
83382   if( pTblName!=0 ){
83383
83384     /* Use the two-part index name to determine the database 
83385     ** to search for the table. 'Fix' the table name to this db
83386     ** before looking up the table.
83387     */
83388     assert( pName1 && pName2 );
83389     iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
83390     if( iDb<0 ) goto exit_create_index;
83391     assert( pName && pName->z );
83392
83393 #ifndef SQLCIPHER_OMIT_TEMPDB
83394     /* If the index name was unqualified, check if the the table
83395     ** is a temp table. If so, set the database to 1. Do not do this
83396     ** if initialising a database schema.
83397     */
83398     if( !db->init.busy ){
83399       pTab = sqlcipher3SrcListLookup(pParse, pTblName);
83400       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83401         iDb = 1;
83402       }
83403     }
83404 #endif
83405
83406     if( sqlcipher3FixInit(&sFix, pParse, iDb, "index", pName) &&
83407         sqlcipher3FixSrcList(&sFix, pTblName)
83408     ){
83409       /* Because the parser constructs pTblName from a single identifier,
83410       ** sqlcipher3FixSrcList can never fail. */
83411       assert(0);
83412     }
83413     pTab = sqlcipher3LocateTable(pParse, 0, pTblName->a[0].zName, 
83414         pTblName->a[0].zDatabase);
83415     if( !pTab || db->mallocFailed ) goto exit_create_index;
83416     assert( db->aDb[iDb].pSchema==pTab->pSchema );
83417   }else{
83418     assert( pName==0 );
83419     assert( pStart==0 );
83420     pTab = pParse->pNewTable;
83421     if( !pTab ) goto exit_create_index;
83422     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
83423   }
83424   pDb = &db->aDb[iDb];
83425
83426   assert( pTab!=0 );
83427   assert( pParse->nErr==0 );
83428   if( sqlcipher3StrNICmp(pTab->zName, "sqlcipher_", 7)==0 
83429        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
83430     sqlcipher3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83431     goto exit_create_index;
83432   }
83433 #ifndef SQLCIPHER_OMIT_VIEW
83434   if( pTab->pSelect ){
83435     sqlcipher3ErrorMsg(pParse, "views may not be indexed");
83436     goto exit_create_index;
83437   }
83438 #endif
83439 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
83440   if( IsVirtual(pTab) ){
83441     sqlcipher3ErrorMsg(pParse, "virtual tables may not be indexed");
83442     goto exit_create_index;
83443   }
83444 #endif
83445
83446   /*
83447   ** Find the name of the index.  Make sure there is not already another
83448   ** index or table with the same name.  
83449   **
83450   ** Exception:  If we are reading the names of permanent indices from the
83451   ** sqlcipher_master table (because some other process changed the schema) and
83452   ** one of the index names collides with the name of a temporary table or
83453   ** index, then we will continue to process this index.
83454   **
83455   ** If pName==0 it means that we are
83456   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83457   ** own name.
83458   */
83459   if( pName ){
83460     zName = sqlcipher3NameFromToken(db, pName);
83461     if( zName==0 ) goto exit_create_index;
83462     assert( pName->z!=0 );
83463     if( SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){
83464       goto exit_create_index;
83465     }
83466     if( !db->init.busy ){
83467       if( sqlcipher3FindTable(db, zName, 0)!=0 ){
83468         sqlcipher3ErrorMsg(pParse, "there is already a table named %s", zName);
83469         goto exit_create_index;
83470       }
83471     }
83472     if( sqlcipher3FindIndex(db, zName, pDb->zName)!=0 ){
83473       if( !ifNotExist ){
83474         sqlcipher3ErrorMsg(pParse, "index %s already exists", zName);
83475       }else{
83476         assert( !db->init.busy );
83477         sqlcipher3CodeVerifySchema(pParse, iDb);
83478       }
83479       goto exit_create_index;
83480     }
83481   }else{
83482     int n;
83483     Index *pLoop;
83484     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83485     zName = sqlcipher3MPrintf(db, "sqlcipher_autoindex_%s_%d", pTab->zName, n);
83486     if( zName==0 ){
83487       goto exit_create_index;
83488     }
83489   }
83490
83491   /* Check for authorization to create an index.
83492   */
83493 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
83494   {
83495     const char *zDb = pDb->zName;
83496     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83497       goto exit_create_index;
83498     }
83499     i = SQLCIPHER_CREATE_INDEX;
83500     if( !OMIT_TEMPDB && iDb==1 ) i = SQLCIPHER_CREATE_TEMP_INDEX;
83501     if( sqlcipher3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83502       goto exit_create_index;
83503     }
83504   }
83505 #endif
83506
83507   /* If pList==0, it means this routine was called to make a primary
83508   ** key out of the last column added to the table under construction.
83509   ** So create a fake list to simulate this.
83510   */
83511   if( pList==0 ){
83512     nullId.z = pTab->aCol[pTab->nCol-1].zName;
83513     nullId.n = sqlcipher3Strlen30((char*)nullId.z);
83514     pList = sqlcipher3ExprListAppend(pParse, 0, 0);
83515     if( pList==0 ) goto exit_create_index;
83516     sqlcipher3ExprListSetName(pParse, pList, &nullId, 0);
83517     pList->a[0].sortOrder = (u8)sortOrder;
83518   }
83519
83520   /* Figure out how many bytes of space are required to store explicitly
83521   ** specified collation sequence names.
83522   */
83523   for(i=0; i<pList->nExpr; i++){
83524     Expr *pExpr = pList->a[i].pExpr;
83525     if( pExpr ){
83526       CollSeq *pColl = pExpr->pColl;
83527       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
83528       ** failure we have quit before reaching this point. */
83529       if( ALWAYS(pColl) ){
83530         nExtra += (1 + sqlcipher3Strlen30(pColl->zName));
83531       }
83532     }
83533   }
83534
83535   /* 
83536   ** Allocate the index structure. 
83537   */
83538   nName = sqlcipher3Strlen30(zName);
83539   nCol = pList->nExpr;
83540   pIndex = sqlcipher3DbMallocZero(db, 
83541       sizeof(Index) +              /* Index structure  */
83542       sizeof(tRowcnt)*(nCol+1) +   /* Index.aiRowEst   */
83543       sizeof(int)*nCol +           /* Index.aiColumn   */
83544       sizeof(char *)*nCol +        /* Index.azColl     */
83545       sizeof(u8)*nCol +            /* Index.aSortOrder */
83546       nName + 1 +                  /* Index.zName      */
83547       nExtra                       /* Collation sequence names */
83548   );
83549   if( db->mallocFailed ){
83550     goto exit_create_index;
83551   }
83552   pIndex->aiRowEst = (tRowcnt*)(&pIndex[1]);
83553   pIndex->azColl = (char**)(&pIndex->aiRowEst[nCol+1]);
83554   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83555   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83556   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83557   zExtra = (char *)(&pIndex->zName[nName+1]);
83558   memcpy(pIndex->zName, zName, nName+1);
83559   pIndex->pTable = pTab;
83560   pIndex->nColumn = pList->nExpr;
83561   pIndex->onError = (u8)onError;
83562   pIndex->autoIndex = (u8)(pName==0);
83563   pIndex->pSchema = db->aDb[iDb].pSchema;
83564   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
83565
83566   /* Check to see if we should honor DESC requests on index columns
83567   */
83568   if( pDb->pSchema->file_format>=4 ){
83569     sortOrderMask = -1;   /* Honor DESC */
83570   }else{
83571     sortOrderMask = 0;    /* Ignore DESC */
83572   }
83573
83574   /* Scan the names of the columns of the table to be indexed and
83575   ** load the column indices into the Index structure.  Report an error
83576   ** if any column is not found.
83577   **
83578   ** TODO:  Add a test to make sure that the same column is not named
83579   ** more than once within the same index.  Only the first instance of
83580   ** the column will ever be used by the optimizer.  Note that using the
83581   ** same column more than once cannot be an error because that would 
83582   ** break backwards compatibility - it needs to be a warning.
83583   */
83584   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83585     const char *zColName = pListItem->zName;
83586     Column *pTabCol;
83587     int requestedSortOrder;
83588     char *zColl;                   /* Collation sequence name */
83589
83590     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83591       if( sqlcipher3StrICmp(zColName, pTabCol->zName)==0 ) break;
83592     }
83593     if( j>=pTab->nCol ){
83594       sqlcipher3ErrorMsg(pParse, "table %s has no column named %s",
83595         pTab->zName, zColName);
83596       pParse->checkSchema = 1;
83597       goto exit_create_index;
83598     }
83599     pIndex->aiColumn[i] = j;
83600     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
83601     ** the way the "idxlist" non-terminal is constructed by the parser,
83602     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
83603     ** must exist or else there must have been an OOM error.  But if there
83604     ** was an OOM error, we would never reach this point. */
83605     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
83606       int nColl;
83607       zColl = pListItem->pExpr->pColl->zName;
83608       nColl = sqlcipher3Strlen30(zColl) + 1;
83609       assert( nExtra>=nColl );
83610       memcpy(zExtra, zColl, nColl);
83611       zColl = zExtra;
83612       zExtra += nColl;
83613       nExtra -= nColl;
83614     }else{
83615       zColl = pTab->aCol[j].zColl;
83616       if( !zColl ){
83617         zColl = db->pDfltColl->zName;
83618       }
83619     }
83620     if( !db->init.busy && !sqlcipher3LocateCollSeq(pParse, zColl) ){
83621       goto exit_create_index;
83622     }
83623     pIndex->azColl[i] = zColl;
83624     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83625     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83626   }
83627   sqlcipher3DefaultRowEst(pIndex);
83628
83629   if( pTab==pParse->pNewTable ){
83630     /* This routine has been called to create an automatic index as a
83631     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83632     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83633     ** i.e. one of:
83634     **
83635     ** CREATE TABLE t(x PRIMARY KEY, y);
83636     ** CREATE TABLE t(x, y, UNIQUE(x, y));
83637     **
83638     ** Either way, check to see if the table already has such an index. If
83639     ** so, don't bother creating this one. This only applies to
83640     ** automatically created indices. Users can do as they wish with
83641     ** explicit indices.
83642     **
83643     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83644     ** (and thus suppressing the second one) even if they have different
83645     ** sort orders.
83646     **
83647     ** If there are different collating sequences or if the columns of
83648     ** the constraint occur in different orders, then the constraints are
83649     ** considered distinct and both result in separate indices.
83650     */
83651     Index *pIdx;
83652     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83653       int k;
83654       assert( pIdx->onError!=OE_None );
83655       assert( pIdx->autoIndex );
83656       assert( pIndex->onError!=OE_None );
83657
83658       if( pIdx->nColumn!=pIndex->nColumn ) continue;
83659       for(k=0; k<pIdx->nColumn; k++){
83660         const char *z1;
83661         const char *z2;
83662         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83663         z1 = pIdx->azColl[k];
83664         z2 = pIndex->azColl[k];
83665         if( z1!=z2 && sqlcipher3StrICmp(z1, z2) ) break;
83666       }
83667       if( k==pIdx->nColumn ){
83668         if( pIdx->onError!=pIndex->onError ){
83669           /* This constraint creates the same index as a previous
83670           ** constraint specified somewhere in the CREATE TABLE statement.
83671           ** However the ON CONFLICT clauses are different. If both this 
83672           ** constraint and the previous equivalent constraint have explicit
83673           ** ON CONFLICT clauses this is an error. Otherwise, use the
83674           ** explicitly specified behaviour for the index.
83675           */
83676           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
83677             sqlcipher3ErrorMsg(pParse, 
83678                 "conflicting ON CONFLICT clauses specified", 0);
83679           }
83680           if( pIdx->onError==OE_Default ){
83681             pIdx->onError = pIndex->onError;
83682           }
83683         }
83684         goto exit_create_index;
83685       }
83686     }
83687   }
83688
83689   /* Link the new Index structure to its table and to the other
83690   ** in-memory database structures. 
83691   */
83692   if( db->init.busy ){
83693     Index *p;
83694     assert( sqlcipher3SchemaMutexHeld(db, 0, pIndex->pSchema) );
83695     p = sqlcipher3HashInsert(&pIndex->pSchema->idxHash, 
83696                           pIndex->zName, sqlcipher3Strlen30(pIndex->zName),
83697                           pIndex);
83698     if( p ){
83699       assert( p==pIndex );  /* Malloc must have failed */
83700       db->mallocFailed = 1;
83701       goto exit_create_index;
83702     }
83703     db->flags |= SQLCIPHER_InternChanges;
83704     if( pTblName!=0 ){
83705       pIndex->tnum = db->init.newTnum;
83706     }
83707   }
83708
83709   /* If the db->init.busy is 0 then create the index on disk.  This
83710   ** involves writing the index into the master table and filling in the
83711   ** index with the current table contents.
83712   **
83713   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
83714   ** command.  db->init.busy is 1 when a database is opened and 
83715   ** CREATE INDEX statements are read out of the master table.  In
83716   ** the latter case the index already exists on disk, which is why
83717   ** we don't want to recreate it.
83718   **
83719   ** If pTblName==0 it means this index is generated as a primary key
83720   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
83721   ** has just been created, it contains no data and the index initialization
83722   ** step can be skipped.
83723   */
83724   else{ /* if( db->init.busy==0 ) */
83725     Vdbe *v;
83726     char *zStmt;
83727     int iMem = ++pParse->nMem;
83728
83729     v = sqlcipher3GetVdbe(pParse);
83730     if( v==0 ) goto exit_create_index;
83731
83732
83733     /* Create the rootpage for the index
83734     */
83735     sqlcipher3BeginWriteOperation(pParse, 1, iDb);
83736     sqlcipher3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
83737
83738     /* Gather the complete text of the CREATE INDEX statement into
83739     ** the zStmt variable
83740     */
83741     if( pStart ){
83742       assert( pEnd!=0 );
83743       /* A named index with an explicit CREATE INDEX statement */
83744       zStmt = sqlcipher3MPrintf(db, "CREATE%s INDEX %.*s",
83745         onError==OE_None ? "" : " UNIQUE",
83746         (int)(pEnd->z - pName->z) + 1,
83747         pName->z);
83748     }else{
83749       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
83750       /* zStmt = sqlcipher3MPrintf(""); */
83751       zStmt = 0;
83752     }
83753
83754     /* Add an entry in sqlcipher_master for this index
83755     */
83756     sqlcipher3NestedParse(pParse, 
83757         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
83758         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83759         pIndex->zName,
83760         pTab->zName,
83761         iMem,
83762         zStmt
83763     );
83764     sqlcipher3DbFree(db, zStmt);
83765
83766     /* Fill the index with data and reparse the schema. Code an OP_Expire
83767     ** to invalidate all pre-compiled statements.
83768     */
83769     if( pTblName ){
83770       sqlcipher3RefillIndex(pParse, pIndex, iMem);
83771       sqlcipher3ChangeCookie(pParse, iDb);
83772       sqlcipher3VdbeAddParseSchemaOp(v, iDb,
83773          sqlcipher3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
83774       sqlcipher3VdbeAddOp1(v, OP_Expire, 0);
83775     }
83776   }
83777
83778   /* When adding an index to the list of indices for a table, make
83779   ** sure all indices labeled OE_Replace come after all those labeled
83780   ** OE_Ignore.  This is necessary for the correct constraint check
83781   ** processing (in sqlcipher3GenerateConstraintChecks()) as part of
83782   ** UPDATE and INSERT statements.  
83783   */
83784   if( db->init.busy || pTblName==0 ){
83785     if( onError!=OE_Replace || pTab->pIndex==0
83786          || pTab->pIndex->onError==OE_Replace){
83787       pIndex->pNext = pTab->pIndex;
83788       pTab->pIndex = pIndex;
83789     }else{
83790       Index *pOther = pTab->pIndex;
83791       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
83792         pOther = pOther->pNext;
83793       }
83794       pIndex->pNext = pOther->pNext;
83795       pOther->pNext = pIndex;
83796     }
83797     pRet = pIndex;
83798     pIndex = 0;
83799   }
83800
83801   /* Clean up before exiting */
83802 exit_create_index:
83803   if( pIndex ){
83804     sqlcipher3DbFree(db, pIndex->zColAff);
83805     sqlcipher3DbFree(db, pIndex);
83806   }
83807   sqlcipher3ExprListDelete(db, pList);
83808   sqlcipher3SrcListDelete(db, pTblName);
83809   sqlcipher3DbFree(db, zName);
83810   return pRet;
83811 }
83812
83813 /*
83814 ** Fill the Index.aiRowEst[] array with default information - information
83815 ** to be used when we have not run the ANALYZE command.
83816 **
83817 ** aiRowEst[0] is suppose to contain the number of elements in the index.
83818 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
83819 ** number of rows in the table that match any particular value of the
83820 ** first column of the index.  aiRowEst[2] is an estimate of the number
83821 ** of rows that match any particular combiniation of the first 2 columns
83822 ** of the index.  And so forth.  It must always be the case that
83823 *
83824 **           aiRowEst[N]<=aiRowEst[N-1]
83825 **           aiRowEst[N]>=1
83826 **
83827 ** Apart from that, we have little to go on besides intuition as to
83828 ** how aiRowEst[] should be initialized.  The numbers generated here
83829 ** are based on typical values found in actual indices.
83830 */
83831 SQLCIPHER_PRIVATE void sqlcipher3DefaultRowEst(Index *pIdx){
83832   tRowcnt *a = pIdx->aiRowEst;
83833   int i;
83834   tRowcnt n;
83835   assert( a!=0 );
83836   a[0] = pIdx->pTable->nRowEst;
83837   if( a[0]<10 ) a[0] = 10;
83838   n = 10;
83839   for(i=1; i<=pIdx->nColumn; i++){
83840     a[i] = n;
83841     if( n>5 ) n--;
83842   }
83843   if( pIdx->onError!=OE_None ){
83844     a[pIdx->nColumn] = 1;
83845   }
83846 }
83847
83848 /*
83849 ** This routine will drop an existing named index.  This routine
83850 ** implements the DROP INDEX statement.
83851 */
83852 SQLCIPHER_PRIVATE void sqlcipher3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
83853   Index *pIndex;
83854   Vdbe *v;
83855   sqlcipher3 *db = pParse->db;
83856   int iDb;
83857
83858   assert( pParse->nErr==0 );   /* Never called with prior errors */
83859   if( db->mallocFailed ){
83860     goto exit_drop_index;
83861   }
83862   assert( pName->nSrc==1 );
83863   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
83864     goto exit_drop_index;
83865   }
83866   pIndex = sqlcipher3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
83867   if( pIndex==0 ){
83868     if( !ifExists ){
83869       sqlcipher3ErrorMsg(pParse, "no such index: %S", pName, 0);
83870     }else{
83871       sqlcipher3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83872     }
83873     pParse->checkSchema = 1;
83874     goto exit_drop_index;
83875   }
83876   if( pIndex->autoIndex ){
83877     sqlcipher3ErrorMsg(pParse, "index associated with UNIQUE "
83878       "or PRIMARY KEY constraint cannot be dropped", 0);
83879     goto exit_drop_index;
83880   }
83881   iDb = sqlcipher3SchemaToIndex(db, pIndex->pSchema);
83882 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
83883   {
83884     int code = SQLCIPHER_DROP_INDEX;
83885     Table *pTab = pIndex->pTable;
83886     const char *zDb = db->aDb[iDb].zName;
83887     const char *zTab = SCHEMA_TABLE(iDb);
83888     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, zTab, 0, zDb) ){
83889       goto exit_drop_index;
83890     }
83891     if( !OMIT_TEMPDB && iDb ) code = SQLCIPHER_DROP_TEMP_INDEX;
83892     if( sqlcipher3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
83893       goto exit_drop_index;
83894     }
83895   }
83896 #endif
83897
83898   /* Generate code to remove the index and from the master table */
83899   v = sqlcipher3GetVdbe(pParse);
83900   if( v ){
83901     sqlcipher3BeginWriteOperation(pParse, 1, iDb);
83902     sqlcipher3NestedParse(pParse,
83903        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
83904        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
83905     );
83906     sqlcipher3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
83907     sqlcipher3ChangeCookie(pParse, iDb);
83908     destroyRootPage(pParse, pIndex->tnum, iDb);
83909     sqlcipher3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
83910   }
83911
83912 exit_drop_index:
83913   sqlcipher3SrcListDelete(db, pName);
83914 }
83915
83916 /*
83917 ** pArray is a pointer to an array of objects.  Each object in the
83918 ** array is szEntry bytes in size.  This routine allocates a new
83919 ** object on the end of the array.
83920 **
83921 ** *pnEntry is the number of entries already in use.  *pnAlloc is
83922 ** the previously allocated size of the array.  initSize is the
83923 ** suggested initial array size allocation.
83924 **
83925 ** The index of the new entry is returned in *pIdx.
83926 **
83927 ** This routine returns a pointer to the array of objects.  This
83928 ** might be the same as the pArray parameter or it might be a different
83929 ** pointer if the array was resized.
83930 */
83931 SQLCIPHER_PRIVATE void *sqlcipher3ArrayAllocate(
83932   sqlcipher3 *db,      /* Connection to notify of malloc failures */
83933   void *pArray,     /* Array of objects.  Might be reallocated */
83934   int szEntry,      /* Size of each object in the array */
83935   int initSize,     /* Suggested initial allocation, in elements */
83936   int *pnEntry,     /* Number of objects currently in use */
83937   int *pnAlloc,     /* Current size of the allocation, in elements */
83938   int *pIdx         /* Write the index of a new slot here */
83939 ){
83940   char *z;
83941   if( *pnEntry >= *pnAlloc ){
83942     void *pNew;
83943     int newSize;
83944     newSize = (*pnAlloc)*2 + initSize;
83945     pNew = sqlcipher3DbRealloc(db, pArray, newSize*szEntry);
83946     if( pNew==0 ){
83947       *pIdx = -1;
83948       return pArray;
83949     }
83950     *pnAlloc = sqlcipher3DbMallocSize(db, pNew)/szEntry;
83951     pArray = pNew;
83952   }
83953   z = (char*)pArray;
83954   memset(&z[*pnEntry * szEntry], 0, szEntry);
83955   *pIdx = *pnEntry;
83956   ++*pnEntry;
83957   return pArray;
83958 }
83959
83960 /*
83961 ** Append a new element to the given IdList.  Create a new IdList if
83962 ** need be.
83963 **
83964 ** A new IdList is returned, or NULL if malloc() fails.
83965 */
83966 SQLCIPHER_PRIVATE IdList *sqlcipher3IdListAppend(sqlcipher3 *db, IdList *pList, Token *pToken){
83967   int i;
83968   if( pList==0 ){
83969     pList = sqlcipher3DbMallocZero(db, sizeof(IdList) );
83970     if( pList==0 ) return 0;
83971     pList->nAlloc = 0;
83972   }
83973   pList->a = sqlcipher3ArrayAllocate(
83974       db,
83975       pList->a,
83976       sizeof(pList->a[0]),
83977       5,
83978       &pList->nId,
83979       &pList->nAlloc,
83980       &i
83981   );
83982   if( i<0 ){
83983     sqlcipher3IdListDelete(db, pList);
83984     return 0;
83985   }
83986   pList->a[i].zName = sqlcipher3NameFromToken(db, pToken);
83987   return pList;
83988 }
83989
83990 /*
83991 ** Delete an IdList.
83992 */
83993 SQLCIPHER_PRIVATE void sqlcipher3IdListDelete(sqlcipher3 *db, IdList *pList){
83994   int i;
83995   if( pList==0 ) return;
83996   for(i=0; i<pList->nId; i++){
83997     sqlcipher3DbFree(db, pList->a[i].zName);
83998   }
83999   sqlcipher3DbFree(db, pList->a);
84000   sqlcipher3DbFree(db, pList);
84001 }
84002
84003 /*
84004 ** Return the index in pList of the identifier named zId.  Return -1
84005 ** if not found.
84006 */
84007 SQLCIPHER_PRIVATE int sqlcipher3IdListIndex(IdList *pList, const char *zName){
84008   int i;
84009   if( pList==0 ) return -1;
84010   for(i=0; i<pList->nId; i++){
84011     if( sqlcipher3StrICmp(pList->a[i].zName, zName)==0 ) return i;
84012   }
84013   return -1;
84014 }
84015
84016 /*
84017 ** Expand the space allocated for the given SrcList object by
84018 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
84019 ** New slots are zeroed.
84020 **
84021 ** For example, suppose a SrcList initially contains two entries: A,B.
84022 ** To append 3 new entries onto the end, do this:
84023 **
84024 **    sqlcipher3SrcListEnlarge(db, pSrclist, 3, 2);
84025 **
84026 ** After the call above it would contain:  A, B, nil, nil, nil.
84027 ** If the iStart argument had been 1 instead of 2, then the result
84028 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
84029 ** the iStart value would be 0.  The result then would
84030 ** be: nil, nil, nil, A, B.
84031 **
84032 ** If a memory allocation fails the SrcList is unchanged.  The
84033 ** db->mallocFailed flag will be set to true.
84034 */
84035 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListEnlarge(
84036   sqlcipher3 *db,       /* Database connection to notify of OOM errors */
84037   SrcList *pSrc,     /* The SrcList to be enlarged */
84038   int nExtra,        /* Number of new slots to add to pSrc->a[] */
84039   int iStart         /* Index in pSrc->a[] of first new slot */
84040 ){
84041   int i;
84042
84043   /* Sanity checking on calling parameters */
84044   assert( iStart>=0 );
84045   assert( nExtra>=1 );
84046   assert( pSrc!=0 );
84047   assert( iStart<=pSrc->nSrc );
84048
84049   /* Allocate additional space if needed */
84050   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
84051     SrcList *pNew;
84052     int nAlloc = pSrc->nSrc+nExtra;
84053     int nGot;
84054     pNew = sqlcipher3DbRealloc(db, pSrc,
84055                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
84056     if( pNew==0 ){
84057       assert( db->mallocFailed );
84058       return pSrc;
84059     }
84060     pSrc = pNew;
84061     nGot = (sqlcipher3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
84062     pSrc->nAlloc = (u16)nGot;
84063   }
84064
84065   /* Move existing slots that come after the newly inserted slots
84066   ** out of the way */
84067   for(i=pSrc->nSrc-1; i>=iStart; i--){
84068     pSrc->a[i+nExtra] = pSrc->a[i];
84069   }
84070   pSrc->nSrc += (i16)nExtra;
84071
84072   /* Zero the newly allocated slots */
84073   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
84074   for(i=iStart; i<iStart+nExtra; i++){
84075     pSrc->a[i].iCursor = -1;
84076   }
84077
84078   /* Return a pointer to the enlarged SrcList */
84079   return pSrc;
84080 }
84081
84082
84083 /*
84084 ** Append a new table name to the given SrcList.  Create a new SrcList if
84085 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
84086 **
84087 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
84088 ** SrcList might be the same as the SrcList that was input or it might be
84089 ** a new one.  If an OOM error does occurs, then the prior value of pList
84090 ** that is input to this routine is automatically freed.
84091 **
84092 ** If pDatabase is not null, it means that the table has an optional
84093 ** database name prefix.  Like this:  "database.table".  The pDatabase
84094 ** points to the table name and the pTable points to the database name.
84095 ** The SrcList.a[].zName field is filled with the table name which might
84096 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
84097 ** SrcList.a[].zDatabase is filled with the database name from pTable,
84098 ** or with NULL if no database is specified.
84099 **
84100 ** In other words, if call like this:
84101 **
84102 **         sqlcipher3SrcListAppend(D,A,B,0);
84103 **
84104 ** Then B is a table name and the database name is unspecified.  If called
84105 ** like this:
84106 **
84107 **         sqlcipher3SrcListAppend(D,A,B,C);
84108 **
84109 ** Then C is the table name and B is the database name.  If C is defined
84110 ** then so is B.  In other words, we never have a case where:
84111 **
84112 **         sqlcipher3SrcListAppend(D,A,0,C);
84113 **
84114 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84115 ** before being added to the SrcList.
84116 */
84117 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppend(
84118   sqlcipher3 *db,        /* Connection to notify of malloc failures */
84119   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84120   Token *pTable,      /* Table to append */
84121   Token *pDatabase    /* Database of the table */
84122 ){
84123   struct SrcList_item *pItem;
84124   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84125   if( pList==0 ){
84126     pList = sqlcipher3DbMallocZero(db, sizeof(SrcList) );
84127     if( pList==0 ) return 0;
84128     pList->nAlloc = 1;
84129   }
84130   pList = sqlcipher3SrcListEnlarge(db, pList, 1, pList->nSrc);
84131   if( db->mallocFailed ){
84132     sqlcipher3SrcListDelete(db, pList);
84133     return 0;
84134   }
84135   pItem = &pList->a[pList->nSrc-1];
84136   if( pDatabase && pDatabase->z==0 ){
84137     pDatabase = 0;
84138   }
84139   if( pDatabase ){
84140     Token *pTemp = pDatabase;
84141     pDatabase = pTable;
84142     pTable = pTemp;
84143   }
84144   pItem->zName = sqlcipher3NameFromToken(db, pTable);
84145   pItem->zDatabase = sqlcipher3NameFromToken(db, pDatabase);
84146   return pList;
84147 }
84148
84149 /*
84150 ** Assign VdbeCursor index numbers to all tables in a SrcList
84151 */
84152 SQLCIPHER_PRIVATE void sqlcipher3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84153   int i;
84154   struct SrcList_item *pItem;
84155   assert(pList || pParse->db->mallocFailed );
84156   if( pList ){
84157     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84158       if( pItem->iCursor>=0 ) break;
84159       pItem->iCursor = pParse->nTab++;
84160       if( pItem->pSelect ){
84161         sqlcipher3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84162       }
84163     }
84164   }
84165 }
84166
84167 /*
84168 ** Delete an entire SrcList including all its substructure.
84169 */
84170 SQLCIPHER_PRIVATE void sqlcipher3SrcListDelete(sqlcipher3 *db, SrcList *pList){
84171   int i;
84172   struct SrcList_item *pItem;
84173   if( pList==0 ) return;
84174   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84175     sqlcipher3DbFree(db, pItem->zDatabase);
84176     sqlcipher3DbFree(db, pItem->zName);
84177     sqlcipher3DbFree(db, pItem->zAlias);
84178     sqlcipher3DbFree(db, pItem->zIndex);
84179     sqlcipher3DeleteTable(db, pItem->pTab);
84180     sqlcipher3SelectDelete(db, pItem->pSelect);
84181     sqlcipher3ExprDelete(db, pItem->pOn);
84182     sqlcipher3IdListDelete(db, pItem->pUsing);
84183   }
84184   sqlcipher3DbFree(db, pList);
84185 }
84186
84187 /*
84188 ** This routine is called by the parser to add a new term to the
84189 ** end of a growing FROM clause.  The "p" parameter is the part of
84190 ** the FROM clause that has already been constructed.  "p" is NULL
84191 ** if this is the first term of the FROM clause.  pTable and pDatabase
84192 ** are the name of the table and database named in the FROM clause term.
84193 ** pDatabase is NULL if the database name qualifier is missing - the
84194 ** usual case.  If the term has a alias, then pAlias points to the
84195 ** alias token.  If the term is a subquery, then pSubquery is the
84196 ** SELECT statement that the subquery encodes.  The pTable and
84197 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84198 ** parameters are the content of the ON and USING clauses.
84199 **
84200 ** Return a new SrcList which encodes is the FROM with the new
84201 ** term added.
84202 */
84203 SQLCIPHER_PRIVATE SrcList *sqlcipher3SrcListAppendFromTerm(
84204   Parse *pParse,          /* Parsing context */
84205   SrcList *p,             /* The left part of the FROM clause already seen */
84206   Token *pTable,          /* Name of the table to add to the FROM clause */
84207   Token *pDatabase,       /* Name of the database containing pTable */
84208   Token *pAlias,          /* The right-hand side of the AS subexpression */
84209   Select *pSubquery,      /* A subquery used in place of a table name */
84210   Expr *pOn,              /* The ON clause of a join */
84211   IdList *pUsing          /* The USING clause of a join */
84212 ){
84213   struct SrcList_item *pItem;
84214   sqlcipher3 *db = pParse->db;
84215   if( !p && (pOn || pUsing) ){
84216     sqlcipher3ErrorMsg(pParse, "a JOIN clause is required before %s", 
84217       (pOn ? "ON" : "USING")
84218     );
84219     goto append_from_error;
84220   }
84221   p = sqlcipher3SrcListAppend(db, p, pTable, pDatabase);
84222   if( p==0 || NEVER(p->nSrc==0) ){
84223     goto append_from_error;
84224   }
84225   pItem = &p->a[p->nSrc-1];
84226   assert( pAlias!=0 );
84227   if( pAlias->n ){
84228     pItem->zAlias = sqlcipher3NameFromToken(db, pAlias);
84229   }
84230   pItem->pSelect = pSubquery;
84231   pItem->pOn = pOn;
84232   pItem->pUsing = pUsing;
84233   return p;
84234
84235  append_from_error:
84236   assert( p==0 );
84237   sqlcipher3ExprDelete(db, pOn);
84238   sqlcipher3IdListDelete(db, pUsing);
84239   sqlcipher3SelectDelete(db, pSubquery);
84240   return 0;
84241 }
84242
84243 /*
84244 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
84245 ** element of the source-list passed as the second argument.
84246 */
84247 SQLCIPHER_PRIVATE void sqlcipher3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84248   assert( pIndexedBy!=0 );
84249   if( p && ALWAYS(p->nSrc>0) ){
84250     struct SrcList_item *pItem = &p->a[p->nSrc-1];
84251     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84252     if( pIndexedBy->n==1 && !pIndexedBy->z ){
84253       /* A "NOT INDEXED" clause was supplied. See parse.y 
84254       ** construct "indexed_opt" for details. */
84255       pItem->notIndexed = 1;
84256     }else{
84257       pItem->zIndex = sqlcipher3NameFromToken(pParse->db, pIndexedBy);
84258     }
84259   }
84260 }
84261
84262 /*
84263 ** When building up a FROM clause in the parser, the join operator
84264 ** is initially attached to the left operand.  But the code generator
84265 ** expects the join operator to be on the right operand.  This routine
84266 ** Shifts all join operators from left to right for an entire FROM
84267 ** clause.
84268 **
84269 ** Example: Suppose the join is like this:
84270 **
84271 **           A natural cross join B
84272 **
84273 ** The operator is "natural cross join".  The A and B operands are stored
84274 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84275 ** operator with A.  This routine shifts that operator over to B.
84276 */
84277 SQLCIPHER_PRIVATE void sqlcipher3SrcListShiftJoinType(SrcList *p){
84278   if( p ){
84279     int i;
84280     assert( p->a || p->nSrc==0 );
84281     for(i=p->nSrc-1; i>0; i--){
84282       p->a[i].jointype = p->a[i-1].jointype;
84283     }
84284     p->a[0].jointype = 0;
84285   }
84286 }
84287
84288 /*
84289 ** Begin a transaction
84290 */
84291 SQLCIPHER_PRIVATE void sqlcipher3BeginTransaction(Parse *pParse, int type){
84292   sqlcipher3 *db;
84293   Vdbe *v;
84294   int i;
84295
84296   assert( pParse!=0 );
84297   db = pParse->db;
84298   assert( db!=0 );
84299 /*  if( db->aDb[0].pBt==0 ) return; */
84300   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_TRANSACTION, "BEGIN", 0, 0) ){
84301     return;
84302   }
84303   v = sqlcipher3GetVdbe(pParse);
84304   if( !v ) return;
84305   if( type!=TK_DEFERRED ){
84306     for(i=0; i<db->nDb; i++){
84307       sqlcipher3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84308       sqlcipher3VdbeUsesBtree(v, i);
84309     }
84310   }
84311   sqlcipher3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84312 }
84313
84314 /*
84315 ** Commit a transaction
84316 */
84317 SQLCIPHER_PRIVATE void sqlcipher3CommitTransaction(Parse *pParse){
84318   Vdbe *v;
84319
84320   assert( pParse!=0 );
84321   assert( pParse->db!=0 );
84322   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_TRANSACTION, "COMMIT", 0, 0) ){
84323     return;
84324   }
84325   v = sqlcipher3GetVdbe(pParse);
84326   if( v ){
84327     sqlcipher3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84328   }
84329 }
84330
84331 /*
84332 ** Rollback a transaction
84333 */
84334 SQLCIPHER_PRIVATE void sqlcipher3RollbackTransaction(Parse *pParse){
84335   Vdbe *v;
84336
84337   assert( pParse!=0 );
84338   assert( pParse->db!=0 );
84339   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_TRANSACTION, "ROLLBACK", 0, 0) ){
84340     return;
84341   }
84342   v = sqlcipher3GetVdbe(pParse);
84343   if( v ){
84344     sqlcipher3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84345   }
84346 }
84347
84348 /*
84349 ** This function is called by the parser when it parses a command to create,
84350 ** release or rollback an SQL savepoint. 
84351 */
84352 SQLCIPHER_PRIVATE void sqlcipher3Savepoint(Parse *pParse, int op, Token *pName){
84353   char *zName = sqlcipher3NameFromToken(pParse->db, pName);
84354   if( zName ){
84355     Vdbe *v = sqlcipher3GetVdbe(pParse);
84356 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
84357     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84358     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84359 #endif
84360     if( !v || sqlcipher3AuthCheck(pParse, SQLCIPHER_SAVEPOINT, az[op], zName, 0) ){
84361       sqlcipher3DbFree(pParse->db, zName);
84362       return;
84363     }
84364     sqlcipher3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84365   }
84366 }
84367
84368 /*
84369 ** Make sure the TEMP database is open and available for use.  Return
84370 ** the number of errors.  Leave any error messages in the pParse structure.
84371 */
84372 SQLCIPHER_PRIVATE int sqlcipher3OpenTempDatabase(Parse *pParse){
84373   sqlcipher3 *db = pParse->db;
84374   if( db->aDb[1].pBt==0 && !pParse->explain ){
84375     int rc;
84376     Btree *pBt;
84377     static const int flags = 
84378           SQLCIPHER_OPEN_READWRITE |
84379           SQLCIPHER_OPEN_CREATE |
84380           SQLCIPHER_OPEN_EXCLUSIVE |
84381           SQLCIPHER_OPEN_DELETEONCLOSE |
84382           SQLCIPHER_OPEN_TEMP_DB;
84383
84384     rc = sqlcipher3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84385     if( rc!=SQLCIPHER_OK ){
84386       sqlcipher3ErrorMsg(pParse, "unable to open a temporary database "
84387         "file for storing temporary tables");
84388       pParse->rc = rc;
84389       return 1;
84390     }
84391     db->aDb[1].pBt = pBt;
84392     assert( db->aDb[1].pSchema );
84393     if( SQLCIPHER_NOMEM==sqlcipher3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84394       db->mallocFailed = 1;
84395       return 1;
84396     }
84397   }
84398   return 0;
84399 }
84400
84401 /*
84402 ** Generate VDBE code that will verify the schema cookie and start
84403 ** a read-transaction for all named database files.
84404 **
84405 ** It is important that all schema cookies be verified and all
84406 ** read transactions be started before anything else happens in
84407 ** the VDBE program.  But this routine can be called after much other
84408 ** code has been generated.  So here is what we do:
84409 **
84410 ** The first time this routine is called, we code an OP_Goto that
84411 ** will jump to a subroutine at the end of the program.  Then we
84412 ** record every database that needs its schema verified in the
84413 ** pParse->cookieMask field.  Later, after all other code has been
84414 ** generated, the subroutine that does the cookie verifications and
84415 ** starts the transactions will be coded and the OP_Goto P2 value
84416 ** will be made to point to that subroutine.  The generation of the
84417 ** cookie verification subroutine code happens in sqlcipher3FinishCoding().
84418 **
84419 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84420 ** schema on any databases.  This can be used to position the OP_Goto
84421 ** early in the code, before we know if any database tables will be used.
84422 */
84423 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifySchema(Parse *pParse, int iDb){
84424   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84425
84426   if( pToplevel->cookieGoto==0 ){
84427     Vdbe *v = sqlcipher3GetVdbe(pToplevel);
84428     if( v==0 ) return;  /* This only happens if there was a prior error */
84429     pToplevel->cookieGoto = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84430   }
84431   if( iDb>=0 ){
84432     sqlcipher3 *db = pToplevel->db;
84433     yDbMask mask;
84434
84435     assert( iDb<db->nDb );
84436     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84437     assert( iDb<SQLCIPHER_MAX_ATTACHED+2 );
84438     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
84439     mask = ((yDbMask)1)<<iDb;
84440     if( (pToplevel->cookieMask & mask)==0 ){
84441       pToplevel->cookieMask |= mask;
84442       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84443       if( !OMIT_TEMPDB && iDb==1 ){
84444         sqlcipher3OpenTempDatabase(pToplevel);
84445       }
84446     }
84447   }
84448 }
84449
84450 /*
84451 ** If argument zDb is NULL, then call sqlcipher3CodeVerifySchema() for each 
84452 ** attached database. Otherwise, invoke it for the database named zDb only.
84453 */
84454 SQLCIPHER_PRIVATE void sqlcipher3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84455   sqlcipher3 *db = pParse->db;
84456   int i;
84457   for(i=0; i<db->nDb; i++){
84458     Db *pDb = &db->aDb[i];
84459     if( pDb->pBt && (!zDb || 0==sqlcipher3StrICmp(zDb, pDb->zName)) ){
84460       sqlcipher3CodeVerifySchema(pParse, i);
84461     }
84462   }
84463 }
84464
84465 /*
84466 ** Generate VDBE code that prepares for doing an operation that
84467 ** might change the database.
84468 **
84469 ** This routine starts a new transaction if we are not already within
84470 ** a transaction.  If we are already within a transaction, then a checkpoint
84471 ** is set if the setStatement parameter is true.  A checkpoint should
84472 ** be set for operations that might fail (due to a constraint) part of
84473 ** the way through and which will need to undo some writes without having to
84474 ** rollback the whole transaction.  For operations where all constraints
84475 ** can be checked before any changes are made to the database, it is never
84476 ** necessary to undo a write and the checkpoint should not be set.
84477 */
84478 SQLCIPHER_PRIVATE void sqlcipher3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84479   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84480   sqlcipher3CodeVerifySchema(pParse, iDb);
84481   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84482   pToplevel->isMultiWrite |= setStatement;
84483 }
84484
84485 /*
84486 ** Indicate that the statement currently under construction might write
84487 ** more than one entry (example: deleting one row then inserting another,
84488 ** inserting multiple rows in a table, or inserting a row and index entries.)
84489 ** If an abort occurs after some of these writes have completed, then it will
84490 ** be necessary to undo the completed writes.
84491 */
84492 SQLCIPHER_PRIVATE void sqlcipher3MultiWrite(Parse *pParse){
84493   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84494   pToplevel->isMultiWrite = 1;
84495 }
84496
84497 /* 
84498 ** The code generator calls this routine if is discovers that it is
84499 ** possible to abort a statement prior to completion.  In order to 
84500 ** perform this abort without corrupting the database, we need to make
84501 ** sure that the statement is protected by a statement transaction.
84502 **
84503 ** Technically, we only need to set the mayAbort flag if the
84504 ** isMultiWrite flag was previously set.  There is a time dependency
84505 ** such that the abort must occur after the multiwrite.  This makes
84506 ** some statements involving the REPLACE conflict resolution algorithm
84507 ** go a little faster.  But taking advantage of this time dependency
84508 ** makes it more difficult to prove that the code is correct (in 
84509 ** particular, it prevents us from writing an effective
84510 ** implementation of sqlcipher3AssertMayAbort()) and so we have chosen
84511 ** to take the safe route and skip the optimization.
84512 */
84513 SQLCIPHER_PRIVATE void sqlcipher3MayAbort(Parse *pParse){
84514   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
84515   pToplevel->mayAbort = 1;
84516 }
84517
84518 /*
84519 ** Code an OP_Halt that causes the vdbe to return an SQLCIPHER_CONSTRAINT
84520 ** error. The onError parameter determines which (if any) of the statement
84521 ** and/or current transaction is rolled back.
84522 */
84523 SQLCIPHER_PRIVATE void sqlcipher3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
84524   Vdbe *v = sqlcipher3GetVdbe(pParse);
84525   if( onError==OE_Abort ){
84526     sqlcipher3MayAbort(pParse);
84527   }
84528   sqlcipher3VdbeAddOp4(v, OP_Halt, SQLCIPHER_CONSTRAINT, onError, 0, p4, p4type);
84529 }
84530
84531 /*
84532 ** Check to see if pIndex uses the collating sequence pColl.  Return
84533 ** true if it does and false if it does not.
84534 */
84535 #ifndef SQLCIPHER_OMIT_REINDEX
84536 static int collationMatch(const char *zColl, Index *pIndex){
84537   int i;
84538   assert( zColl!=0 );
84539   for(i=0; i<pIndex->nColumn; i++){
84540     const char *z = pIndex->azColl[i];
84541     assert( z!=0 );
84542     if( 0==sqlcipher3StrICmp(z, zColl) ){
84543       return 1;
84544     }
84545   }
84546   return 0;
84547 }
84548 #endif
84549
84550 /*
84551 ** Recompute all indices of pTab that use the collating sequence pColl.
84552 ** If pColl==0 then recompute all indices of pTab.
84553 */
84554 #ifndef SQLCIPHER_OMIT_REINDEX
84555 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84556   Index *pIndex;              /* An index associated with pTab */
84557
84558   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84559     if( zColl==0 || collationMatch(zColl, pIndex) ){
84560       int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
84561       sqlcipher3BeginWriteOperation(pParse, 0, iDb);
84562       sqlcipher3RefillIndex(pParse, pIndex, -1);
84563     }
84564   }
84565 }
84566 #endif
84567
84568 /*
84569 ** Recompute all indices of all tables in all databases where the
84570 ** indices use the collating sequence pColl.  If pColl==0 then recompute
84571 ** all indices everywhere.
84572 */
84573 #ifndef SQLCIPHER_OMIT_REINDEX
84574 static void reindexDatabases(Parse *pParse, char const *zColl){
84575   Db *pDb;                    /* A single database */
84576   int iDb;                    /* The database index number */
84577   sqlcipher3 *db = pParse->db;   /* The database connection */
84578   HashElem *k;                /* For looping over tables in pDb */
84579   Table *pTab;                /* A table in the database */
84580
84581   assert( sqlcipher3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84582   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84583     assert( pDb!=0 );
84584     for(k=sqlcipherHashFirst(&pDb->pSchema->tblHash);  k; k=sqlcipherHashNext(k)){
84585       pTab = (Table*)sqlcipherHashData(k);
84586       reindexTable(pParse, pTab, zColl);
84587     }
84588   }
84589 }
84590 #endif
84591
84592 /*
84593 ** Generate code for the REINDEX command.
84594 **
84595 **        REINDEX                            -- 1
84596 **        REINDEX  <collation>               -- 2
84597 **        REINDEX  ?<database>.?<tablename>  -- 3
84598 **        REINDEX  ?<database>.?<indexname>  -- 4
84599 **
84600 ** Form 1 causes all indices in all attached databases to be rebuilt.
84601 ** Form 2 rebuilds all indices in all databases that use the named
84602 ** collating function.  Forms 3 and 4 rebuild the named index or all
84603 ** indices associated with the named table.
84604 */
84605 #ifndef SQLCIPHER_OMIT_REINDEX
84606 SQLCIPHER_PRIVATE void sqlcipher3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84607   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84608   char *z;                    /* Name of a table or index */
84609   const char *zDb;            /* Name of the database */
84610   Table *pTab;                /* A table in the database */
84611   Index *pIndex;              /* An index associated with pTab */
84612   int iDb;                    /* The database index number */
84613   sqlcipher3 *db = pParse->db;   /* The database connection */
84614   Token *pObjName;            /* Name of the table or index to be reindexed */
84615
84616   /* Read the database schema. If an error occurs, leave an error message
84617   ** and code in pParse and return NULL. */
84618   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
84619     return;
84620   }
84621
84622   if( pName1==0 ){
84623     reindexDatabases(pParse, 0);
84624     return;
84625   }else if( NEVER(pName2==0) || pName2->z==0 ){
84626     char *zColl;
84627     assert( pName1->z );
84628     zColl = sqlcipher3NameFromToken(pParse->db, pName1);
84629     if( !zColl ) return;
84630     pColl = sqlcipher3FindCollSeq(db, ENC(db), zColl, 0);
84631     if( pColl ){
84632       reindexDatabases(pParse, zColl);
84633       sqlcipher3DbFree(db, zColl);
84634       return;
84635     }
84636     sqlcipher3DbFree(db, zColl);
84637   }
84638   iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pObjName);
84639   if( iDb<0 ) return;
84640   z = sqlcipher3NameFromToken(db, pObjName);
84641   if( z==0 ) return;
84642   zDb = db->aDb[iDb].zName;
84643   pTab = sqlcipher3FindTable(db, z, zDb);
84644   if( pTab ){
84645     reindexTable(pParse, pTab, 0);
84646     sqlcipher3DbFree(db, z);
84647     return;
84648   }
84649   pIndex = sqlcipher3FindIndex(db, z, zDb);
84650   sqlcipher3DbFree(db, z);
84651   if( pIndex ){
84652     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
84653     sqlcipher3RefillIndex(pParse, pIndex, -1);
84654     return;
84655   }
84656   sqlcipher3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84657 }
84658 #endif
84659
84660 /*
84661 ** Return a dynamicly allocated KeyInfo structure that can be used
84662 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84663 **
84664 ** If successful, a pointer to the new structure is returned. In this case
84665 ** the caller is responsible for calling sqlcipher3DbFree(db, ) on the returned 
84666 ** pointer. If an error occurs (out of memory or missing collation 
84667 ** sequence), NULL is returned and the state of pParse updated to reflect
84668 ** the error.
84669 */
84670 SQLCIPHER_PRIVATE KeyInfo *sqlcipher3IndexKeyinfo(Parse *pParse, Index *pIdx){
84671   int i;
84672   int nCol = pIdx->nColumn;
84673   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
84674   sqlcipher3 *db = pParse->db;
84675   KeyInfo *pKey = (KeyInfo *)sqlcipher3DbMallocZero(db, nBytes);
84676
84677   if( pKey ){
84678     pKey->db = pParse->db;
84679     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
84680     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
84681     for(i=0; i<nCol; i++){
84682       char *zColl = pIdx->azColl[i];
84683       assert( zColl );
84684       pKey->aColl[i] = sqlcipher3LocateCollSeq(pParse, zColl);
84685       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
84686     }
84687     pKey->nField = (u16)nCol;
84688   }
84689
84690   if( pParse->nErr ){
84691     sqlcipher3DbFree(db, pKey);
84692     pKey = 0;
84693   }
84694   return pKey;
84695 }
84696
84697 /************** End of build.c ***********************************************/
84698 /************** Begin file callback.c ****************************************/
84699 /*
84700 ** 2005 May 23 
84701 **
84702 ** The author disclaims copyright to this source code.  In place of
84703 ** a legal notice, here is a blessing:
84704 **
84705 **    May you do good and not evil.
84706 **    May you find forgiveness for yourself and forgive others.
84707 **    May you share freely, never taking more than you give.
84708 **
84709 *************************************************************************
84710 **
84711 ** This file contains functions used to access the internal hash tables
84712 ** of user defined functions and collation sequences.
84713 */
84714
84715
84716 /*
84717 ** Invoke the 'collation needed' callback to request a collation sequence
84718 ** in the encoding enc of name zName, length nName.
84719 */
84720 static void callCollNeeded(sqlcipher3 *db, int enc, const char *zName){
84721   assert( !db->xCollNeeded || !db->xCollNeeded16 );
84722   if( db->xCollNeeded ){
84723     char *zExternal = sqlcipher3DbStrDup(db, zName);
84724     if( !zExternal ) return;
84725     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
84726     sqlcipher3DbFree(db, zExternal);
84727   }
84728 #ifndef SQLCIPHER_OMIT_UTF16
84729   if( db->xCollNeeded16 ){
84730     char const *zExternal;
84731     sqlcipher3_value *pTmp = sqlcipher3ValueNew(db);
84732     sqlcipher3ValueSetStr(pTmp, -1, zName, SQLCIPHER_UTF8, SQLCIPHER_STATIC);
84733     zExternal = sqlcipher3ValueText(pTmp, SQLCIPHER_UTF16NATIVE);
84734     if( zExternal ){
84735       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
84736     }
84737     sqlcipher3ValueFree(pTmp);
84738   }
84739 #endif
84740 }
84741
84742 /*
84743 ** This routine is called if the collation factory fails to deliver a
84744 ** collation function in the best encoding but there may be other versions
84745 ** of this collation function (for other text encodings) available. Use one
84746 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
84747 ** possible.
84748 */
84749 static int synthCollSeq(sqlcipher3 *db, CollSeq *pColl){
84750   CollSeq *pColl2;
84751   char *z = pColl->zName;
84752   int i;
84753   static const u8 aEnc[] = { SQLCIPHER_UTF16BE, SQLCIPHER_UTF16LE, SQLCIPHER_UTF8 };
84754   for(i=0; i<3; i++){
84755     pColl2 = sqlcipher3FindCollSeq(db, aEnc[i], z, 0);
84756     if( pColl2->xCmp!=0 ){
84757       memcpy(pColl, pColl2, sizeof(CollSeq));
84758       pColl->xDel = 0;         /* Do not copy the destructor */
84759       return SQLCIPHER_OK;
84760     }
84761   }
84762   return SQLCIPHER_ERROR;
84763 }
84764
84765 /*
84766 ** This function is responsible for invoking the collation factory callback
84767 ** or substituting a collation sequence of a different encoding when the
84768 ** requested collation sequence is not available in the desired encoding.
84769 ** 
84770 ** If it is not NULL, then pColl must point to the database native encoding 
84771 ** collation sequence with name zName, length nName.
84772 **
84773 ** The return value is either the collation sequence to be used in database
84774 ** db for collation type name zName, length nName, or NULL, if no collation
84775 ** sequence can be found.
84776 **
84777 ** See also: sqlcipher3LocateCollSeq(), sqlcipher3FindCollSeq()
84778 */
84779 SQLCIPHER_PRIVATE CollSeq *sqlcipher3GetCollSeq(
84780   sqlcipher3* db,          /* The database connection */
84781   u8 enc,               /* The desired encoding for the collating sequence */
84782   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
84783   const char *zName     /* Collating sequence name */
84784 ){
84785   CollSeq *p;
84786
84787   p = pColl;
84788   if( !p ){
84789     p = sqlcipher3FindCollSeq(db, enc, zName, 0);
84790   }
84791   if( !p || !p->xCmp ){
84792     /* No collation sequence of this type for this encoding is registered.
84793     ** Call the collation factory to see if it can supply us with one.
84794     */
84795     callCollNeeded(db, enc, zName);
84796     p = sqlcipher3FindCollSeq(db, enc, zName, 0);
84797   }
84798   if( p && !p->xCmp && synthCollSeq(db, p) ){
84799     p = 0;
84800   }
84801   assert( !p || p->xCmp );
84802   return p;
84803 }
84804
84805 /*
84806 ** This routine is called on a collation sequence before it is used to
84807 ** check that it is defined. An undefined collation sequence exists when
84808 ** a database is loaded that contains references to collation sequences
84809 ** that have not been defined by sqlcipher3_create_collation() etc.
84810 **
84811 ** If required, this routine calls the 'collation needed' callback to
84812 ** request a definition of the collating sequence. If this doesn't work, 
84813 ** an equivalent collating sequence that uses a text encoding different
84814 ** from the main database is substituted, if one is available.
84815 */
84816 SQLCIPHER_PRIVATE int sqlcipher3CheckCollSeq(Parse *pParse, CollSeq *pColl){
84817   if( pColl ){
84818     const char *zName = pColl->zName;
84819     sqlcipher3 *db = pParse->db;
84820     CollSeq *p = sqlcipher3GetCollSeq(db, ENC(db), pColl, zName);
84821     if( !p ){
84822       sqlcipher3ErrorMsg(pParse, "no such collation sequence: %s", zName);
84823       pParse->nErr++;
84824       return SQLCIPHER_ERROR;
84825     }
84826     assert( p==pColl );
84827   }
84828   return SQLCIPHER_OK;
84829 }
84830
84831
84832
84833 /*
84834 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
84835 ** specified by zName and nName is not found and parameter 'create' is
84836 ** true, then create a new entry. Otherwise return NULL.
84837 **
84838 ** Each pointer stored in the sqlcipher3.aCollSeq hash table contains an
84839 ** array of three CollSeq structures. The first is the collation sequence
84840 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
84841 **
84842 ** Stored immediately after the three collation sequences is a copy of
84843 ** the collation sequence name. A pointer to this string is stored in
84844 ** each collation sequence structure.
84845 */
84846 static CollSeq *findCollSeqEntry(
84847   sqlcipher3 *db,          /* Database connection */
84848   const char *zName,    /* Name of the collating sequence */
84849   int create            /* Create a new entry if true */
84850 ){
84851   CollSeq *pColl;
84852   int nName = sqlcipher3Strlen30(zName);
84853   pColl = sqlcipher3HashFind(&db->aCollSeq, zName, nName);
84854
84855   if( 0==pColl && create ){
84856     pColl = sqlcipher3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
84857     if( pColl ){
84858       CollSeq *pDel = 0;
84859       pColl[0].zName = (char*)&pColl[3];
84860       pColl[0].enc = SQLCIPHER_UTF8;
84861       pColl[1].zName = (char*)&pColl[3];
84862       pColl[1].enc = SQLCIPHER_UTF16LE;
84863       pColl[2].zName = (char*)&pColl[3];
84864       pColl[2].enc = SQLCIPHER_UTF16BE;
84865       memcpy(pColl[0].zName, zName, nName);
84866       pColl[0].zName[nName] = 0;
84867       pDel = sqlcipher3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
84868
84869       /* If a malloc() failure occurred in sqlcipher3HashInsert(), it will 
84870       ** return the pColl pointer to be deleted (because it wasn't added
84871       ** to the hash table).
84872       */
84873       assert( pDel==0 || pDel==pColl );
84874       if( pDel!=0 ){
84875         db->mallocFailed = 1;
84876         sqlcipher3DbFree(db, pDel);
84877         pColl = 0;
84878       }
84879     }
84880   }
84881   return pColl;
84882 }
84883
84884 /*
84885 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
84886 ** Return the CollSeq* pointer for the collation sequence named zName
84887 ** for the encoding 'enc' from the database 'db'.
84888 **
84889 ** If the entry specified is not found and 'create' is true, then create a
84890 ** new entry.  Otherwise return NULL.
84891 **
84892 ** A separate function sqlcipher3LocateCollSeq() is a wrapper around
84893 ** this routine.  sqlcipher3LocateCollSeq() invokes the collation factory
84894 ** if necessary and generates an error message if the collating sequence
84895 ** cannot be found.
84896 **
84897 ** See also: sqlcipher3LocateCollSeq(), sqlcipher3GetCollSeq()
84898 */
84899 SQLCIPHER_PRIVATE CollSeq *sqlcipher3FindCollSeq(
84900   sqlcipher3 *db,
84901   u8 enc,
84902   const char *zName,
84903   int create
84904 ){
84905   CollSeq *pColl;
84906   if( zName ){
84907     pColl = findCollSeqEntry(db, zName, create);
84908   }else{
84909     pColl = db->pDfltColl;
84910   }
84911   assert( SQLCIPHER_UTF8==1 && SQLCIPHER_UTF16LE==2 && SQLCIPHER_UTF16BE==3 );
84912   assert( enc>=SQLCIPHER_UTF8 && enc<=SQLCIPHER_UTF16BE );
84913   if( pColl ) pColl += enc-1;
84914   return pColl;
84915 }
84916
84917 /* During the search for the best function definition, this procedure
84918 ** is called to test how well the function passed as the first argument
84919 ** matches the request for a function with nArg arguments in a system
84920 ** that uses encoding enc. The value returned indicates how well the
84921 ** request is matched. A higher value indicates a better match.
84922 **
84923 ** The returned value is always between 0 and 6, as follows:
84924 **
84925 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
84926 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
84927 **    encoding is requested, or vice versa.
84928 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
84929 **    requested, or vice versa.
84930 ** 3: A variable arguments function using the same text encoding.
84931 ** 4: A function with the exact number of arguments requested that
84932 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
84933 ** 5: A function with the exact number of arguments requested that
84934 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
84935 ** 6: An exact match.
84936 **
84937 */
84938 static int matchQuality(FuncDef *p, int nArg, u8 enc){
84939   int match = 0;
84940   if( p->nArg==-1 || p->nArg==nArg 
84941    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
84942   ){
84943     match = 1;
84944     if( p->nArg==nArg || nArg==-1 ){
84945       match = 4;
84946     }
84947     if( enc==p->iPrefEnc ){
84948       match += 2;
84949     }
84950     else if( (enc==SQLCIPHER_UTF16LE && p->iPrefEnc==SQLCIPHER_UTF16BE) ||
84951              (enc==SQLCIPHER_UTF16BE && p->iPrefEnc==SQLCIPHER_UTF16LE) ){
84952       match += 1;
84953     }
84954   }
84955   return match;
84956 }
84957
84958 /*
84959 ** Search a FuncDefHash for a function with the given name.  Return
84960 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
84961 */
84962 static FuncDef *functionSearch(
84963   FuncDefHash *pHash,  /* Hash table to search */
84964   int h,               /* Hash of the name */
84965   const char *zFunc,   /* Name of function */
84966   int nFunc            /* Number of bytes in zFunc */
84967 ){
84968   FuncDef *p;
84969   for(p=pHash->a[h]; p; p=p->pHash){
84970     if( sqlcipher3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
84971       return p;
84972     }
84973   }
84974   return 0;
84975 }
84976
84977 /*
84978 ** Insert a new FuncDef into a FuncDefHash hash table.
84979 */
84980 SQLCIPHER_PRIVATE void sqlcipher3FuncDefInsert(
84981   FuncDefHash *pHash,  /* The hash table into which to insert */
84982   FuncDef *pDef        /* The function definition to insert */
84983 ){
84984   FuncDef *pOther;
84985   int nName = sqlcipher3Strlen30(pDef->zName);
84986   u8 c1 = (u8)pDef->zName[0];
84987   int h = (sqlcipher3UpperToLower[c1] + nName) % ArraySize(pHash->a);
84988   pOther = functionSearch(pHash, h, pDef->zName, nName);
84989   if( pOther ){
84990     assert( pOther!=pDef && pOther->pNext!=pDef );
84991     pDef->pNext = pOther->pNext;
84992     pOther->pNext = pDef;
84993   }else{
84994     pDef->pNext = 0;
84995     pDef->pHash = pHash->a[h];
84996     pHash->a[h] = pDef;
84997   }
84998 }
84999   
85000   
85001
85002 /*
85003 ** Locate a user function given a name, a number of arguments and a flag
85004 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
85005 ** pointer to the FuncDef structure that defines that function, or return
85006 ** NULL if the function does not exist.
85007 **
85008 ** If the createFlag argument is true, then a new (blank) FuncDef
85009 ** structure is created and liked into the "db" structure if a
85010 ** no matching function previously existed.  When createFlag is true
85011 ** and the nArg parameter is -1, then only a function that accepts
85012 ** any number of arguments will be returned.
85013 **
85014 ** If createFlag is false and nArg is -1, then the first valid
85015 ** function found is returned.  A function is valid if either xFunc
85016 ** or xStep is non-zero.
85017 **
85018 ** If createFlag is false, then a function with the required name and
85019 ** number of arguments may be returned even if the eTextRep flag does not
85020 ** match that requested.
85021 */
85022 SQLCIPHER_PRIVATE FuncDef *sqlcipher3FindFunction(
85023   sqlcipher3 *db,       /* An open database */
85024   const char *zName, /* Name of the function.  Not null-terminated */
85025   int nName,         /* Number of characters in the name */
85026   int nArg,          /* Number of arguments.  -1 means any number */
85027   u8 enc,            /* Preferred text encoding */
85028   int createFlag     /* Create new entry if true and does not otherwise exist */
85029 ){
85030   FuncDef *p;         /* Iterator variable */
85031   FuncDef *pBest = 0; /* Best match found so far */
85032   int bestScore = 0;  /* Score of best match */
85033   int h;              /* Hash value */
85034
85035
85036   assert( enc==SQLCIPHER_UTF8 || enc==SQLCIPHER_UTF16LE || enc==SQLCIPHER_UTF16BE );
85037   h = (sqlcipher3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
85038
85039   /* First search for a match amongst the application-defined functions.
85040   */
85041   p = functionSearch(&db->aFunc, h, zName, nName);
85042   while( p ){
85043     int score = matchQuality(p, nArg, enc);
85044     if( score>bestScore ){
85045       pBest = p;
85046       bestScore = score;
85047     }
85048     p = p->pNext;
85049   }
85050
85051   /* If no match is found, search the built-in functions.
85052   **
85053   ** If the SQLCIPHER_PreferBuiltin flag is set, then search the built-in
85054   ** functions even if a prior app-defined function was found.  And give
85055   ** priority to built-in functions.
85056   **
85057   ** Except, if createFlag is true, that means that we are trying to
85058   ** install a new function.  Whatever FuncDef structure is returned it will
85059   ** have fields overwritten with new information appropriate for the
85060   ** new function.  But the FuncDefs for built-in functions are read-only.
85061   ** So we must not search for built-ins when creating a new function.
85062   */ 
85063   if( !createFlag && (pBest==0 || (db->flags & SQLCIPHER_PreferBuiltin)!=0) ){
85064     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
85065     bestScore = 0;
85066     p = functionSearch(pHash, h, zName, nName);
85067     while( p ){
85068       int score = matchQuality(p, nArg, enc);
85069       if( score>bestScore ){
85070         pBest = p;
85071         bestScore = score;
85072       }
85073       p = p->pNext;
85074     }
85075   }
85076
85077   /* If the createFlag parameter is true and the search did not reveal an
85078   ** exact match for the name, number of arguments and encoding, then add a
85079   ** new entry to the hash table and return it.
85080   */
85081   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
85082       (pBest = sqlcipher3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85083     pBest->zName = (char *)&pBest[1];
85084     pBest->nArg = (u16)nArg;
85085     pBest->iPrefEnc = enc;
85086     memcpy(pBest->zName, zName, nName);
85087     pBest->zName[nName] = 0;
85088     sqlcipher3FuncDefInsert(&db->aFunc, pBest);
85089   }
85090
85091   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85092     return pBest;
85093   }
85094   return 0;
85095 }
85096
85097 /*
85098 ** Free all resources held by the schema structure. The void* argument points
85099 ** at a Schema struct. This function does not call sqlcipher3DbFree(db, ) on the 
85100 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85101 ** of the schema hash tables).
85102 **
85103 ** The Schema.cache_size variable is not cleared.
85104 */
85105 SQLCIPHER_PRIVATE void sqlcipher3SchemaClear(void *p){
85106   Hash temp1;
85107   Hash temp2;
85108   HashElem *pElem;
85109   Schema *pSchema = (Schema *)p;
85110
85111   temp1 = pSchema->tblHash;
85112   temp2 = pSchema->trigHash;
85113   sqlcipher3HashInit(&pSchema->trigHash);
85114   sqlcipher3HashClear(&pSchema->idxHash);
85115   for(pElem=sqlcipherHashFirst(&temp2); pElem; pElem=sqlcipherHashNext(pElem)){
85116     sqlcipher3DeleteTrigger(0, (Trigger*)sqlcipherHashData(pElem));
85117   }
85118   sqlcipher3HashClear(&temp2);
85119   sqlcipher3HashInit(&pSchema->tblHash);
85120   for(pElem=sqlcipherHashFirst(&temp1); pElem; pElem=sqlcipherHashNext(pElem)){
85121     Table *pTab = sqlcipherHashData(pElem);
85122     sqlcipher3DeleteTable(0, pTab);
85123   }
85124   sqlcipher3HashClear(&temp1);
85125   sqlcipher3HashClear(&pSchema->fkeyHash);
85126   pSchema->pSeqTab = 0;
85127   if( pSchema->flags & DB_SchemaLoaded ){
85128     pSchema->iGeneration++;
85129     pSchema->flags &= ~DB_SchemaLoaded;
85130   }
85131 }
85132
85133 /*
85134 ** Find and return the schema associated with a BTree.  Create
85135 ** a new one if necessary.
85136 */
85137 SQLCIPHER_PRIVATE Schema *sqlcipher3SchemaGet(sqlcipher3 *db, Btree *pBt){
85138   Schema * p;
85139   if( pBt ){
85140     p = (Schema *)sqlcipher3BtreeSchema(pBt, sizeof(Schema), sqlcipher3SchemaClear);
85141   }else{
85142     p = (Schema *)sqlcipher3DbMallocZero(0, sizeof(Schema));
85143   }
85144   if( !p ){
85145     db->mallocFailed = 1;
85146   }else if ( 0==p->file_format ){
85147     sqlcipher3HashInit(&p->tblHash);
85148     sqlcipher3HashInit(&p->idxHash);
85149     sqlcipher3HashInit(&p->trigHash);
85150     sqlcipher3HashInit(&p->fkeyHash);
85151     p->enc = SQLCIPHER_UTF8;
85152   }
85153   return p;
85154 }
85155
85156 /************** End of callback.c ********************************************/
85157 /************** Begin file delete.c ******************************************/
85158 /*
85159 ** 2001 September 15
85160 **
85161 ** The author disclaims copyright to this source code.  In place of
85162 ** a legal notice, here is a blessing:
85163 **
85164 **    May you do good and not evil.
85165 **    May you find forgiveness for yourself and forgive others.
85166 **    May you share freely, never taking more than you give.
85167 **
85168 *************************************************************************
85169 ** This file contains C code routines that are called by the parser
85170 ** in order to generate code for DELETE FROM statements.
85171 */
85172
85173 /*
85174 ** While a SrcList can in general represent multiple tables and subqueries
85175 ** (as in the FROM clause of a SELECT statement) in this case it contains
85176 ** the name of a single table, as one might find in an INSERT, DELETE,
85177 ** or UPDATE statement.  Look up that table in the symbol table and
85178 ** return a pointer.  Set an error message and return NULL if the table 
85179 ** name is not found or if any other error occurs.
85180 **
85181 ** The following fields are initialized appropriate in pSrc:
85182 **
85183 **    pSrc->a[0].pTab       Pointer to the Table object
85184 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85185 **
85186 */
85187 SQLCIPHER_PRIVATE Table *sqlcipher3SrcListLookup(Parse *pParse, SrcList *pSrc){
85188   struct SrcList_item *pItem = pSrc->a;
85189   Table *pTab;
85190   assert( pItem && pSrc->nSrc==1 );
85191   pTab = sqlcipher3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
85192   sqlcipher3DeleteTable(pParse->db, pItem->pTab);
85193   pItem->pTab = pTab;
85194   if( pTab ){
85195     pTab->nRef++;
85196   }
85197   if( sqlcipher3IndexedByLookup(pParse, pItem) ){
85198     pTab = 0;
85199   }
85200   return pTab;
85201 }
85202
85203 /*
85204 ** Check to make sure the given table is writable.  If it is not
85205 ** writable, generate an error message and return 1.  If it is
85206 ** writable return 0;
85207 */
85208 SQLCIPHER_PRIVATE int sqlcipher3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85209   /* A table is not writable under the following circumstances:
85210   **
85211   **   1) It is a virtual table and no implementation of the xUpdate method
85212   **      has been provided, or
85213   **   2) It is a system table (i.e. sqlcipher_master), this call is not
85214   **      part of a nested parse and writable_schema pragma has not 
85215   **      been specified.
85216   **
85217   ** In either case leave an error message in pParse and return non-zero.
85218   */
85219   if( ( IsVirtual(pTab) 
85220      && sqlcipher3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85221    || ( (pTab->tabFlags & TF_Readonly)!=0
85222      && (pParse->db->flags & SQLCIPHER_WriteSchema)==0
85223      && pParse->nested==0 )
85224   ){
85225     sqlcipher3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85226     return 1;
85227   }
85228
85229 #ifndef SQLCIPHER_OMIT_VIEW
85230   if( !viewOk && pTab->pSelect ){
85231     sqlcipher3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85232     return 1;
85233   }
85234 #endif
85235   return 0;
85236 }
85237
85238
85239 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
85240 /*
85241 ** Evaluate a view and store its result in an ephemeral table.  The
85242 ** pWhere argument is an optional WHERE clause that restricts the
85243 ** set of rows in the view that are to be added to the ephemeral table.
85244 */
85245 SQLCIPHER_PRIVATE void sqlcipher3MaterializeView(
85246   Parse *pParse,       /* Parsing context */
85247   Table *pView,        /* View definition */
85248   Expr *pWhere,        /* Optional WHERE clause to be added */
85249   int iCur             /* Cursor number for ephemerial table */
85250 ){
85251   SelectDest dest;
85252   Select *pDup;
85253   sqlcipher3 *db = pParse->db;
85254
85255   pDup = sqlcipher3SelectDup(db, pView->pSelect, 0);
85256   if( pWhere ){
85257     SrcList *pFrom;
85258     
85259     pWhere = sqlcipher3ExprDup(db, pWhere, 0);
85260     pFrom = sqlcipher3SrcListAppend(db, 0, 0, 0);
85261     if( pFrom ){
85262       assert( pFrom->nSrc==1 );
85263       pFrom->a[0].zAlias = sqlcipher3DbStrDup(db, pView->zName);
85264       pFrom->a[0].pSelect = pDup;
85265       assert( pFrom->a[0].pOn==0 );
85266       assert( pFrom->a[0].pUsing==0 );
85267     }else{
85268       sqlcipher3SelectDelete(db, pDup);
85269     }
85270     pDup = sqlcipher3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85271   }
85272   sqlcipher3SelectDestInit(&dest, SRT_EphemTab, iCur);
85273   sqlcipher3Select(pParse, pDup, &dest);
85274   sqlcipher3SelectDelete(db, pDup);
85275 }
85276 #endif /* !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER) */
85277
85278 #if defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY)
85279 /*
85280 ** Generate an expression tree to implement the WHERE, ORDER BY,
85281 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85282 **
85283 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85284 **                            \__________________________/
85285 **                               pLimitWhere (pInClause)
85286 */
85287 SQLCIPHER_PRIVATE Expr *sqlcipher3LimitWhere(
85288   Parse *pParse,               /* The parser context */
85289   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85290   Expr *pWhere,                /* The WHERE clause.  May be null */
85291   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85292   Expr *pLimit,                /* The LIMIT clause.  May be null */
85293   Expr *pOffset,               /* The OFFSET clause.  May be null */
85294   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85295 ){
85296   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85297   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85298   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85299   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85300   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85301   Select *pSelect = NULL;      /* Complete SELECT tree */
85302
85303   /* Check that there isn't an ORDER BY without a LIMIT clause.
85304   */
85305   if( pOrderBy && (pLimit == 0) ) {
85306     sqlcipher3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85307     pParse->parseError = 1;
85308     goto limit_where_cleanup_2;
85309   }
85310
85311   /* We only need to generate a select expression if there
85312   ** is a limit/offset term to enforce.
85313   */
85314   if( pLimit == 0 ) {
85315     /* if pLimit is null, pOffset will always be null as well. */
85316     assert( pOffset == 0 );
85317     return pWhere;
85318   }
85319
85320   /* Generate a select expression tree to enforce the limit/offset 
85321   ** term for the DELETE or UPDATE statement.  For example:
85322   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85323   ** becomes:
85324   **   DELETE FROM table_a WHERE rowid IN ( 
85325   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85326   **   );
85327   */
85328
85329   pSelectRowid = sqlcipher3PExpr(pParse, TK_ROW, 0, 0, 0);
85330   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85331   pEList = sqlcipher3ExprListAppend(pParse, 0, pSelectRowid);
85332   if( pEList == 0 ) goto limit_where_cleanup_2;
85333
85334   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85335   ** and the SELECT subtree. */
85336   pSelectSrc = sqlcipher3SrcListDup(pParse->db, pSrc, 0);
85337   if( pSelectSrc == 0 ) {
85338     sqlcipher3ExprListDelete(pParse->db, pEList);
85339     goto limit_where_cleanup_2;
85340   }
85341
85342   /* generate the SELECT expression tree. */
85343   pSelect = sqlcipher3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85344                              pOrderBy,0,pLimit,pOffset);
85345   if( pSelect == 0 ) return 0;
85346
85347   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85348   pWhereRowid = sqlcipher3PExpr(pParse, TK_ROW, 0, 0, 0);
85349   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85350   pInClause = sqlcipher3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85351   if( pInClause == 0 ) goto limit_where_cleanup_1;
85352
85353   pInClause->x.pSelect = pSelect;
85354   pInClause->flags |= EP_xIsSelect;
85355   sqlcipher3ExprSetHeight(pParse, pInClause);
85356   return pInClause;
85357
85358   /* something went wrong. clean up anything allocated. */
85359 limit_where_cleanup_1:
85360   sqlcipher3SelectDelete(pParse->db, pSelect);
85361   return 0;
85362
85363 limit_where_cleanup_2:
85364   sqlcipher3ExprDelete(pParse->db, pWhere);
85365   sqlcipher3ExprListDelete(pParse->db, pOrderBy);
85366   sqlcipher3ExprDelete(pParse->db, pLimit);
85367   sqlcipher3ExprDelete(pParse->db, pOffset);
85368   return 0;
85369 }
85370 #endif /* defined(SQLCIPHER_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLCIPHER_OMIT_SUBQUERY) */
85371
85372 /*
85373 ** Generate code for a DELETE FROM statement.
85374 **
85375 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85376 **                 \________/       \________________/
85377 **                  pTabList              pWhere
85378 */
85379 SQLCIPHER_PRIVATE void sqlcipher3DeleteFrom(
85380   Parse *pParse,         /* The parser context */
85381   SrcList *pTabList,     /* The table from which we should delete things */
85382   Expr *pWhere           /* The WHERE clause.  May be null */
85383 ){
85384   Vdbe *v;               /* The virtual database engine */
85385   Table *pTab;           /* The table from which records will be deleted */
85386   const char *zDb;       /* Name of database holding pTab */
85387   int end, addr = 0;     /* A couple addresses of generated code */
85388   int i;                 /* Loop counter */
85389   WhereInfo *pWInfo;     /* Information about the WHERE clause */
85390   Index *pIdx;           /* For looping over indices of the table */
85391   int iCur;              /* VDBE Cursor number for pTab */
85392   sqlcipher3 *db;           /* Main database structure */
85393   AuthContext sContext;  /* Authorization context */
85394   NameContext sNC;       /* Name context to resolve expressions in */
85395   int iDb;               /* Database number */
85396   int memCnt = -1;       /* Memory cell used for change counting */
85397   int rcauth;            /* Value returned by authorization callback */
85398
85399 #ifndef SQLCIPHER_OMIT_TRIGGER
85400   int isView;                  /* True if attempting to delete from a view */
85401   Trigger *pTrigger;           /* List of table triggers, if required */
85402 #endif
85403
85404   memset(&sContext, 0, sizeof(sContext));
85405   db = pParse->db;
85406   if( pParse->nErr || db->mallocFailed ){
85407     goto delete_from_cleanup;
85408   }
85409   assert( pTabList->nSrc==1 );
85410
85411   /* Locate the table which we want to delete.  This table has to be
85412   ** put in an SrcList structure because some of the subroutines we
85413   ** will be calling are designed to work with multiple tables and expect
85414   ** an SrcList* parameter instead of just a Table* parameter.
85415   */
85416   pTab = sqlcipher3SrcListLookup(pParse, pTabList);
85417   if( pTab==0 )  goto delete_from_cleanup;
85418
85419   /* Figure out if we have any triggers and if the table being
85420   ** deleted from is a view
85421   */
85422 #ifndef SQLCIPHER_OMIT_TRIGGER
85423   pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85424   isView = pTab->pSelect!=0;
85425 #else
85426 # define pTrigger 0
85427 # define isView 0
85428 #endif
85429 #ifdef SQLCIPHER_OMIT_VIEW
85430 # undef isView
85431 # define isView 0
85432 #endif
85433
85434   /* If pTab is really a view, make sure it has been initialized.
85435   */
85436   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
85437     goto delete_from_cleanup;
85438   }
85439
85440   if( sqlcipher3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85441     goto delete_from_cleanup;
85442   }
85443   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
85444   assert( iDb<db->nDb );
85445   zDb = db->aDb[iDb].zName;
85446   rcauth = sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, pTab->zName, 0, zDb);
85447   assert( rcauth==SQLCIPHER_OK || rcauth==SQLCIPHER_DENY || rcauth==SQLCIPHER_IGNORE );
85448   if( rcauth==SQLCIPHER_DENY ){
85449     goto delete_from_cleanup;
85450   }
85451   assert(!isView || pTrigger);
85452
85453   /* Assign  cursor number to the table and all its indices.
85454   */
85455   assert( pTabList->nSrc==1 );
85456   iCur = pTabList->a[0].iCursor = pParse->nTab++;
85457   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85458     pParse->nTab++;
85459   }
85460
85461   /* Start the view context
85462   */
85463   if( isView ){
85464     sqlcipher3AuthContextPush(pParse, &sContext, pTab->zName);
85465   }
85466
85467   /* Begin generating code.
85468   */
85469   v = sqlcipher3GetVdbe(pParse);
85470   if( v==0 ){
85471     goto delete_from_cleanup;
85472   }
85473   if( pParse->nested==0 ) sqlcipher3VdbeCountChanges(v);
85474   sqlcipher3BeginWriteOperation(pParse, 1, iDb);
85475
85476   /* If we are trying to delete from a view, realize that view into
85477   ** a ephemeral table.
85478   */
85479 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
85480   if( isView ){
85481     sqlcipher3MaterializeView(pParse, pTab, pWhere, iCur);
85482   }
85483 #endif
85484
85485   /* Resolve the column names in the WHERE clause.
85486   */
85487   memset(&sNC, 0, sizeof(sNC));
85488   sNC.pParse = pParse;
85489   sNC.pSrcList = pTabList;
85490   if( sqlcipher3ResolveExprNames(&sNC, pWhere) ){
85491     goto delete_from_cleanup;
85492   }
85493
85494   /* Initialize the counter of the number of rows deleted, if
85495   ** we are counting rows.
85496   */
85497   if( db->flags & SQLCIPHER_CountRows ){
85498     memCnt = ++pParse->nMem;
85499     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85500   }
85501
85502 #ifndef SQLCIPHER_OMIT_TRUNCATE_OPTIMIZATION
85503   /* Special case: A DELETE without a WHERE clause deletes everything.
85504   ** It is easier just to erase the whole table. Prior to version 3.6.5,
85505   ** this optimization caused the row change count (the value returned by 
85506   ** API function sqlcipher3_count_changes) to be set incorrectly.  */
85507   if( rcauth==SQLCIPHER_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
85508    && 0==sqlcipher3FkRequired(pParse, pTab, 0, 0)
85509   ){
85510     assert( !isView );
85511     sqlcipher3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85512                       pTab->zName, P4_STATIC);
85513     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85514       assert( pIdx->pSchema==pTab->pSchema );
85515       sqlcipher3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85516     }
85517   }else
85518 #endif /* SQLCIPHER_OMIT_TRUNCATE_OPTIMIZATION */
85519   /* The usual case: There is a WHERE clause so we have to scan through
85520   ** the table and pick which records to delete.
85521   */
85522   {
85523     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85524     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85525     int regRowid;                   /* Actual register containing rowids */
85526
85527     /* Collect rowids of every row to be deleted.
85528     */
85529     sqlcipher3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85530     pWInfo = sqlcipher3WhereBegin(
85531         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
85532     );
85533     if( pWInfo==0 ) goto delete_from_cleanup;
85534     regRowid = sqlcipher3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
85535     sqlcipher3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85536     if( db->flags & SQLCIPHER_CountRows ){
85537       sqlcipher3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85538     }
85539     sqlcipher3WhereEnd(pWInfo);
85540
85541     /* Delete every item whose key was written to the list during the
85542     ** database scan.  We have to delete items after the scan is complete
85543     ** because deleting an item can change the scan order.  */
85544     end = sqlcipher3VdbeMakeLabel(v);
85545
85546     /* Unless this is a view, open cursors for the table we are 
85547     ** deleting from and all its indices. If this is a view, then the
85548     ** only effect this statement has is to fire the INSTEAD OF 
85549     ** triggers.  */
85550     if( !isView ){
85551       sqlcipher3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85552     }
85553
85554     addr = sqlcipher3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85555
85556     /* Delete the row */
85557 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
85558     if( IsVirtual(pTab) ){
85559       const char *pVTab = (const char *)sqlcipher3GetVTable(db, pTab);
85560       sqlcipher3VtabMakeWritable(pParse, pTab);
85561       sqlcipher3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85562       sqlcipher3VdbeChangeP5(v, OE_Abort);
85563       sqlcipher3MayAbort(pParse);
85564     }else
85565 #endif
85566     {
85567       int count = (pParse->nested==0);    /* True to count changes */
85568       sqlcipher3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85569     }
85570
85571     /* End of the delete loop */
85572     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addr);
85573     sqlcipher3VdbeResolveLabel(v, end);
85574
85575     /* Close the cursors open on the table and its indexes. */
85576     if( !isView && !IsVirtual(pTab) ){
85577       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85578         sqlcipher3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85579       }
85580       sqlcipher3VdbeAddOp1(v, OP_Close, iCur);
85581     }
85582   }
85583
85584   /* Update the sqlcipher_sequence table by storing the content of the
85585   ** maximum rowid counter values recorded while inserting into
85586   ** autoincrement tables.
85587   */
85588   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85589     sqlcipher3AutoincrementEnd(pParse);
85590   }
85591
85592   /* Return the number of rows that were deleted. If this routine is 
85593   ** generating code because of a call to sqlcipher3NestedParse(), do not
85594   ** invoke the callback function.
85595   */
85596   if( (db->flags&SQLCIPHER_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85597     sqlcipher3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85598     sqlcipher3VdbeSetNumCols(v, 1);
85599     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLCIPHER_STATIC);
85600   }
85601
85602 delete_from_cleanup:
85603   sqlcipher3AuthContextPop(&sContext);
85604   sqlcipher3SrcListDelete(db, pTabList);
85605   sqlcipher3ExprDelete(db, pWhere);
85606   return;
85607 }
85608 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85609 ** thely may interfere with compilation of other functions in this file
85610 ** (or in another file, if this file becomes part of the amalgamation).  */
85611 #ifdef isView
85612  #undef isView
85613 #endif
85614 #ifdef pTrigger
85615  #undef pTrigger
85616 #endif
85617
85618 /*
85619 ** This routine generates VDBE code that causes a single row of a
85620 ** single table to be deleted.
85621 **
85622 ** The VDBE must be in a particular state when this routine is called.
85623 ** These are the requirements:
85624 **
85625 **   1.  A read/write cursor pointing to pTab, the table containing the row
85626 **       to be deleted, must be opened as cursor number $iCur.
85627 **
85628 **   2.  Read/write cursors for all indices of pTab must be open as
85629 **       cursor number base+i for the i-th index.
85630 **
85631 **   3.  The record number of the row to be deleted must be stored in
85632 **       memory cell iRowid.
85633 **
85634 ** This routine generates code to remove both the table record and all 
85635 ** index entries that point to that record.
85636 */
85637 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowDelete(
85638   Parse *pParse,     /* Parsing context */
85639   Table *pTab,       /* Table containing the row to be deleted */
85640   int iCur,          /* Cursor number for the table */
85641   int iRowid,        /* Memory cell that contains the rowid to delete */
85642   int count,         /* If non-zero, increment the row change counter */
85643   Trigger *pTrigger, /* List of triggers to (potentially) fire */
85644   int onconf         /* Default ON CONFLICT policy for triggers */
85645 ){
85646   Vdbe *v = pParse->pVdbe;        /* Vdbe */
85647   int iOld = 0;                   /* First register in OLD.* array */
85648   int iLabel;                     /* Label resolved to end of generated code */
85649
85650   /* Vdbe is guaranteed to have been allocated by this stage. */
85651   assert( v );
85652
85653   /* Seek cursor iCur to the row to delete. If this row no longer exists 
85654   ** (this can happen if a trigger program has already deleted it), do
85655   ** not attempt to delete it or fire any DELETE triggers.  */
85656   iLabel = sqlcipher3VdbeMakeLabel(v);
85657   sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85658  
85659   /* If there are any triggers to fire, allocate a range of registers to
85660   ** use for the old.* references in the triggers.  */
85661   if( sqlcipher3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85662     u32 mask;                     /* Mask of OLD.* columns in use */
85663     int iCol;                     /* Iterator used while populating OLD.* */
85664
85665     /* TODO: Could use temporary registers here. Also could attempt to
85666     ** avoid copying the contents of the rowid register.  */
85667     mask = sqlcipher3TriggerColmask(
85668         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85669     );
85670     mask |= sqlcipher3FkOldmask(pParse, pTab);
85671     iOld = pParse->nMem+1;
85672     pParse->nMem += (1 + pTab->nCol);
85673
85674     /* Populate the OLD.* pseudo-table register array. These values will be 
85675     ** used by any BEFORE and AFTER triggers that exist.  */
85676     sqlcipher3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
85677     for(iCol=0; iCol<pTab->nCol; iCol++){
85678       if( mask==0xffffffff || mask&(1<<iCol) ){
85679         sqlcipher3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
85680       }
85681     }
85682
85683     /* Invoke BEFORE DELETE trigger programs. */
85684     sqlcipher3CodeRowTrigger(pParse, pTrigger, 
85685         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
85686     );
85687
85688     /* Seek the cursor to the row to be deleted again. It may be that
85689     ** the BEFORE triggers coded above have already removed the row
85690     ** being deleted. Do not attempt to delete the row a second time, and 
85691     ** do not fire AFTER triggers.  */
85692     sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85693
85694     /* Do FK processing. This call checks that any FK constraints that
85695     ** refer to this table (i.e. constraints attached to other tables) 
85696     ** are not violated by deleting this row.  */
85697     sqlcipher3FkCheck(pParse, pTab, iOld, 0);
85698   }
85699
85700   /* Delete the index and table entries. Skip this step if pTab is really
85701   ** a view (in which case the only effect of the DELETE statement is to
85702   ** fire the INSTEAD OF triggers).  */ 
85703   if( pTab->pSelect==0 ){
85704     sqlcipher3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
85705     sqlcipher3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
85706     if( count ){
85707       sqlcipher3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85708     }
85709   }
85710
85711   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85712   ** handle rows (possibly in other tables) that refer via a foreign key
85713   ** to the row just deleted. */ 
85714   sqlcipher3FkActions(pParse, pTab, 0, iOld);
85715
85716   /* Invoke AFTER DELETE trigger programs. */
85717   sqlcipher3CodeRowTrigger(pParse, pTrigger, 
85718       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
85719   );
85720
85721   /* Jump here if the row had already been deleted before any BEFORE
85722   ** trigger programs were invoked. Or if a trigger program throws a 
85723   ** RAISE(IGNORE) exception.  */
85724   sqlcipher3VdbeResolveLabel(v, iLabel);
85725 }
85726
85727 /*
85728 ** This routine generates VDBE code that causes the deletion of all
85729 ** index entries associated with a single row of a single table.
85730 **
85731 ** The VDBE must be in a particular state when this routine is called.
85732 ** These are the requirements:
85733 **
85734 **   1.  A read/write cursor pointing to pTab, the table containing the row
85735 **       to be deleted, must be opened as cursor number "iCur".
85736 **
85737 **   2.  Read/write cursors for all indices of pTab must be open as
85738 **       cursor number iCur+i for the i-th index.
85739 **
85740 **   3.  The "iCur" cursor must be pointing to the row that is to be
85741 **       deleted.
85742 */
85743 SQLCIPHER_PRIVATE void sqlcipher3GenerateRowIndexDelete(
85744   Parse *pParse,     /* Parsing and code generating context */
85745   Table *pTab,       /* Table containing the row to be deleted */
85746   int iCur,          /* Cursor number for the table */
85747   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
85748 ){
85749   int i;
85750   Index *pIdx;
85751   int r1;
85752
85753   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85754     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
85755     r1 = sqlcipher3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
85756     sqlcipher3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
85757   }
85758 }
85759
85760 /*
85761 ** Generate code that will assemble an index key and put it in register
85762 ** regOut.  The key with be for index pIdx which is an index on pTab.
85763 ** iCur is the index of a cursor open on the pTab table and pointing to
85764 ** the entry that needs indexing.
85765 **
85766 ** Return a register number which is the first in a block of
85767 ** registers that holds the elements of the index key.  The
85768 ** block of registers has already been deallocated by the time
85769 ** this routine returns.
85770 */
85771 SQLCIPHER_PRIVATE int sqlcipher3GenerateIndexKey(
85772   Parse *pParse,     /* Parsing context */
85773   Index *pIdx,       /* The index for which to generate a key */
85774   int iCur,          /* Cursor number for the pIdx->pTable table */
85775   int regOut,        /* Write the new index key to this register */
85776   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
85777 ){
85778   Vdbe *v = pParse->pVdbe;
85779   int j;
85780   Table *pTab = pIdx->pTable;
85781   int regBase;
85782   int nCol;
85783
85784   nCol = pIdx->nColumn;
85785   regBase = sqlcipher3GetTempRange(pParse, nCol+1);
85786   sqlcipher3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
85787   for(j=0; j<nCol; j++){
85788     int idx = pIdx->aiColumn[j];
85789     if( idx==pTab->iPKey ){
85790       sqlcipher3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
85791     }else{
85792       sqlcipher3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
85793       sqlcipher3ColumnDefault(v, pTab, idx, -1);
85794     }
85795   }
85796   if( doMakeRec ){
85797     const char *zAff;
85798     if( pTab->pSelect || (pParse->db->flags & SQLCIPHER_IdxRealAsInt)!=0 ){
85799       zAff = 0;
85800     }else{
85801       zAff = sqlcipher3IndexAffinityStr(v, pIdx);
85802     }
85803     sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
85804     sqlcipher3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
85805   }
85806   sqlcipher3ReleaseTempRange(pParse, regBase, nCol+1);
85807   return regBase;
85808 }
85809
85810 /************** End of delete.c **********************************************/
85811 /************** Begin file func.c ********************************************/
85812 /*
85813 ** 2002 February 23
85814 **
85815 ** The author disclaims copyright to this source code.  In place of
85816 ** a legal notice, here is a blessing:
85817 **
85818 **    May you do good and not evil.
85819 **    May you find forgiveness for yourself and forgive others.
85820 **    May you share freely, never taking more than you give.
85821 **
85822 *************************************************************************
85823 ** This file contains the C functions that implement various SQL
85824 ** functions of SQLite.  
85825 **
85826 ** There is only one exported symbol in this file - the function
85827 ** sqlcipherRegisterBuildinFunctions() found at the bottom of the file.
85828 ** All other code has file scope.
85829 */
85830 /* #include <stdlib.h> */
85831 /* #include <assert.h> */
85832
85833 /*
85834 ** Return the collating function associated with a function.
85835 */
85836 static CollSeq *sqlcipher3GetFuncCollSeq(sqlcipher3_context *context){
85837   return context->pColl;
85838 }
85839
85840 /*
85841 ** Implementation of the non-aggregate min() and max() functions
85842 */
85843 static void minmaxFunc(
85844   sqlcipher3_context *context,
85845   int argc,
85846   sqlcipher3_value **argv
85847 ){
85848   int i;
85849   int mask;    /* 0 for min() or 0xffffffff for max() */
85850   int iBest;
85851   CollSeq *pColl;
85852
85853   assert( argc>1 );
85854   mask = sqlcipher3_user_data(context)==0 ? 0 : -1;
85855   pColl = sqlcipher3GetFuncCollSeq(context);
85856   assert( pColl );
85857   assert( mask==-1 || mask==0 );
85858   iBest = 0;
85859   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
85860   for(i=1; i<argc; i++){
85861     if( sqlcipher3_value_type(argv[i])==SQLCIPHER_NULL ) return;
85862     if( (sqlcipher3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
85863       testcase( mask==0 );
85864       iBest = i;
85865     }
85866   }
85867   sqlcipher3_result_value(context, argv[iBest]);
85868 }
85869
85870 /*
85871 ** Return the type of the argument.
85872 */
85873 static void typeofFunc(
85874   sqlcipher3_context *context,
85875   int NotUsed,
85876   sqlcipher3_value **argv
85877 ){
85878   const char *z = 0;
85879   UNUSED_PARAMETER(NotUsed);
85880   switch( sqlcipher3_value_type(argv[0]) ){
85881     case SQLCIPHER_INTEGER: z = "integer"; break;
85882     case SQLCIPHER_TEXT:    z = "text";    break;
85883     case SQLCIPHER_FLOAT:   z = "real";    break;
85884     case SQLCIPHER_BLOB:    z = "blob";    break;
85885     default:             z = "null";    break;
85886   }
85887   sqlcipher3_result_text(context, z, -1, SQLCIPHER_STATIC);
85888 }
85889
85890
85891 /*
85892 ** Implementation of the length() function
85893 */
85894 static void lengthFunc(
85895   sqlcipher3_context *context,
85896   int argc,
85897   sqlcipher3_value **argv
85898 ){
85899   int len;
85900
85901   assert( argc==1 );
85902   UNUSED_PARAMETER(argc);
85903   switch( sqlcipher3_value_type(argv[0]) ){
85904     case SQLCIPHER_BLOB:
85905     case SQLCIPHER_INTEGER:
85906     case SQLCIPHER_FLOAT: {
85907       sqlcipher3_result_int(context, sqlcipher3_value_bytes(argv[0]));
85908       break;
85909     }
85910     case SQLCIPHER_TEXT: {
85911       const unsigned char *z = sqlcipher3_value_text(argv[0]);
85912       if( z==0 ) return;
85913       len = 0;
85914       while( *z ){
85915         len++;
85916         SQLCIPHER_SKIP_UTF8(z);
85917       }
85918       sqlcipher3_result_int(context, len);
85919       break;
85920     }
85921     default: {
85922       sqlcipher3_result_null(context);
85923       break;
85924     }
85925   }
85926 }
85927
85928 /*
85929 ** Implementation of the abs() function.
85930 **
85931 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
85932 ** the numeric argument X. 
85933 */
85934 static void absFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
85935   assert( argc==1 );
85936   UNUSED_PARAMETER(argc);
85937   switch( sqlcipher3_value_type(argv[0]) ){
85938     case SQLCIPHER_INTEGER: {
85939       i64 iVal = sqlcipher3_value_int64(argv[0]);
85940       if( iVal<0 ){
85941         if( (iVal<<1)==0 ){
85942           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
85943           ** abs(X) throws an integer overflow error since there is no
85944           ** equivalent positive 64-bit two complement value. */
85945           sqlcipher3_result_error(context, "integer overflow", -1);
85946           return;
85947         }
85948         iVal = -iVal;
85949       } 
85950       sqlcipher3_result_int64(context, iVal);
85951       break;
85952     }
85953     case SQLCIPHER_NULL: {
85954       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
85955       sqlcipher3_result_null(context);
85956       break;
85957     }
85958     default: {
85959       /* Because sqlcipher3_value_double() returns 0.0 if the argument is not
85960       ** something that can be converted into a number, we have:
85961       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
85962       ** cannot be converted to a numeric value. 
85963       */
85964       double rVal = sqlcipher3_value_double(argv[0]);
85965       if( rVal<0 ) rVal = -rVal;
85966       sqlcipher3_result_double(context, rVal);
85967       break;
85968     }
85969   }
85970 }
85971
85972 /*
85973 ** Implementation of the substr() function.
85974 **
85975 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
85976 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
85977 ** of x.  If x is text, then we actually count UTF-8 characters.
85978 ** If x is a blob, then we count bytes.
85979 **
85980 ** If p1 is negative, then we begin abs(p1) from the end of x[].
85981 **
85982 ** If p2 is negative, return the p2 characters preceeding p1.
85983 */
85984 static void substrFunc(
85985   sqlcipher3_context *context,
85986   int argc,
85987   sqlcipher3_value **argv
85988 ){
85989   const unsigned char *z;
85990   const unsigned char *z2;
85991   int len;
85992   int p0type;
85993   i64 p1, p2;
85994   int negP2 = 0;
85995
85996   assert( argc==3 || argc==2 );
85997   if( sqlcipher3_value_type(argv[1])==SQLCIPHER_NULL
85998    || (argc==3 && sqlcipher3_value_type(argv[2])==SQLCIPHER_NULL)
85999   ){
86000     return;
86001   }
86002   p0type = sqlcipher3_value_type(argv[0]);
86003   p1 = sqlcipher3_value_int(argv[1]);
86004   if( p0type==SQLCIPHER_BLOB ){
86005     len = sqlcipher3_value_bytes(argv[0]);
86006     z = sqlcipher3_value_blob(argv[0]);
86007     if( z==0 ) return;
86008     assert( len==sqlcipher3_value_bytes(argv[0]) );
86009   }else{
86010     z = sqlcipher3_value_text(argv[0]);
86011     if( z==0 ) return;
86012     len = 0;
86013     if( p1<0 ){
86014       for(z2=z; *z2; len++){
86015         SQLCIPHER_SKIP_UTF8(z2);
86016       }
86017     }
86018   }
86019   if( argc==3 ){
86020     p2 = sqlcipher3_value_int(argv[2]);
86021     if( p2<0 ){
86022       p2 = -p2;
86023       negP2 = 1;
86024     }
86025   }else{
86026     p2 = sqlcipher3_context_db_handle(context)->aLimit[SQLCIPHER_LIMIT_LENGTH];
86027   }
86028   if( p1<0 ){
86029     p1 += len;
86030     if( p1<0 ){
86031       p2 += p1;
86032       if( p2<0 ) p2 = 0;
86033       p1 = 0;
86034     }
86035   }else if( p1>0 ){
86036     p1--;
86037   }else if( p2>0 ){
86038     p2--;
86039   }
86040   if( negP2 ){
86041     p1 -= p2;
86042     if( p1<0 ){
86043       p2 += p1;
86044       p1 = 0;
86045     }
86046   }
86047   assert( p1>=0 && p2>=0 );
86048   if( p0type!=SQLCIPHER_BLOB ){
86049     while( *z && p1 ){
86050       SQLCIPHER_SKIP_UTF8(z);
86051       p1--;
86052     }
86053     for(z2=z; *z2 && p2; p2--){
86054       SQLCIPHER_SKIP_UTF8(z2);
86055     }
86056     sqlcipher3_result_text(context, (char*)z, (int)(z2-z), SQLCIPHER_TRANSIENT);
86057   }else{
86058     if( p1+p2>len ){
86059       p2 = len-p1;
86060       if( p2<0 ) p2 = 0;
86061     }
86062     sqlcipher3_result_blob(context, (char*)&z[p1], (int)p2, SQLCIPHER_TRANSIENT);
86063   }
86064 }
86065
86066 /*
86067 ** Implementation of the round() function
86068 */
86069 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
86070 static void roundFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86071   int n = 0;
86072   double r;
86073   char *zBuf;
86074   assert( argc==1 || argc==2 );
86075   if( argc==2 ){
86076     if( SQLCIPHER_NULL==sqlcipher3_value_type(argv[1]) ) return;
86077     n = sqlcipher3_value_int(argv[1]);
86078     if( n>30 ) n = 30;
86079     if( n<0 ) n = 0;
86080   }
86081   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
86082   r = sqlcipher3_value_double(argv[0]);
86083   /* If Y==0 and X will fit in a 64-bit int,
86084   ** handle the rounding directly,
86085   ** otherwise use printf.
86086   */
86087   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86088     r = (double)((sqlcipher_int64)(r+0.5));
86089   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86090     r = -(double)((sqlcipher_int64)((-r)+0.5));
86091   }else{
86092     zBuf = sqlcipher3_mprintf("%.*f",n,r);
86093     if( zBuf==0 ){
86094       sqlcipher3_result_error_nomem(context);
86095       return;
86096     }
86097     sqlcipher3AtoF(zBuf, &r, sqlcipher3Strlen30(zBuf), SQLCIPHER_UTF8);
86098     sqlcipher3_free(zBuf);
86099   }
86100   sqlcipher3_result_double(context, r);
86101 }
86102 #endif
86103
86104 /*
86105 ** Allocate nByte bytes of space using sqlcipher3_malloc(). If the
86106 ** allocation fails, call sqlcipher3_result_error_nomem() to notify
86107 ** the database handle that malloc() has failed and return NULL.
86108 ** If nByte is larger than the maximum string or blob length, then
86109 ** raise an SQLCIPHER_TOOBIG exception and return NULL.
86110 */
86111 static void *contextMalloc(sqlcipher3_context *context, i64 nByte){
86112   char *z;
86113   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86114   assert( nByte>0 );
86115   testcase( nByte==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86116   testcase( nByte==db->aLimit[SQLCIPHER_LIMIT_LENGTH]+1 );
86117   if( nByte>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
86118     sqlcipher3_result_error_toobig(context);
86119     z = 0;
86120   }else{
86121     z = sqlcipher3Malloc((int)nByte);
86122     if( !z ){
86123       sqlcipher3_result_error_nomem(context);
86124     }
86125   }
86126   return z;
86127 }
86128
86129 /*
86130 ** Implementation of the upper() and lower() SQL functions.
86131 */
86132 static void upperFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86133   char *z1;
86134   const char *z2;
86135   int i, n;
86136   UNUSED_PARAMETER(argc);
86137   z2 = (char*)sqlcipher3_value_text(argv[0]);
86138   n = sqlcipher3_value_bytes(argv[0]);
86139   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86140   assert( z2==(char*)sqlcipher3_value_text(argv[0]) );
86141   if( z2 ){
86142     z1 = contextMalloc(context, ((i64)n)+1);
86143     if( z1 ){
86144       for(i=0; i<n; i++){
86145         z1[i] = (char)sqlcipher3Toupper(z2[i]);
86146       }
86147       sqlcipher3_result_text(context, z1, n, sqlcipher3_free);
86148     }
86149   }
86150 }
86151 static void lowerFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86152   char *z1;
86153   const char *z2;
86154   int i, n;
86155   UNUSED_PARAMETER(argc);
86156   z2 = (char*)sqlcipher3_value_text(argv[0]);
86157   n = sqlcipher3_value_bytes(argv[0]);
86158   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86159   assert( z2==(char*)sqlcipher3_value_text(argv[0]) );
86160   if( z2 ){
86161     z1 = contextMalloc(context, ((i64)n)+1);
86162     if( z1 ){
86163       for(i=0; i<n; i++){
86164         z1[i] = sqlcipher3Tolower(z2[i]);
86165       }
86166       sqlcipher3_result_text(context, z1, n, sqlcipher3_free);
86167     }
86168   }
86169 }
86170
86171
86172 #if 0  /* This function is never used. */
86173 /*
86174 ** The COALESCE() and IFNULL() functions used to be implemented as shown
86175 ** here.  But now they are implemented as VDBE code so that unused arguments
86176 ** do not have to be computed.  This legacy implementation is retained as
86177 ** comment.
86178 */
86179 /*
86180 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
86181 ** All three do the same thing.  They return the first non-NULL
86182 ** argument.
86183 */
86184 static void ifnullFunc(
86185   sqlcipher3_context *context,
86186   int argc,
86187   sqlcipher3_value **argv
86188 ){
86189   int i;
86190   for(i=0; i<argc; i++){
86191     if( SQLCIPHER_NULL!=sqlcipher3_value_type(argv[i]) ){
86192       sqlcipher3_result_value(context, argv[i]);
86193       break;
86194     }
86195   }
86196 }
86197 #endif /* NOT USED */
86198 #define ifnullFunc versionFunc   /* Substitute function - never called */
86199
86200 /*
86201 ** Implementation of random().  Return a random integer.  
86202 */
86203 static void randomFunc(
86204   sqlcipher3_context *context,
86205   int NotUsed,
86206   sqlcipher3_value **NotUsed2
86207 ){
86208   sqlcipher_int64 r;
86209   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86210   sqlcipher3_randomness(sizeof(r), &r);
86211   if( r<0 ){
86212     /* We need to prevent a random number of 0x8000000000000000 
86213     ** (or -9223372036854775808) since when you do abs() of that
86214     ** number of you get the same value back again.  To do this
86215     ** in a way that is testable, mask the sign bit off of negative
86216     ** values, resulting in a positive value.  Then take the 
86217     ** 2s complement of that positive value.  The end result can
86218     ** therefore be no less than -9223372036854775807.
86219     */
86220     r = -(r ^ (((sqlcipher3_int64)1)<<63));
86221   }
86222   sqlcipher3_result_int64(context, r);
86223 }
86224
86225 /*
86226 ** Implementation of randomblob(N).  Return a random blob
86227 ** that is N bytes long.
86228 */
86229 static void randomBlob(
86230   sqlcipher3_context *context,
86231   int argc,
86232   sqlcipher3_value **argv
86233 ){
86234   int n;
86235   unsigned char *p;
86236   assert( argc==1 );
86237   UNUSED_PARAMETER(argc);
86238   n = sqlcipher3_value_int(argv[0]);
86239   if( n<1 ){
86240     n = 1;
86241   }
86242   p = contextMalloc(context, n);
86243   if( p ){
86244     sqlcipher3_randomness(n, p);
86245     sqlcipher3_result_blob(context, (char*)p, n, sqlcipher3_free);
86246   }
86247 }
86248
86249 /*
86250 ** Implementation of the last_insert_rowid() SQL function.  The return
86251 ** value is the same as the sqlcipher3_last_insert_rowid() API function.
86252 */
86253 static void last_insert_rowid(
86254   sqlcipher3_context *context, 
86255   int NotUsed, 
86256   sqlcipher3_value **NotUsed2
86257 ){
86258   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86259   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86260   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86261   ** wrapper around the sqlcipher3_last_insert_rowid() C/C++ interface
86262   ** function. */
86263   sqlcipher3_result_int64(context, sqlcipher3_last_insert_rowid(db));
86264 }
86265
86266 /*
86267 ** Implementation of the changes() SQL function.
86268 **
86269 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
86270 ** around the sqlcipher3_changes() C/C++ function and hence follows the same
86271 ** rules for counting changes.
86272 */
86273 static void changes(
86274   sqlcipher3_context *context,
86275   int NotUsed,
86276   sqlcipher3_value **NotUsed2
86277 ){
86278   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86279   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86280   sqlcipher3_result_int(context, sqlcipher3_changes(db));
86281 }
86282
86283 /*
86284 ** Implementation of the total_changes() SQL function.  The return value is
86285 ** the same as the sqlcipher3_total_changes() API function.
86286 */
86287 static void total_changes(
86288   sqlcipher3_context *context,
86289   int NotUsed,
86290   sqlcipher3_value **NotUsed2
86291 ){
86292   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86293   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86294   /* IMP: R-52756-41993 This function is a wrapper around the
86295   ** sqlcipher3_total_changes() C/C++ interface. */
86296   sqlcipher3_result_int(context, sqlcipher3_total_changes(db));
86297 }
86298
86299 /*
86300 ** A structure defining how to do GLOB-style comparisons.
86301 */
86302 struct compareInfo {
86303   u8 matchAll;
86304   u8 matchOne;
86305   u8 matchSet;
86306   u8 noCase;
86307 };
86308
86309 /*
86310 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
86311 ** character is exactly one byte in size.  Also, all characters are
86312 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
86313 ** whereas only characters less than 0x80 do in ASCII.
86314 */
86315 #if defined(SQLCIPHER_EBCDIC)
86316 # define sqlcipher3Utf8Read(A,C)  (*(A++))
86317 # define GlogUpperToLower(A)   A = sqlcipher3UpperToLower[A]
86318 #else
86319 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlcipher3UpperToLower[A]; }
86320 #endif
86321
86322 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86323 /* The correct SQL-92 behavior is for the LIKE operator to ignore
86324 ** case.  Thus  'a' LIKE 'A' would be true. */
86325 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86326 /* If SQLCIPHER_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86327 ** is case sensitive causing 'a' LIKE 'A' to be false */
86328 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86329
86330 /*
86331 ** Compare two UTF-8 strings for equality where the first string can
86332 ** potentially be a "glob" expression.  Return true (1) if they
86333 ** are the same and false (0) if they are different.
86334 **
86335 ** Globbing rules:
86336 **
86337 **      '*'       Matches any sequence of zero or more characters.
86338 **
86339 **      '?'       Matches exactly one character.
86340 **
86341 **     [...]      Matches one character from the enclosed list of
86342 **                characters.
86343 **
86344 **     [^...]     Matches one character not in the enclosed list.
86345 **
86346 ** With the [...] and [^...] matching, a ']' character can be included
86347 ** in the list by making it the first character after '[' or '^'.  A
86348 ** range of characters can be specified using '-'.  Example:
86349 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
86350 ** it the last character in the list.
86351 **
86352 ** This routine is usually quick, but can be N**2 in the worst case.
86353 **
86354 ** Hints: to match '*' or '?', put them in "[]".  Like this:
86355 **
86356 **         abc[*]xyz        Matches "abc*xyz" only
86357 */
86358 static int patternCompare(
86359   const u8 *zPattern,              /* The glob pattern */
86360   const u8 *zString,               /* The string to compare against the glob */
86361   const struct compareInfo *pInfo, /* Information about how to do the compare */
86362   u32 esc                          /* The escape character */
86363 ){
86364   u32 c, c2;
86365   int invert;
86366   int seen;
86367   u8 matchOne = pInfo->matchOne;
86368   u8 matchAll = pInfo->matchAll;
86369   u8 matchSet = pInfo->matchSet;
86370   u8 noCase = pInfo->noCase; 
86371   int prevEscape = 0;     /* True if the previous character was 'escape' */
86372
86373   while( (c = sqlcipher3Utf8Read(zPattern,&zPattern))!=0 ){
86374     if( !prevEscape && c==matchAll ){
86375       while( (c=sqlcipher3Utf8Read(zPattern,&zPattern)) == matchAll
86376                || c == matchOne ){
86377         if( c==matchOne && sqlcipher3Utf8Read(zString, &zString)==0 ){
86378           return 0;
86379         }
86380       }
86381       if( c==0 ){
86382         return 1;
86383       }else if( c==esc ){
86384         c = sqlcipher3Utf8Read(zPattern, &zPattern);
86385         if( c==0 ){
86386           return 0;
86387         }
86388       }else if( c==matchSet ){
86389         assert( esc==0 );         /* This is GLOB, not LIKE */
86390         assert( matchSet<0x80 );  /* '[' is a single-byte character */
86391         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86392           SQLCIPHER_SKIP_UTF8(zString);
86393         }
86394         return *zString!=0;
86395       }
86396       while( (c2 = sqlcipher3Utf8Read(zString,&zString))!=0 ){
86397         if( noCase ){
86398           GlogUpperToLower(c2);
86399           GlogUpperToLower(c);
86400           while( c2 != 0 && c2 != c ){
86401             c2 = sqlcipher3Utf8Read(zString, &zString);
86402             GlogUpperToLower(c2);
86403           }
86404         }else{
86405           while( c2 != 0 && c2 != c ){
86406             c2 = sqlcipher3Utf8Read(zString, &zString);
86407           }
86408         }
86409         if( c2==0 ) return 0;
86410         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86411       }
86412       return 0;
86413     }else if( !prevEscape && c==matchOne ){
86414       if( sqlcipher3Utf8Read(zString, &zString)==0 ){
86415         return 0;
86416       }
86417     }else if( c==matchSet ){
86418       u32 prior_c = 0;
86419       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86420       seen = 0;
86421       invert = 0;
86422       c = sqlcipher3Utf8Read(zString, &zString);
86423       if( c==0 ) return 0;
86424       c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86425       if( c2=='^' ){
86426         invert = 1;
86427         c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86428       }
86429       if( c2==']' ){
86430         if( c==']' ) seen = 1;
86431         c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86432       }
86433       while( c2 && c2!=']' ){
86434         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86435           c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86436           if( c>=prior_c && c<=c2 ) seen = 1;
86437           prior_c = 0;
86438         }else{
86439           if( c==c2 ){
86440             seen = 1;
86441           }
86442           prior_c = c2;
86443         }
86444         c2 = sqlcipher3Utf8Read(zPattern, &zPattern);
86445       }
86446       if( c2==0 || (seen ^ invert)==0 ){
86447         return 0;
86448       }
86449     }else if( esc==c && !prevEscape ){
86450       prevEscape = 1;
86451     }else{
86452       c2 = sqlcipher3Utf8Read(zString, &zString);
86453       if( noCase ){
86454         GlogUpperToLower(c);
86455         GlogUpperToLower(c2);
86456       }
86457       if( c!=c2 ){
86458         return 0;
86459       }
86460       prevEscape = 0;
86461     }
86462   }
86463   return *zString==0;
86464 }
86465
86466 /*
86467 ** Count the number of times that the LIKE operator (or GLOB which is
86468 ** just a variation of LIKE) gets called.  This is used for testing
86469 ** only.
86470 */
86471 #ifdef SQLCIPHER_TEST
86472 SQLCIPHER_API int sqlcipher3_like_count = 0;
86473 #endif
86474
86475
86476 /*
86477 ** Implementation of the like() SQL function.  This function implements
86478 ** the build-in LIKE operator.  The first argument to the function is the
86479 ** pattern and the second argument is the string.  So, the SQL statements:
86480 **
86481 **       A LIKE B
86482 **
86483 ** is implemented as like(B,A).
86484 **
86485 ** This same function (with a different compareInfo structure) computes
86486 ** the GLOB operator.
86487 */
86488 static void likeFunc(
86489   sqlcipher3_context *context, 
86490   int argc, 
86491   sqlcipher3_value **argv
86492 ){
86493   const unsigned char *zA, *zB;
86494   u32 escape = 0;
86495   int nPat;
86496   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86497
86498   zB = sqlcipher3_value_text(argv[0]);
86499   zA = sqlcipher3_value_text(argv[1]);
86500
86501   /* Limit the length of the LIKE or GLOB pattern to avoid problems
86502   ** of deep recursion and N*N behavior in patternCompare().
86503   */
86504   nPat = sqlcipher3_value_bytes(argv[0]);
86505   testcase( nPat==db->aLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH] );
86506   testcase( nPat==db->aLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86507   if( nPat > db->aLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH] ){
86508     sqlcipher3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86509     return;
86510   }
86511   assert( zB==sqlcipher3_value_text(argv[0]) );  /* Encoding did not change */
86512
86513   if( argc==3 ){
86514     /* The escape character string must consist of a single UTF-8 character.
86515     ** Otherwise, return an error.
86516     */
86517     const unsigned char *zEsc = sqlcipher3_value_text(argv[2]);
86518     if( zEsc==0 ) return;
86519     if( sqlcipher3Utf8CharLen((char*)zEsc, -1)!=1 ){
86520       sqlcipher3_result_error(context, 
86521           "ESCAPE expression must be a single character", -1);
86522       return;
86523     }
86524     escape = sqlcipher3Utf8Read(zEsc, &zEsc);
86525   }
86526   if( zA && zB ){
86527     struct compareInfo *pInfo = sqlcipher3_user_data(context);
86528 #ifdef SQLCIPHER_TEST
86529     sqlcipher3_like_count++;
86530 #endif
86531     
86532     sqlcipher3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86533   }
86534 }
86535
86536 /*
86537 ** Implementation of the NULLIF(x,y) function.  The result is the first
86538 ** argument if the arguments are different.  The result is NULL if the
86539 ** arguments are equal to each other.
86540 */
86541 static void nullifFunc(
86542   sqlcipher3_context *context,
86543   int NotUsed,
86544   sqlcipher3_value **argv
86545 ){
86546   CollSeq *pColl = sqlcipher3GetFuncCollSeq(context);
86547   UNUSED_PARAMETER(NotUsed);
86548   if( sqlcipher3MemCompare(argv[0], argv[1], pColl)!=0 ){
86549     sqlcipher3_result_value(context, argv[0]);
86550   }
86551 }
86552
86553 /*
86554 ** Implementation of the sqlcipher_version() function.  The result is the version
86555 ** of the SQLite library that is running.
86556 */
86557 static void versionFunc(
86558   sqlcipher3_context *context,
86559   int NotUsed,
86560   sqlcipher3_value **NotUsed2
86561 ){
86562   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86563   /* IMP: R-48699-48617 This function is an SQL wrapper around the
86564   ** sqlcipher3_libversion() C-interface. */
86565   sqlcipher3_result_text(context, sqlcipher3_libversion(), -1, SQLCIPHER_STATIC);
86566 }
86567
86568 /*
86569 ** Implementation of the sqlcipher_source_id() function. The result is a string
86570 ** that identifies the particular version of the source code used to build
86571 ** SQLite.
86572 */
86573 static void sourceidFunc(
86574   sqlcipher3_context *context,
86575   int NotUsed,
86576   sqlcipher3_value **NotUsed2
86577 ){
86578   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86579   /* IMP: R-24470-31136 This function is an SQL wrapper around the
86580   ** sqlcipher3_sourceid() C interface. */
86581   sqlcipher3_result_text(context, sqlcipher3_sourceid(), -1, SQLCIPHER_STATIC);
86582 }
86583
86584 /*
86585 ** Implementation of the sqlcipher_log() function.  This is a wrapper around
86586 ** sqlcipher3_log().  The return value is NULL.  The function exists purely for
86587 ** its side-effects.
86588 */
86589 static void errlogFunc(
86590   sqlcipher3_context *context,
86591   int argc,
86592   sqlcipher3_value **argv
86593 ){
86594   UNUSED_PARAMETER(argc);
86595   UNUSED_PARAMETER(context);
86596   sqlcipher3_log(sqlcipher3_value_int(argv[0]), "%s", sqlcipher3_value_text(argv[1]));
86597 }
86598
86599 /*
86600 ** Implementation of the sqlcipher_compileoption_used() function.
86601 ** The result is an integer that identifies if the compiler option
86602 ** was used to build SQLite.
86603 */
86604 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
86605 static void compileoptionusedFunc(
86606   sqlcipher3_context *context,
86607   int argc,
86608   sqlcipher3_value **argv
86609 ){
86610   const char *zOptName;
86611   assert( argc==1 );
86612   UNUSED_PARAMETER(argc);
86613   /* IMP: R-39564-36305 The sqlcipher_compileoption_used() SQL
86614   ** function is a wrapper around the sqlcipher3_compileoption_used() C/C++
86615   ** function.
86616   */
86617   if( (zOptName = (const char*)sqlcipher3_value_text(argv[0]))!=0 ){
86618     sqlcipher3_result_int(context, sqlcipher3_compileoption_used(zOptName));
86619   }
86620 }
86621 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
86622
86623 /*
86624 ** Implementation of the sqlcipher_compileoption_get() function. 
86625 ** The result is a string that identifies the compiler options 
86626 ** used to build SQLite.
86627 */
86628 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
86629 static void compileoptiongetFunc(
86630   sqlcipher3_context *context,
86631   int argc,
86632   sqlcipher3_value **argv
86633 ){
86634   int n;
86635   assert( argc==1 );
86636   UNUSED_PARAMETER(argc);
86637   /* IMP: R-04922-24076 The sqlcipher_compileoption_get() SQL function
86638   ** is a wrapper around the sqlcipher3_compileoption_get() C/C++ function.
86639   */
86640   n = sqlcipher3_value_int(argv[0]);
86641   sqlcipher3_result_text(context, sqlcipher3_compileoption_get(n), -1, SQLCIPHER_STATIC);
86642 }
86643 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
86644
86645 /* Array for converting from half-bytes (nybbles) into ASCII hex
86646 ** digits. */
86647 static const char hexdigits[] = {
86648   '0', '1', '2', '3', '4', '5', '6', '7',
86649   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
86650 };
86651
86652 /*
86653 ** EXPERIMENTAL - This is not an official function.  The interface may
86654 ** change.  This function may disappear.  Do not write code that depends
86655 ** on this function.
86656 **
86657 ** Implementation of the QUOTE() function.  This function takes a single
86658 ** argument.  If the argument is numeric, the return value is the same as
86659 ** the argument.  If the argument is NULL, the return value is the string
86660 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
86661 ** single-quote escapes.
86662 */
86663 static void quoteFunc(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
86664   assert( argc==1 );
86665   UNUSED_PARAMETER(argc);
86666   switch( sqlcipher3_value_type(argv[0]) ){
86667     case SQLCIPHER_INTEGER:
86668     case SQLCIPHER_FLOAT: {
86669       sqlcipher3_result_value(context, argv[0]);
86670       break;
86671     }
86672     case SQLCIPHER_BLOB: {
86673       char *zText = 0;
86674       char const *zBlob = sqlcipher3_value_blob(argv[0]);
86675       int nBlob = sqlcipher3_value_bytes(argv[0]);
86676       assert( zBlob==sqlcipher3_value_blob(argv[0]) ); /* No encoding change */
86677       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
86678       if( zText ){
86679         int i;
86680         for(i=0; i<nBlob; i++){
86681           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
86682           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
86683         }
86684         zText[(nBlob*2)+2] = '\'';
86685         zText[(nBlob*2)+3] = '\0';
86686         zText[0] = 'X';
86687         zText[1] = '\'';
86688         sqlcipher3_result_text(context, zText, -1, SQLCIPHER_TRANSIENT);
86689         sqlcipher3_free(zText);
86690       }
86691       break;
86692     }
86693     case SQLCIPHER_TEXT: {
86694       int i,j;
86695       u64 n;
86696       const unsigned char *zArg = sqlcipher3_value_text(argv[0]);
86697       char *z;
86698
86699       if( zArg==0 ) return;
86700       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
86701       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
86702       if( z ){
86703         z[0] = '\'';
86704         for(i=0, j=1; zArg[i]; i++){
86705           z[j++] = zArg[i];
86706           if( zArg[i]=='\'' ){
86707             z[j++] = '\'';
86708           }
86709         }
86710         z[j++] = '\'';
86711         z[j] = 0;
86712         sqlcipher3_result_text(context, z, j, sqlcipher3_free);
86713       }
86714       break;
86715     }
86716     default: {
86717       assert( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL );
86718       sqlcipher3_result_text(context, "NULL", 4, SQLCIPHER_STATIC);
86719       break;
86720     }
86721   }
86722 }
86723
86724 /*
86725 ** The hex() function.  Interpret the argument as a blob.  Return
86726 ** a hexadecimal rendering as text.
86727 */
86728 static void hexFunc(
86729   sqlcipher3_context *context,
86730   int argc,
86731   sqlcipher3_value **argv
86732 ){
86733   int i, n;
86734   const unsigned char *pBlob;
86735   char *zHex, *z;
86736   assert( argc==1 );
86737   UNUSED_PARAMETER(argc);
86738   pBlob = sqlcipher3_value_blob(argv[0]);
86739   n = sqlcipher3_value_bytes(argv[0]);
86740   assert( pBlob==sqlcipher3_value_blob(argv[0]) );  /* No encoding change */
86741   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
86742   if( zHex ){
86743     for(i=0; i<n; i++, pBlob++){
86744       unsigned char c = *pBlob;
86745       *(z++) = hexdigits[(c>>4)&0xf];
86746       *(z++) = hexdigits[c&0xf];
86747     }
86748     *z = 0;
86749     sqlcipher3_result_text(context, zHex, n*2, sqlcipher3_free);
86750   }
86751 }
86752
86753 /*
86754 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
86755 */
86756 static void zeroblobFunc(
86757   sqlcipher3_context *context,
86758   int argc,
86759   sqlcipher3_value **argv
86760 ){
86761   i64 n;
86762   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86763   assert( argc==1 );
86764   UNUSED_PARAMETER(argc);
86765   n = sqlcipher3_value_int64(argv[0]);
86766   testcase( n==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86767   testcase( n==db->aLimit[SQLCIPHER_LIMIT_LENGTH]+1 );
86768   if( n>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
86769     sqlcipher3_result_error_toobig(context);
86770   }else{
86771     sqlcipher3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
86772   }
86773 }
86774
86775 /*
86776 ** The replace() function.  Three arguments are all strings: call
86777 ** them A, B, and C. The result is also a string which is derived
86778 ** from A by replacing every occurance of B with C.  The match
86779 ** must be exact.  Collating sequences are not used.
86780 */
86781 static void replaceFunc(
86782   sqlcipher3_context *context,
86783   int argc,
86784   sqlcipher3_value **argv
86785 ){
86786   const unsigned char *zStr;        /* The input string A */
86787   const unsigned char *zPattern;    /* The pattern string B */
86788   const unsigned char *zRep;        /* The replacement string C */
86789   unsigned char *zOut;              /* The output */
86790   int nStr;                /* Size of zStr */
86791   int nPattern;            /* Size of zPattern */
86792   int nRep;                /* Size of zRep */
86793   i64 nOut;                /* Maximum size of zOut */
86794   int loopLimit;           /* Last zStr[] that might match zPattern[] */
86795   int i, j;                /* Loop counters */
86796
86797   assert( argc==3 );
86798   UNUSED_PARAMETER(argc);
86799   zStr = sqlcipher3_value_text(argv[0]);
86800   if( zStr==0 ) return;
86801   nStr = sqlcipher3_value_bytes(argv[0]);
86802   assert( zStr==sqlcipher3_value_text(argv[0]) );  /* No encoding change */
86803   zPattern = sqlcipher3_value_text(argv[1]);
86804   if( zPattern==0 ){
86805     assert( sqlcipher3_value_type(argv[1])==SQLCIPHER_NULL
86806             || sqlcipher3_context_db_handle(context)->mallocFailed );
86807     return;
86808   }
86809   if( zPattern[0]==0 ){
86810     assert( sqlcipher3_value_type(argv[1])!=SQLCIPHER_NULL );
86811     sqlcipher3_result_value(context, argv[0]);
86812     return;
86813   }
86814   nPattern = sqlcipher3_value_bytes(argv[1]);
86815   assert( zPattern==sqlcipher3_value_text(argv[1]) );  /* No encoding change */
86816   zRep = sqlcipher3_value_text(argv[2]);
86817   if( zRep==0 ) return;
86818   nRep = sqlcipher3_value_bytes(argv[2]);
86819   assert( zRep==sqlcipher3_value_text(argv[2]) );
86820   nOut = nStr + 1;
86821   assert( nOut<SQLCIPHER_MAX_LENGTH );
86822   zOut = contextMalloc(context, (i64)nOut);
86823   if( zOut==0 ){
86824     return;
86825   }
86826   loopLimit = nStr - nPattern;  
86827   for(i=j=0; i<=loopLimit; i++){
86828     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
86829       zOut[j++] = zStr[i];
86830     }else{
86831       u8 *zOld;
86832       sqlcipher3 *db = sqlcipher3_context_db_handle(context);
86833       nOut += nRep - nPattern;
86834       testcase( nOut-1==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86835       testcase( nOut-2==db->aLimit[SQLCIPHER_LIMIT_LENGTH] );
86836       if( nOut-1>db->aLimit[SQLCIPHER_LIMIT_LENGTH] ){
86837         sqlcipher3_result_error_toobig(context);
86838         sqlcipher3_free(zOut);
86839         return;
86840       }
86841       zOld = zOut;
86842       zOut = sqlcipher3_realloc(zOut, (int)nOut);
86843       if( zOut==0 ){
86844         sqlcipher3_result_error_nomem(context);
86845         sqlcipher3_free(zOld);
86846         return;
86847       }
86848       memcpy(&zOut[j], zRep, nRep);
86849       j += nRep;
86850       i += nPattern-1;
86851     }
86852   }
86853   assert( j+nStr-i+1==nOut );
86854   memcpy(&zOut[j], &zStr[i], nStr-i);
86855   j += nStr - i;
86856   assert( j<=nOut );
86857   zOut[j] = 0;
86858   sqlcipher3_result_text(context, (char*)zOut, j, sqlcipher3_free);
86859 }
86860
86861 /*
86862 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
86863 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
86864 */
86865 static void trimFunc(
86866   sqlcipher3_context *context,
86867   int argc,
86868   sqlcipher3_value **argv
86869 ){
86870   const unsigned char *zIn;         /* Input string */
86871   const unsigned char *zCharSet;    /* Set of characters to trim */
86872   int nIn;                          /* Number of bytes in input */
86873   int flags;                        /* 1: trimleft  2: trimright  3: trim */
86874   int i;                            /* Loop counter */
86875   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
86876   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
86877   int nChar;                        /* Number of characters in zCharSet */
86878
86879   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ){
86880     return;
86881   }
86882   zIn = sqlcipher3_value_text(argv[0]);
86883   if( zIn==0 ) return;
86884   nIn = sqlcipher3_value_bytes(argv[0]);
86885   assert( zIn==sqlcipher3_value_text(argv[0]) );
86886   if( argc==1 ){
86887     static const unsigned char lenOne[] = { 1 };
86888     static unsigned char * const azOne[] = { (u8*)" " };
86889     nChar = 1;
86890     aLen = (u8*)lenOne;
86891     azChar = (unsigned char **)azOne;
86892     zCharSet = 0;
86893   }else if( (zCharSet = sqlcipher3_value_text(argv[1]))==0 ){
86894     return;
86895   }else{
86896     const unsigned char *z;
86897     for(z=zCharSet, nChar=0; *z; nChar++){
86898       SQLCIPHER_SKIP_UTF8(z);
86899     }
86900     if( nChar>0 ){
86901       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
86902       if( azChar==0 ){
86903         return;
86904       }
86905       aLen = (unsigned char*)&azChar[nChar];
86906       for(z=zCharSet, nChar=0; *z; nChar++){
86907         azChar[nChar] = (unsigned char *)z;
86908         SQLCIPHER_SKIP_UTF8(z);
86909         aLen[nChar] = (u8)(z - azChar[nChar]);
86910       }
86911     }
86912   }
86913   if( nChar>0 ){
86914     flags = SQLCIPHER_PTR_TO_INT(sqlcipher3_user_data(context));
86915     if( flags & 1 ){
86916       while( nIn>0 ){
86917         int len = 0;
86918         for(i=0; i<nChar; i++){
86919           len = aLen[i];
86920           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
86921         }
86922         if( i>=nChar ) break;
86923         zIn += len;
86924         nIn -= len;
86925       }
86926     }
86927     if( flags & 2 ){
86928       while( nIn>0 ){
86929         int len = 0;
86930         for(i=0; i<nChar; i++){
86931           len = aLen[i];
86932           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
86933         }
86934         if( i>=nChar ) break;
86935         nIn -= len;
86936       }
86937     }
86938     if( zCharSet ){
86939       sqlcipher3_free(azChar);
86940     }
86941   }
86942   sqlcipher3_result_text(context, (char*)zIn, nIn, SQLCIPHER_TRANSIENT);
86943 }
86944
86945
86946 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
86947 ** is only available if the SQLCIPHER_SOUNDEX compile-time option is used
86948 ** when SQLite is built.
86949 */
86950 #ifdef SQLCIPHER_SOUNDEX
86951 /*
86952 ** Compute the soundex encoding of a word.
86953 **
86954 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
86955 ** soundex encoding of the string X. 
86956 */
86957 static void soundexFunc(
86958   sqlcipher3_context *context,
86959   int argc,
86960   sqlcipher3_value **argv
86961 ){
86962   char zResult[8];
86963   const u8 *zIn;
86964   int i, j;
86965   static const unsigned char iCode[] = {
86966     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86967     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86968     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86969     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86970     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86971     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86972     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86973     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86974   };
86975   assert( argc==1 );
86976   zIn = (u8*)sqlcipher3_value_text(argv[0]);
86977   if( zIn==0 ) zIn = (u8*)"";
86978   for(i=0; zIn[i] && !sqlcipher3Isalpha(zIn[i]); i++){}
86979   if( zIn[i] ){
86980     u8 prevcode = iCode[zIn[i]&0x7f];
86981     zResult[0] = sqlcipher3Toupper(zIn[i]);
86982     for(j=1; j<4 && zIn[i]; i++){
86983       int code = iCode[zIn[i]&0x7f];
86984       if( code>0 ){
86985         if( code!=prevcode ){
86986           prevcode = code;
86987           zResult[j++] = code + '0';
86988         }
86989       }else{
86990         prevcode = 0;
86991       }
86992     }
86993     while( j<4 ){
86994       zResult[j++] = '0';
86995     }
86996     zResult[j] = 0;
86997     sqlcipher3_result_text(context, zResult, 4, SQLCIPHER_TRANSIENT);
86998   }else{
86999     /* IMP: R-64894-50321 The string "?000" is returned if the argument
87000     ** is NULL or contains no ASCII alphabetic characters. */
87001     sqlcipher3_result_text(context, "?000", 4, SQLCIPHER_STATIC);
87002   }
87003 }
87004 #endif /* SQLCIPHER_SOUNDEX */
87005
87006 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
87007 /*
87008 ** A function that loads a shared-library extension then returns NULL.
87009 */
87010 static void loadExt(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
87011   const char *zFile = (const char *)sqlcipher3_value_text(argv[0]);
87012   const char *zProc;
87013   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
87014   char *zErrMsg = 0;
87015
87016   if( argc==2 ){
87017     zProc = (const char *)sqlcipher3_value_text(argv[1]);
87018   }else{
87019     zProc = 0;
87020   }
87021   if( zFile && sqlcipher3_load_extension(db, zFile, zProc, &zErrMsg) ){
87022     sqlcipher3_result_error(context, zErrMsg, -1);
87023     sqlcipher3_free(zErrMsg);
87024   }
87025 }
87026 #endif
87027
87028
87029 /*
87030 ** An instance of the following structure holds the context of a
87031 ** sum() or avg() aggregate computation.
87032 */
87033 typedef struct SumCtx SumCtx;
87034 struct SumCtx {
87035   double rSum;      /* Floating point sum */
87036   i64 iSum;         /* Integer sum */   
87037   i64 cnt;          /* Number of elements summed */
87038   u8 overflow;      /* True if integer overflow seen */
87039   u8 approx;        /* True if non-integer value was input to the sum */
87040 };
87041
87042 /*
87043 ** Routines used to compute the sum, average, and total.
87044 **
87045 ** The SUM() function follows the (broken) SQL standard which means
87046 ** that it returns NULL if it sums over no inputs.  TOTAL returns
87047 ** 0.0 in that case.  In addition, TOTAL always returns a float where
87048 ** SUM might return an integer if it never encounters a floating point
87049 ** value.  TOTAL never fails, but SUM might through an exception if
87050 ** it overflows an integer.
87051 */
87052 static void sumStep(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
87053   SumCtx *p;
87054   int type;
87055   assert( argc==1 );
87056   UNUSED_PARAMETER(argc);
87057   p = sqlcipher3_aggregate_context(context, sizeof(*p));
87058   type = sqlcipher3_value_numeric_type(argv[0]);
87059   if( p && type!=SQLCIPHER_NULL ){
87060     p->cnt++;
87061     if( type==SQLCIPHER_INTEGER ){
87062       i64 v = sqlcipher3_value_int64(argv[0]);
87063       p->rSum += v;
87064       if( (p->approx|p->overflow)==0 && sqlcipher3AddInt64(&p->iSum, v) ){
87065         p->overflow = 1;
87066       }
87067     }else{
87068       p->rSum += sqlcipher3_value_double(argv[0]);
87069       p->approx = 1;
87070     }
87071   }
87072 }
87073 static void sumFinalize(sqlcipher3_context *context){
87074   SumCtx *p;
87075   p = sqlcipher3_aggregate_context(context, 0);
87076   if( p && p->cnt>0 ){
87077     if( p->overflow ){
87078       sqlcipher3_result_error(context,"integer overflow",-1);
87079     }else if( p->approx ){
87080       sqlcipher3_result_double(context, p->rSum);
87081     }else{
87082       sqlcipher3_result_int64(context, p->iSum);
87083     }
87084   }
87085 }
87086 static void avgFinalize(sqlcipher3_context *context){
87087   SumCtx *p;
87088   p = sqlcipher3_aggregate_context(context, 0);
87089   if( p && p->cnt>0 ){
87090     sqlcipher3_result_double(context, p->rSum/(double)p->cnt);
87091   }
87092 }
87093 static void totalFinalize(sqlcipher3_context *context){
87094   SumCtx *p;
87095   p = sqlcipher3_aggregate_context(context, 0);
87096   /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
87097   sqlcipher3_result_double(context, p ? p->rSum : (double)0);
87098 }
87099
87100 /*
87101 ** The following structure keeps track of state information for the
87102 ** count() aggregate function.
87103 */
87104 typedef struct CountCtx CountCtx;
87105 struct CountCtx {
87106   i64 n;
87107 };
87108
87109 /*
87110 ** Routines to implement the count() aggregate function.
87111 */
87112 static void countStep(sqlcipher3_context *context, int argc, sqlcipher3_value **argv){
87113   CountCtx *p;
87114   p = sqlcipher3_aggregate_context(context, sizeof(*p));
87115   if( (argc==0 || SQLCIPHER_NULL!=sqlcipher3_value_type(argv[0])) && p ){
87116     p->n++;
87117   }
87118
87119 #ifndef SQLCIPHER_OMIT_DEPRECATED
87120   /* The sqlcipher3_aggregate_count() function is deprecated.  But just to make
87121   ** sure it still operates correctly, verify that its count agrees with our 
87122   ** internal count when using count(*) and when the total count can be
87123   ** expressed as a 32-bit integer. */
87124   assert( argc==1 || p==0 || p->n>0x7fffffff
87125           || p->n==sqlcipher3_aggregate_count(context) );
87126 #endif
87127 }   
87128 static void countFinalize(sqlcipher3_context *context){
87129   CountCtx *p;
87130   p = sqlcipher3_aggregate_context(context, 0);
87131   sqlcipher3_result_int64(context, p ? p->n : 0);
87132 }
87133
87134 /*
87135 ** Routines to implement min() and max() aggregate functions.
87136 */
87137 static void minmaxStep(
87138   sqlcipher3_context *context, 
87139   int NotUsed, 
87140   sqlcipher3_value **argv
87141 ){
87142   Mem *pArg  = (Mem *)argv[0];
87143   Mem *pBest;
87144   UNUSED_PARAMETER(NotUsed);
87145
87146   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
87147   pBest = (Mem *)sqlcipher3_aggregate_context(context, sizeof(*pBest));
87148   if( !pBest ) return;
87149
87150   if( pBest->flags ){
87151     int max;
87152     int cmp;
87153     CollSeq *pColl = sqlcipher3GetFuncCollSeq(context);
87154     /* This step function is used for both the min() and max() aggregates,
87155     ** the only difference between the two being that the sense of the
87156     ** comparison is inverted. For the max() aggregate, the
87157     ** sqlcipher3_user_data() function returns (void *)-1. For min() it
87158     ** returns (void *)db, where db is the sqlcipher3* database pointer.
87159     ** Therefore the next statement sets variable 'max' to 1 for the max()
87160     ** aggregate, or 0 for min().
87161     */
87162     max = sqlcipher3_user_data(context)!=0;
87163     cmp = sqlcipher3MemCompare(pBest, pArg, pColl);
87164     if( (max && cmp<0) || (!max && cmp>0) ){
87165       sqlcipher3VdbeMemCopy(pBest, pArg);
87166     }
87167   }else{
87168     sqlcipher3VdbeMemCopy(pBest, pArg);
87169   }
87170 }
87171 static void minMaxFinalize(sqlcipher3_context *context){
87172   sqlcipher3_value *pRes;
87173   pRes = (sqlcipher3_value *)sqlcipher3_aggregate_context(context, 0);
87174   if( pRes ){
87175     if( ALWAYS(pRes->flags) ){
87176       sqlcipher3_result_value(context, pRes);
87177     }
87178     sqlcipher3VdbeMemRelease(pRes);
87179   }
87180 }
87181
87182 /*
87183 ** group_concat(EXPR, ?SEPARATOR?)
87184 */
87185 static void groupConcatStep(
87186   sqlcipher3_context *context,
87187   int argc,
87188   sqlcipher3_value **argv
87189 ){
87190   const char *zVal;
87191   StrAccum *pAccum;
87192   const char *zSep;
87193   int nVal, nSep;
87194   assert( argc==1 || argc==2 );
87195   if( sqlcipher3_value_type(argv[0])==SQLCIPHER_NULL ) return;
87196   pAccum = (StrAccum*)sqlcipher3_aggregate_context(context, sizeof(*pAccum));
87197
87198   if( pAccum ){
87199     sqlcipher3 *db = sqlcipher3_context_db_handle(context);
87200     int firstTerm = pAccum->useMalloc==0;
87201     pAccum->useMalloc = 2;
87202     pAccum->mxAlloc = db->aLimit[SQLCIPHER_LIMIT_LENGTH];
87203     if( !firstTerm ){
87204       if( argc==2 ){
87205         zSep = (char*)sqlcipher3_value_text(argv[1]);
87206         nSep = sqlcipher3_value_bytes(argv[1]);
87207       }else{
87208         zSep = ",";
87209         nSep = 1;
87210       }
87211       sqlcipher3StrAccumAppend(pAccum, zSep, nSep);
87212     }
87213     zVal = (char*)sqlcipher3_value_text(argv[0]);
87214     nVal = sqlcipher3_value_bytes(argv[0]);
87215     sqlcipher3StrAccumAppend(pAccum, zVal, nVal);
87216   }
87217 }
87218 static void groupConcatFinalize(sqlcipher3_context *context){
87219   StrAccum *pAccum;
87220   pAccum = sqlcipher3_aggregate_context(context, 0);
87221   if( pAccum ){
87222     if( pAccum->tooBig ){
87223       sqlcipher3_result_error_toobig(context);
87224     }else if( pAccum->mallocFailed ){
87225       sqlcipher3_result_error_nomem(context);
87226     }else{    
87227       sqlcipher3_result_text(context, sqlcipher3StrAccumFinish(pAccum), -1, 
87228                           sqlcipher3_free);
87229     }
87230   }
87231 }
87232
87233 /*
87234 ** This routine does per-connection function registration.  Most
87235 ** of the built-in functions above are part of the global function set.
87236 ** This routine only deals with those that are not global.
87237 */
87238 SQLCIPHER_PRIVATE void sqlcipher3RegisterBuiltinFunctions(sqlcipher3 *db){
87239   int rc = sqlcipher3_overload_function(db, "MATCH", 2);
87240 #ifndef OMIT_EXPORT
87241   extern void sqlcipher_exportFunc(sqlcipher3_context *, int, sqlcipher3_value **);
87242 #endif
87243   assert( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_OK );
87244   if( rc==SQLCIPHER_NOMEM ){
87245     db->mallocFailed = 1;
87246   }
87247 #ifndef OMIT_EXPORT
87248   sqlcipher3CreateFunc(db, "sqlcipher_export", 1, SQLCIPHER_TEXT, 0, sqlcipher_exportFunc, 0, 0, 0);
87249 #endif
87250 }
87251
87252 /*
87253 ** Set the LIKEOPT flag on the 2-argument function with the given name.
87254 */
87255 static void setLikeOptFlag(sqlcipher3 *db, const char *zName, u8 flagVal){
87256   FuncDef *pDef;
87257   pDef = sqlcipher3FindFunction(db, zName, sqlcipher3Strlen30(zName),
87258                              2, SQLCIPHER_UTF8, 0);
87259   if( ALWAYS(pDef) ){
87260     pDef->flags = flagVal;
87261   }
87262 }
87263
87264 /*
87265 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
87266 ** parameter determines whether or not the LIKE operator is case
87267 ** sensitive.  GLOB is always case sensitive.
87268 */
87269 SQLCIPHER_PRIVATE void sqlcipher3RegisterLikeFunctions(sqlcipher3 *db, int caseSensitive){
87270   struct compareInfo *pInfo;
87271   if( caseSensitive ){
87272     pInfo = (struct compareInfo*)&likeInfoAlt;
87273   }else{
87274     pInfo = (struct compareInfo*)&likeInfoNorm;
87275   }
87276   sqlcipher3CreateFunc(db, "like", 2, SQLCIPHER_UTF8, pInfo, likeFunc, 0, 0, 0);
87277   sqlcipher3CreateFunc(db, "like", 3, SQLCIPHER_UTF8, pInfo, likeFunc, 0, 0, 0);
87278   sqlcipher3CreateFunc(db, "glob", 2, SQLCIPHER_UTF8, 
87279       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87280   setLikeOptFlag(db, "glob", SQLCIPHER_FUNC_LIKE | SQLCIPHER_FUNC_CASE);
87281   setLikeOptFlag(db, "like", 
87282       caseSensitive ? (SQLCIPHER_FUNC_LIKE | SQLCIPHER_FUNC_CASE) : SQLCIPHER_FUNC_LIKE);
87283 }
87284
87285 /*
87286 ** pExpr points to an expression which implements a function.  If
87287 ** it is appropriate to apply the LIKE optimization to that function
87288 ** then set aWc[0] through aWc[2] to the wildcard characters and
87289 ** return TRUE.  If the function is not a LIKE-style function then
87290 ** return FALSE.
87291 */
87292 SQLCIPHER_PRIVATE int sqlcipher3IsLikeFunction(sqlcipher3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87293   FuncDef *pDef;
87294   if( pExpr->op!=TK_FUNCTION 
87295    || !pExpr->x.pList 
87296    || pExpr->x.pList->nExpr!=2
87297   ){
87298     return 0;
87299   }
87300   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87301   pDef = sqlcipher3FindFunction(db, pExpr->u.zToken, 
87302                              sqlcipher3Strlen30(pExpr->u.zToken),
87303                              2, SQLCIPHER_UTF8, 0);
87304   if( NEVER(pDef==0) || (pDef->flags & SQLCIPHER_FUNC_LIKE)==0 ){
87305     return 0;
87306   }
87307
87308   /* The memcpy() statement assumes that the wildcard characters are
87309   ** the first three statements in the compareInfo structure.  The
87310   ** asserts() that follow verify that assumption
87311   */
87312   memcpy(aWc, pDef->pUserData, 3);
87313   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87314   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87315   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87316   *pIsNocase = (pDef->flags & SQLCIPHER_FUNC_CASE)==0;
87317   return 1;
87318 }
87319
87320 /*
87321 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
87322 ** to the global function hash table.  This occurs at start-time (as
87323 ** a consequence of calling sqlcipher3_initialize()).
87324 **
87325 ** After this routine runs
87326 */
87327 SQLCIPHER_PRIVATE void sqlcipher3RegisterGlobalFunctions(void){
87328   /*
87329   ** The following array holds FuncDef structures for all of the functions
87330   ** defined in this file.
87331   **
87332   ** The array cannot be constant since changes are made to the
87333   ** FuncDef.pHash elements at start-time.  The elements of this array
87334   ** are read-only after initialization is complete.
87335   */
87336   static SQLCIPHER_WSD FuncDef aBuiltinFunc[] = {
87337     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87338     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87339     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87340     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87341     FUNCTION(trim,               1, 3, 0, trimFunc         ),
87342     FUNCTION(trim,               2, 3, 0, trimFunc         ),
87343     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87344     FUNCTION(min,                0, 0, 1, 0                ),
87345     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87346     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87347     FUNCTION(max,                0, 1, 1, 0                ),
87348     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87349     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
87350     FUNCTION(length,             1, 0, 0, lengthFunc       ),
87351     FUNCTION(substr,             2, 0, 0, substrFunc       ),
87352     FUNCTION(substr,             3, 0, 0, substrFunc       ),
87353     FUNCTION(abs,                1, 0, 0, absFunc          ),
87354 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
87355     FUNCTION(round,              1, 0, 0, roundFunc        ),
87356     FUNCTION(round,              2, 0, 0, roundFunc        ),
87357 #endif
87358     FUNCTION(upper,              1, 0, 0, upperFunc        ),
87359     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87360     FUNCTION(coalesce,           1, 0, 0, 0                ),
87361     FUNCTION(coalesce,           0, 0, 0, 0                ),
87362 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
87363     {-1,SQLCIPHER_UTF8,SQLCIPHER_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
87364     FUNCTION(hex,                1, 0, 0, hexFunc          ),
87365 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
87366     {2,SQLCIPHER_UTF8,SQLCIPHER_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
87367     FUNCTION(random,             0, 0, 0, randomFunc       ),
87368     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87369     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87370     FUNCTION(sqlcipher_version,     0, 0, 0, versionFunc      ),
87371     FUNCTION(sqlcipher_source_id,   0, 0, 0, sourceidFunc     ),
87372     FUNCTION(sqlcipher_log,         2, 0, 0, errlogFunc       ),
87373 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
87374     FUNCTION(sqlcipher_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87375     FUNCTION(sqlcipher_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87376 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
87377     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87378     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87379     FUNCTION(changes,            0, 0, 0, changes          ),
87380     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87381     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87382     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87383   #ifdef SQLCIPHER_SOUNDEX
87384     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87385   #endif
87386   #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
87387     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87388     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87389   #endif
87390     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87391     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87392     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87393  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87394     {0,SQLCIPHER_UTF8,SQLCIPHER_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87395     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87396     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87397     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87398   
87399     LIKEFUNC(glob, 2, &globInfo, SQLCIPHER_FUNC_LIKE|SQLCIPHER_FUNC_CASE),
87400   #ifdef SQLCIPHER_CASE_SENSITIVE_LIKE
87401     LIKEFUNC(like, 2, &likeInfoAlt, SQLCIPHER_FUNC_LIKE|SQLCIPHER_FUNC_CASE),
87402     LIKEFUNC(like, 3, &likeInfoAlt, SQLCIPHER_FUNC_LIKE|SQLCIPHER_FUNC_CASE),
87403   #else
87404     LIKEFUNC(like, 2, &likeInfoNorm, SQLCIPHER_FUNC_LIKE),
87405     LIKEFUNC(like, 3, &likeInfoNorm, SQLCIPHER_FUNC_LIKE),
87406   #endif
87407   };
87408
87409   int i;
87410   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
87411   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87412
87413   for(i=0; i<ArraySize(aBuiltinFunc); i++){
87414     sqlcipher3FuncDefInsert(pHash, &aFunc[i]);
87415   }
87416   sqlcipher3RegisterDateTimeFunctions();
87417 #ifndef SQLCIPHER_OMIT_ALTERTABLE
87418   sqlcipher3AlterFunctions();
87419 #endif
87420 }
87421
87422 /************** End of func.c ************************************************/
87423 /************** Begin file fkey.c ********************************************/
87424 /*
87425 **
87426 ** The author disclaims copyright to this source code.  In place of
87427 ** a legal notice, here is a blessing:
87428 **
87429 **    May you do good and not evil.
87430 **    May you find forgiveness for yourself and forgive others.
87431 **    May you share freely, never taking more than you give.
87432 **
87433 *************************************************************************
87434 ** This file contains code used by the compiler to add foreign key
87435 ** support to compiled SQL statements.
87436 */
87437
87438 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
87439 #ifndef SQLCIPHER_OMIT_TRIGGER
87440
87441 /*
87442 ** Deferred and Immediate FKs
87443 ** --------------------------
87444 **
87445 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
87446 ** If an immediate foreign key constraint is violated, SQLCIPHER_CONSTRAINT
87447 ** is returned and the current statement transaction rolled back. If a 
87448 ** deferred foreign key constraint is violated, no action is taken 
87449 ** immediately. However if the application attempts to commit the 
87450 ** transaction before fixing the constraint violation, the attempt fails.
87451 **
87452 ** Deferred constraints are implemented using a simple counter associated
87453 ** with the database handle. The counter is set to zero each time a 
87454 ** database transaction is opened. Each time a statement is executed 
87455 ** that causes a foreign key violation, the counter is incremented. Each
87456 ** time a statement is executed that removes an existing violation from
87457 ** the database, the counter is decremented. When the transaction is
87458 ** committed, the commit fails if the current value of the counter is
87459 ** greater than zero. This scheme has two big drawbacks:
87460 **
87461 **   * When a commit fails due to a deferred foreign key constraint, 
87462 **     there is no way to tell which foreign constraint is not satisfied,
87463 **     or which row it is not satisfied for.
87464 **
87465 **   * If the database contains foreign key violations when the 
87466 **     transaction is opened, this may cause the mechanism to malfunction.
87467 **
87468 ** Despite these problems, this approach is adopted as it seems simpler
87469 ** than the alternatives.
87470 **
87471 ** INSERT operations:
87472 **
87473 **   I.1) For each FK for which the table is the child table, search
87474 **        the parent table for a match. If none is found increment the
87475 **        constraint counter.
87476 **
87477 **   I.2) For each FK for which the table is the parent table, 
87478 **        search the child table for rows that correspond to the new
87479 **        row in the parent table. Decrement the counter for each row
87480 **        found (as the constraint is now satisfied).
87481 **
87482 ** DELETE operations:
87483 **
87484 **   D.1) For each FK for which the table is the child table, 
87485 **        search the parent table for a row that corresponds to the 
87486 **        deleted row in the child table. If such a row is not found, 
87487 **        decrement the counter.
87488 **
87489 **   D.2) For each FK for which the table is the parent table, search 
87490 **        the child table for rows that correspond to the deleted row 
87491 **        in the parent table. For each found increment the counter.
87492 **
87493 ** UPDATE operations:
87494 **
87495 **   An UPDATE command requires that all 4 steps above are taken, but only
87496 **   for FK constraints for which the affected columns are actually 
87497 **   modified (values must be compared at runtime).
87498 **
87499 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87500 ** This simplifies the implementation a bit.
87501 **
87502 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
87503 ** resolution is considered to delete rows before the new row is inserted.
87504 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
87505 ** is thrown, even if the FK constraint would be satisfied after the new 
87506 ** row is inserted.
87507 **
87508 ** Immediate constraints are usually handled similarly. The only difference 
87509 ** is that the counter used is stored as part of each individual statement
87510 ** object (struct Vdbe). If, after the statement has run, its immediate
87511 ** constraint counter is greater than zero, it returns SQLCIPHER_CONSTRAINT
87512 ** and the statement transaction is rolled back. An exception is an INSERT
87513 ** statement that inserts a single row only (no triggers). In this case,
87514 ** instead of using a counter, an exception is thrown immediately if the
87515 ** INSERT violates a foreign key constraint. This is necessary as such
87516 ** an INSERT does not open a statement transaction.
87517 **
87518 ** TODO: How should dropping a table be handled? How should renaming a 
87519 ** table be handled?
87520 **
87521 **
87522 ** Query API Notes
87523 ** ---------------
87524 **
87525 ** Before coding an UPDATE or DELETE row operation, the code-generator
87526 ** for those two operations needs to know whether or not the operation
87527 ** requires any FK processing and, if so, which columns of the original
87528 ** row are required by the FK processing VDBE code (i.e. if FKs were
87529 ** implemented using triggers, which of the old.* columns would be 
87530 ** accessed). No information is required by the code-generator before
87531 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
87532 ** generation code to query for this information are:
87533 **
87534 **   sqlcipher3FkRequired() - Test to see if FK processing is required.
87535 **   sqlcipher3FkOldmask()  - Query for the set of required old.* columns.
87536 **
87537 **
87538 ** Externally accessible module functions
87539 ** --------------------------------------
87540 **
87541 **   sqlcipher3FkCheck()    - Check for foreign key violations.
87542 **   sqlcipher3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87543 **   sqlcipher3FkDelete()   - Delete an FKey structure.
87544 */
87545
87546 /*
87547 ** VDBE Calling Convention
87548 ** -----------------------
87549 **
87550 ** Example:
87551 **
87552 **   For the following INSERT statement:
87553 **
87554 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87555 **     INSERT INTO t1 VALUES(1, 2, 3.1);
87556 **
87557 **   Register (x):        2    (type integer)
87558 **   Register (x+1):      1    (type integer)
87559 **   Register (x+2):      NULL (type NULL)
87560 **   Register (x+3):      3.1  (type real)
87561 */
87562
87563 /*
87564 ** A foreign key constraint requires that the key columns in the parent
87565 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87566 ** Given that pParent is the parent table for foreign key constraint pFKey, 
87567 ** search the schema a unique index on the parent key columns. 
87568 **
87569 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
87570 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
87571 ** is set to point to the unique index. 
87572 ** 
87573 ** If the parent key consists of a single column (the foreign key constraint
87574 ** is not a composite foreign key), output variable *paiCol is set to NULL.
87575 ** Otherwise, it is set to point to an allocated array of size N, where
87576 ** N is the number of columns in the parent key. The first element of the
87577 ** array is the index of the child table column that is mapped by the FK
87578 ** constraint to the parent table column stored in the left-most column
87579 ** of index *ppIdx. The second element of the array is the index of the
87580 ** child table column that corresponds to the second left-most column of
87581 ** *ppIdx, and so on.
87582 **
87583 ** If the required index cannot be found, either because:
87584 **
87585 **   1) The named parent key columns do not exist, or
87586 **
87587 **   2) The named parent key columns do exist, but are not subject to a
87588 **      UNIQUE or PRIMARY KEY constraint, or
87589 **
87590 **   3) No parent key columns were provided explicitly as part of the
87591 **      foreign key definition, and the parent table does not have a
87592 **      PRIMARY KEY, or
87593 **
87594 **   4) No parent key columns were provided explicitly as part of the
87595 **      foreign key definition, and the PRIMARY KEY of the parent table 
87596 **      consists of a a different number of columns to the child key in 
87597 **      the child table.
87598 **
87599 ** then non-zero is returned, and a "foreign key mismatch" error loaded
87600 ** into pParse. If an OOM error occurs, non-zero is returned and the
87601 ** pParse->db->mallocFailed flag is set.
87602 */
87603 static int locateFkeyIndex(
87604   Parse *pParse,                  /* Parse context to store any error in */
87605   Table *pParent,                 /* Parent table of FK constraint pFKey */
87606   FKey *pFKey,                    /* Foreign key to find index for */
87607   Index **ppIdx,                  /* OUT: Unique index on parent table */
87608   int **paiCol                    /* OUT: Map of index columns in pFKey */
87609 ){
87610   Index *pIdx = 0;                    /* Value to return via *ppIdx */
87611   int *aiCol = 0;                     /* Value to return via *paiCol */
87612   int nCol = pFKey->nCol;             /* Number of columns in parent key */
87613   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87614
87615   /* The caller is responsible for zeroing output parameters. */
87616   assert( ppIdx && *ppIdx==0 );
87617   assert( !paiCol || *paiCol==0 );
87618   assert( pParse );
87619
87620   /* If this is a non-composite (single column) foreign key, check if it 
87621   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
87622   ** and *paiCol set to zero and return early. 
87623   **
87624   ** Otherwise, for a composite foreign key (more than one column), allocate
87625   ** space for the aiCol array (returned via output parameter *paiCol).
87626   ** Non-composite foreign keys do not require the aiCol array.
87627   */
87628   if( nCol==1 ){
87629     /* The FK maps to the IPK if any of the following are true:
87630     **
87631     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
87632     **      mapped to the primary key of table pParent, or
87633     **   2) The FK is explicitly mapped to a column declared as INTEGER
87634     **      PRIMARY KEY.
87635     */
87636     if( pParent->iPKey>=0 ){
87637       if( !zKey ) return 0;
87638       if( !sqlcipher3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87639     }
87640   }else if( paiCol ){
87641     assert( nCol>1 );
87642     aiCol = (int *)sqlcipher3DbMallocRaw(pParse->db, nCol*sizeof(int));
87643     if( !aiCol ) return 1;
87644     *paiCol = aiCol;
87645   }
87646
87647   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87648     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
87649       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87650       ** of columns. If each indexed column corresponds to a foreign key
87651       ** column of pFKey, then this index is a winner.  */
87652
87653       if( zKey==0 ){
87654         /* If zKey is NULL, then this foreign key is implicitly mapped to 
87655         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
87656         ** identified by the test (Index.autoIndex==2).  */
87657         if( pIdx->autoIndex==2 ){
87658           if( aiCol ){
87659             int i;
87660             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87661           }
87662           break;
87663         }
87664       }else{
87665         /* If zKey is non-NULL, then this foreign key was declared to
87666         ** map to an explicit list of columns in table pParent. Check if this
87667         ** index matches those columns. Also, check that the index uses
87668         ** the default collation sequences for each column. */
87669         int i, j;
87670         for(i=0; i<nCol; i++){
87671           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
87672           char *zDfltColl;                  /* Def. collation for column */
87673           char *zIdxCol;                    /* Name of indexed column */
87674
87675           /* If the index uses a collation sequence that is different from
87676           ** the default collation sequence for the column, this index is
87677           ** unusable. Bail out early in this case.  */
87678           zDfltColl = pParent->aCol[iCol].zColl;
87679           if( !zDfltColl ){
87680             zDfltColl = "BINARY";
87681           }
87682           if( sqlcipher3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
87683
87684           zIdxCol = pParent->aCol[iCol].zName;
87685           for(j=0; j<nCol; j++){
87686             if( sqlcipher3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
87687               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
87688               break;
87689             }
87690           }
87691           if( j==nCol ) break;
87692         }
87693         if( i==nCol ) break;      /* pIdx is usable */
87694       }
87695     }
87696   }
87697
87698   if( !pIdx ){
87699     if( !pParse->disableTriggers ){
87700       sqlcipher3ErrorMsg(pParse, "foreign key mismatch");
87701     }
87702     sqlcipher3DbFree(pParse->db, aiCol);
87703     return 1;
87704   }
87705
87706   *ppIdx = pIdx;
87707   return 0;
87708 }
87709
87710 /*
87711 ** This function is called when a row is inserted into or deleted from the 
87712 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
87713 ** on the child table of pFKey, this function is invoked twice for each row
87714 ** affected - once to "delete" the old row, and then again to "insert" the
87715 ** new row.
87716 **
87717 ** Each time it is called, this function generates VDBE code to locate the
87718 ** row in the parent table that corresponds to the row being inserted into 
87719 ** or deleted from the child table. If the parent row can be found, no 
87720 ** special action is taken. Otherwise, if the parent row can *not* be
87721 ** found in the parent table:
87722 **
87723 **   Operation | FK type   | Action taken
87724 **   --------------------------------------------------------------------------
87725 **   INSERT      immediate   Increment the "immediate constraint counter".
87726 **
87727 **   DELETE      immediate   Decrement the "immediate constraint counter".
87728 **
87729 **   INSERT      deferred    Increment the "deferred constraint counter".
87730 **
87731 **   DELETE      deferred    Decrement the "deferred constraint counter".
87732 **
87733 ** These operations are identified in the comment at the top of this file 
87734 ** (fkey.c) as "I.1" and "D.1".
87735 */
87736 static void fkLookupParent(
87737   Parse *pParse,        /* Parse context */
87738   int iDb,              /* Index of database housing pTab */
87739   Table *pTab,          /* Parent table of FK pFKey */
87740   Index *pIdx,          /* Unique index on parent key columns in pTab */
87741   FKey *pFKey,          /* Foreign key constraint */
87742   int *aiCol,           /* Map from parent key columns to child table columns */
87743   int regData,          /* Address of array containing child table row */
87744   int nIncr,            /* Increment constraint counter by this */
87745   int isIgnore          /* If true, pretend pTab contains all NULL values */
87746 ){
87747   int i;                                    /* Iterator variable */
87748   Vdbe *v = sqlcipher3GetVdbe(pParse);         /* Vdbe to add code to */
87749   int iCur = pParse->nTab - 1;              /* Cursor number to use */
87750   int iOk = sqlcipher3VdbeMakeLabel(v);        /* jump here if parent key found */
87751
87752   /* If nIncr is less than zero, then check at runtime if there are any
87753   ** outstanding constraints to resolve. If there are not, there is no need
87754   ** to check if deleting this row resolves any outstanding violations.
87755   **
87756   ** Check if any of the key columns in the child table row are NULL. If 
87757   ** any are, then the constraint is considered satisfied. No need to 
87758   ** search for a matching row in the parent table.  */
87759   if( nIncr<0 ){
87760     sqlcipher3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
87761   }
87762   for(i=0; i<pFKey->nCol; i++){
87763     int iReg = aiCol[i] + regData + 1;
87764     sqlcipher3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
87765   }
87766
87767   if( isIgnore==0 ){
87768     if( pIdx==0 ){
87769       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
87770       ** column of the parent table (table pTab).  */
87771       int iMustBeInt;               /* Address of MustBeInt instruction */
87772       int regTemp = sqlcipher3GetTempReg(pParse);
87773   
87774       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
87775       ** apply the affinity of the parent key). If this fails, then there
87776       ** is no matching parent key. Before using MustBeInt, make a copy of
87777       ** the value. Otherwise, the value inserted into the child key column
87778       ** will have INTEGER affinity applied to it, which may not be correct.  */
87779       sqlcipher3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
87780       iMustBeInt = sqlcipher3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
87781   
87782       /* If the parent table is the same as the child table, and we are about
87783       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87784       ** then check if the row being inserted matches itself. If so, do not
87785       ** increment the constraint-counter.  */
87786       if( pTab==pFKey->pFrom && nIncr==1 ){
87787         sqlcipher3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
87788       }
87789   
87790       sqlcipher3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
87791       sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
87792       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iOk);
87793       sqlcipher3VdbeJumpHere(v, sqlcipher3VdbeCurrentAddr(v)-2);
87794       sqlcipher3VdbeJumpHere(v, iMustBeInt);
87795       sqlcipher3ReleaseTempReg(pParse, regTemp);
87796     }else{
87797       int nCol = pFKey->nCol;
87798       int regTemp = sqlcipher3GetTempRange(pParse, nCol);
87799       int regRec = sqlcipher3GetTempReg(pParse);
87800       KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
87801   
87802       sqlcipher3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
87803       sqlcipher3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
87804       for(i=0; i<nCol; i++){
87805         sqlcipher3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
87806       }
87807   
87808       /* If the parent table is the same as the child table, and we are about
87809       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87810       ** then check if the row being inserted matches itself. If so, do not
87811       ** increment the constraint-counter. 
87812       **
87813       ** If any of the parent-key values are NULL, then the row cannot match 
87814       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
87815       ** of the parent-key values are NULL (at this point it is known that
87816       ** none of the child key values are).
87817       */
87818       if( pTab==pFKey->pFrom && nIncr==1 ){
87819         int iJump = sqlcipher3VdbeCurrentAddr(v) + nCol + 1;
87820         for(i=0; i<nCol; i++){
87821           int iChild = aiCol[i]+1+regData;
87822           int iParent = pIdx->aiColumn[i]+1+regData;
87823           assert( aiCol[i]!=pTab->iPKey );
87824           if( pIdx->aiColumn[i]==pTab->iPKey ){
87825             /* The parent key is a composite key that includes the IPK column */
87826             iParent = regData;
87827           }
87828           sqlcipher3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
87829           sqlcipher3VdbeChangeP5(v, SQLCIPHER_JUMPIFNULL);
87830         }
87831         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iOk);
87832       }
87833   
87834       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
87835       sqlcipher3VdbeChangeP4(v, -1, sqlcipher3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
87836       sqlcipher3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
87837   
87838       sqlcipher3ReleaseTempReg(pParse, regRec);
87839       sqlcipher3ReleaseTempRange(pParse, regTemp, nCol);
87840     }
87841   }
87842
87843   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
87844     /* Special case: If this is an INSERT statement that will insert exactly
87845     ** one row into the table, raise a constraint immediately instead of
87846     ** incrementing a counter. This is necessary as the VM code is being
87847     ** generated for will not open a statement transaction.  */
87848     assert( nIncr==1 );
87849     sqlcipher3HaltConstraint(
87850         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
87851     );
87852   }else{
87853     if( nIncr>0 && pFKey->isDeferred==0 ){
87854       sqlcipher3ParseToplevel(pParse)->mayAbort = 1;
87855     }
87856     sqlcipher3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87857   }
87858
87859   sqlcipher3VdbeResolveLabel(v, iOk);
87860   sqlcipher3VdbeAddOp1(v, OP_Close, iCur);
87861 }
87862
87863 /*
87864 ** This function is called to generate code executed when a row is deleted
87865 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
87866 ** deferred, when a row is inserted into the same table. When generating
87867 ** code for an SQL UPDATE operation, this function may be called twice -
87868 ** once to "delete" the old row and once to "insert" the new row.
87869 **
87870 ** The code generated by this function scans through the rows in the child
87871 ** table that correspond to the parent table row being deleted or inserted.
87872 ** For each child row found, one of the following actions is taken:
87873 **
87874 **   Operation | FK type   | Action taken
87875 **   --------------------------------------------------------------------------
87876 **   DELETE      immediate   Increment the "immediate constraint counter".
87877 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87878 **                           throw a "foreign key constraint failed" exception.
87879 **
87880 **   INSERT      immediate   Decrement the "immediate constraint counter".
87881 **
87882 **   DELETE      deferred    Increment the "deferred constraint counter".
87883 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87884 **                           throw a "foreign key constraint failed" exception.
87885 **
87886 **   INSERT      deferred    Decrement the "deferred constraint counter".
87887 **
87888 ** These operations are identified in the comment at the top of this file 
87889 ** (fkey.c) as "I.2" and "D.2".
87890 */
87891 static void fkScanChildren(
87892   Parse *pParse,                  /* Parse context */
87893   SrcList *pSrc,                  /* SrcList containing the table to scan */
87894   Table *pTab,
87895   Index *pIdx,                    /* Foreign key index */
87896   FKey *pFKey,                    /* Foreign key relationship */
87897   int *aiCol,                     /* Map from pIdx cols to child table cols */
87898   int regData,                    /* Referenced table data starts here */
87899   int nIncr                       /* Amount to increment deferred counter by */
87900 ){
87901   sqlcipher3 *db = pParse->db;       /* Database handle */
87902   int i;                          /* Iterator variable */
87903   Expr *pWhere = 0;               /* WHERE clause to scan with */
87904   NameContext sNameContext;       /* Context used to resolve WHERE clause */
87905   WhereInfo *pWInfo;              /* Context used by sqlcipher3WhereXXX() */
87906   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
87907   Vdbe *v = sqlcipher3GetVdbe(pParse);
87908
87909   assert( !pIdx || pIdx->pTable==pTab );
87910
87911   if( nIncr<0 ){
87912     iFkIfZero = sqlcipher3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
87913   }
87914
87915   /* Create an Expr object representing an SQL expression like:
87916   **
87917   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
87918   **
87919   ** The collation sequence used for the comparison should be that of
87920   ** the parent key columns. The affinity of the parent key column should
87921   ** be applied to each child key value before the comparison takes place.
87922   */
87923   for(i=0; i<pFKey->nCol; i++){
87924     Expr *pLeft;                  /* Value from parent table row */
87925     Expr *pRight;                 /* Column ref to child table */
87926     Expr *pEq;                    /* Expression (pLeft = pRight) */
87927     int iCol;                     /* Index of column in child table */ 
87928     const char *zCol;             /* Name of column in child table */
87929
87930     pLeft = sqlcipher3Expr(db, TK_REGISTER, 0);
87931     if( pLeft ){
87932       /* Set the collation sequence and affinity of the LHS of each TK_EQ
87933       ** expression to the parent key column defaults.  */
87934       if( pIdx ){
87935         Column *pCol;
87936         iCol = pIdx->aiColumn[i];
87937         pCol = &pTab->aCol[iCol];
87938         if( pTab->iPKey==iCol ) iCol = -1;
87939         pLeft->iTable = regData+iCol+1;
87940         pLeft->affinity = pCol->affinity;
87941         pLeft->pColl = sqlcipher3LocateCollSeq(pParse, pCol->zColl);
87942       }else{
87943         pLeft->iTable = regData;
87944         pLeft->affinity = SQLCIPHER_AFF_INTEGER;
87945       }
87946     }
87947     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
87948     assert( iCol>=0 );
87949     zCol = pFKey->pFrom->aCol[iCol].zName;
87950     pRight = sqlcipher3Expr(db, TK_ID, zCol);
87951     pEq = sqlcipher3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
87952     pWhere = sqlcipher3ExprAnd(db, pWhere, pEq);
87953   }
87954
87955   /* If the child table is the same as the parent table, and this scan
87956   ** is taking place as part of a DELETE operation (operation D.2), omit the
87957   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
87958   ** clause, where $rowid is the rowid of the row being deleted.  */
87959   if( pTab==pFKey->pFrom && nIncr>0 ){
87960     Expr *pEq;                    /* Expression (pLeft = pRight) */
87961     Expr *pLeft;                  /* Value from parent table row */
87962     Expr *pRight;                 /* Column ref to child table */
87963     pLeft = sqlcipher3Expr(db, TK_REGISTER, 0);
87964     pRight = sqlcipher3Expr(db, TK_COLUMN, 0);
87965     if( pLeft && pRight ){
87966       pLeft->iTable = regData;
87967       pLeft->affinity = SQLCIPHER_AFF_INTEGER;
87968       pRight->iTable = pSrc->a[0].iCursor;
87969       pRight->iColumn = -1;
87970     }
87971     pEq = sqlcipher3PExpr(pParse, TK_NE, pLeft, pRight, 0);
87972     pWhere = sqlcipher3ExprAnd(db, pWhere, pEq);
87973   }
87974
87975   /* Resolve the references in the WHERE clause. */
87976   memset(&sNameContext, 0, sizeof(NameContext));
87977   sNameContext.pSrcList = pSrc;
87978   sNameContext.pParse = pParse;
87979   sqlcipher3ResolveExprNames(&sNameContext, pWhere);
87980
87981   /* Create VDBE to loop through the entries in pSrc that match the WHERE
87982   ** clause. If the constraint is not deferred, throw an exception for
87983   ** each row found. Otherwise, for deferred constraints, increment the
87984   ** deferred constraint counter by nIncr for each row selected.  */
87985   pWInfo = sqlcipher3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
87986   if( nIncr>0 && pFKey->isDeferred==0 ){
87987     sqlcipher3ParseToplevel(pParse)->mayAbort = 1;
87988   }
87989   sqlcipher3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87990   if( pWInfo ){
87991     sqlcipher3WhereEnd(pWInfo);
87992   }
87993
87994   /* Clean up the WHERE clause constructed above. */
87995   sqlcipher3ExprDelete(db, pWhere);
87996   if( iFkIfZero ){
87997     sqlcipher3VdbeJumpHere(v, iFkIfZero);
87998   }
87999 }
88000
88001 /*
88002 ** This function returns a pointer to the head of a linked list of FK
88003 ** constraints for which table pTab is the parent table. For example,
88004 ** given the following schema:
88005 **
88006 **   CREATE TABLE t1(a PRIMARY KEY);
88007 **   CREATE TABLE t2(b REFERENCES t1(a);
88008 **
88009 ** Calling this function with table "t1" as an argument returns a pointer
88010 ** to the FKey structure representing the foreign key constraint on table
88011 ** "t2". Calling this function with "t2" as the argument would return a
88012 ** NULL pointer (as there are no FK constraints for which t2 is the parent
88013 ** table).
88014 */
88015 SQLCIPHER_PRIVATE FKey *sqlcipher3FkReferences(Table *pTab){
88016   int nName = sqlcipher3Strlen30(pTab->zName);
88017   return (FKey *)sqlcipher3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
88018 }
88019
88020 /*
88021 ** The second argument is a Trigger structure allocated by the 
88022 ** fkActionTrigger() routine. This function deletes the Trigger structure
88023 ** and all of its sub-components.
88024 **
88025 ** The Trigger structure or any of its sub-components may be allocated from
88026 ** the lookaside buffer belonging to database handle dbMem.
88027 */
88028 static void fkTriggerDelete(sqlcipher3 *dbMem, Trigger *p){
88029   if( p ){
88030     TriggerStep *pStep = p->step_list;
88031     sqlcipher3ExprDelete(dbMem, pStep->pWhere);
88032     sqlcipher3ExprListDelete(dbMem, pStep->pExprList);
88033     sqlcipher3SelectDelete(dbMem, pStep->pSelect);
88034     sqlcipher3ExprDelete(dbMem, p->pWhen);
88035     sqlcipher3DbFree(dbMem, p);
88036   }
88037 }
88038
88039 /*
88040 ** This function is called to generate code that runs when table pTab is
88041 ** being dropped from the database. The SrcList passed as the second argument
88042 ** to this function contains a single entry guaranteed to resolve to
88043 ** table pTab.
88044 **
88045 ** Normally, no code is required. However, if either
88046 **
88047 **   (a) The table is the parent table of a FK constraint, or
88048 **   (b) The table is the child table of a deferred FK constraint and it is
88049 **       determined at runtime that there are outstanding deferred FK 
88050 **       constraint violations in the database,
88051 **
88052 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88053 ** the table from the database. Triggers are disabled while running this
88054 ** DELETE, but foreign key actions are not.
88055 */
88056 SQLCIPHER_PRIVATE void sqlcipher3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88057   sqlcipher3 *db = pParse->db;
88058   if( (db->flags&SQLCIPHER_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88059     int iSkip = 0;
88060     Vdbe *v = sqlcipher3GetVdbe(pParse);
88061
88062     assert( v );                  /* VDBE has already been allocated */
88063     if( sqlcipher3FkReferences(pTab)==0 ){
88064       /* Search for a deferred foreign key constraint for which this table
88065       ** is the child table. If one cannot be found, return without 
88066       ** generating any VDBE code. If one can be found, then jump over
88067       ** the entire DELETE if there are no outstanding deferred constraints
88068       ** when this statement is run.  */
88069       FKey *p;
88070       for(p=pTab->pFKey; p; p=p->pNextFrom){
88071         if( p->isDeferred ) break;
88072       }
88073       if( !p ) return;
88074       iSkip = sqlcipher3VdbeMakeLabel(v);
88075       sqlcipher3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88076     }
88077
88078     pParse->disableTriggers = 1;
88079     sqlcipher3DeleteFrom(pParse, sqlcipher3SrcListDup(db, pName, 0), 0);
88080     pParse->disableTriggers = 0;
88081
88082     /* If the DELETE has generated immediate foreign key constraint 
88083     ** violations, halt the VDBE and return an error at this point, before
88084     ** any modifications to the schema are made. This is because statement
88085     ** transactions are not able to rollback schema changes.  */
88086     sqlcipher3VdbeAddOp2(v, OP_FkIfZero, 0, sqlcipher3VdbeCurrentAddr(v)+2);
88087     sqlcipher3HaltConstraint(
88088         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88089     );
88090
88091     if( iSkip ){
88092       sqlcipher3VdbeResolveLabel(v, iSkip);
88093     }
88094   }
88095 }
88096
88097 /*
88098 ** This function is called when inserting, deleting or updating a row of
88099 ** table pTab to generate VDBE code to perform foreign key constraint 
88100 ** processing for the operation.
88101 **
88102 ** For a DELETE operation, parameter regOld is passed the index of the
88103 ** first register in an array of (pTab->nCol+1) registers containing the
88104 ** rowid of the row being deleted, followed by each of the column values
88105 ** of the row being deleted, from left to right. Parameter regNew is passed
88106 ** zero in this case.
88107 **
88108 ** For an INSERT operation, regOld is passed zero and regNew is passed the
88109 ** first register of an array of (pTab->nCol+1) registers containing the new
88110 ** row data.
88111 **
88112 ** For an UPDATE operation, this function is called twice. Once before
88113 ** the original record is deleted from the table using the calling convention
88114 ** described for DELETE. Then again after the original record is deleted
88115 ** but before the new record is inserted using the INSERT convention. 
88116 */
88117 SQLCIPHER_PRIVATE void sqlcipher3FkCheck(
88118   Parse *pParse,                  /* Parse context */
88119   Table *pTab,                    /* Row is being deleted from this table */ 
88120   int regOld,                     /* Previous row data is stored here */
88121   int regNew                      /* New row data is stored here */
88122 ){
88123   sqlcipher3 *db = pParse->db;       /* Database handle */
88124   FKey *pFKey;                    /* Used to iterate through FKs */
88125   int iDb;                        /* Index of database containing pTab */
88126   const char *zDb;                /* Name of database containing pTab */
88127   int isIgnoreErrors = pParse->disableTriggers;
88128
88129   /* Exactly one of regOld and regNew should be non-zero. */
88130   assert( (regOld==0)!=(regNew==0) );
88131
88132   /* If foreign-keys are disabled, this function is a no-op. */
88133   if( (db->flags&SQLCIPHER_ForeignKeys)==0 ) return;
88134
88135   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
88136   zDb = db->aDb[iDb].zName;
88137
88138   /* Loop through all the foreign key constraints for which pTab is the
88139   ** child table (the table that the foreign key definition is part of).  */
88140   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88141     Table *pTo;                   /* Parent table of foreign key pFKey */
88142     Index *pIdx = 0;              /* Index on key columns in pTo */
88143     int *aiFree = 0;
88144     int *aiCol;
88145     int iCol;
88146     int i;
88147     int isIgnore = 0;
88148
88149     /* Find the parent table of this foreign key. Also find a unique index 
88150     ** on the parent key columns in the parent table. If either of these 
88151     ** schema items cannot be located, set an error in pParse and return 
88152     ** early.  */
88153     if( pParse->disableTriggers ){
88154       pTo = sqlcipher3FindTable(db, pFKey->zTo, zDb);
88155     }else{
88156       pTo = sqlcipher3LocateTable(pParse, 0, pFKey->zTo, zDb);
88157     }
88158     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88159       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88160       if( !isIgnoreErrors || db->mallocFailed ) return;
88161       if( pTo==0 ){
88162         /* If isIgnoreErrors is true, then a table is being dropped. In this
88163         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88164         ** before actually dropping it in order to check FK constraints.
88165         ** If the parent table of an FK constraint on the current table is
88166         ** missing, behave as if it is empty. i.e. decrement the relevant
88167         ** FK counter for each row of the current table with non-NULL keys.
88168         */
88169         Vdbe *v = sqlcipher3GetVdbe(pParse);
88170         int iJump = sqlcipher3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88171         for(i=0; i<pFKey->nCol; i++){
88172           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88173           sqlcipher3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88174         }
88175         sqlcipher3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88176       }
88177       continue;
88178     }
88179     assert( pFKey->nCol==1 || (aiFree && pIdx) );
88180
88181     if( aiFree ){
88182       aiCol = aiFree;
88183     }else{
88184       iCol = pFKey->aCol[0].iFrom;
88185       aiCol = &iCol;
88186     }
88187     for(i=0; i<pFKey->nCol; i++){
88188       if( aiCol[i]==pTab->iPKey ){
88189         aiCol[i] = -1;
88190       }
88191 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
88192       /* Request permission to read the parent key columns. If the 
88193       ** authorization callback returns SQLCIPHER_IGNORE, behave as if any
88194       ** values read from the parent table are NULL. */
88195       if( db->xAuth ){
88196         int rcauth;
88197         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88198         rcauth = sqlcipher3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88199         isIgnore = (rcauth==SQLCIPHER_IGNORE);
88200       }
88201 #endif
88202     }
88203
88204     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
88205     ** a cursor to use to search the unique index on the parent key columns 
88206     ** in the parent table.  */
88207     sqlcipher3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88208     pParse->nTab++;
88209
88210     if( regOld!=0 ){
88211       /* A row is being removed from the child table. Search for the parent.
88212       ** If the parent does not exist, removing the child row resolves an 
88213       ** outstanding foreign key constraint violation. */
88214       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88215     }
88216     if( regNew!=0 ){
88217       /* A row is being added to the child table. If a parent row cannot
88218       ** be found, adding the child row has violated the FK constraint. */ 
88219       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88220     }
88221
88222     sqlcipher3DbFree(db, aiFree);
88223   }
88224
88225   /* Loop through all the foreign key constraints that refer to this table */
88226   for(pFKey = sqlcipher3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88227     Index *pIdx = 0;              /* Foreign key index for pFKey */
88228     SrcList *pSrc;
88229     int *aiCol = 0;
88230
88231     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88232       assert( regOld==0 && regNew!=0 );
88233       /* Inserting a single row into a parent table cannot cause an immediate
88234       ** foreign key violation. So do nothing in this case.  */
88235       continue;
88236     }
88237
88238     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88239       if( !isIgnoreErrors || db->mallocFailed ) return;
88240       continue;
88241     }
88242     assert( aiCol || pFKey->nCol==1 );
88243
88244     /* Create a SrcList structure containing a single table (the table 
88245     ** the foreign key that refers to this table is attached to). This
88246     ** is required for the sqlcipher3WhereXXX() interface.  */
88247     pSrc = sqlcipher3SrcListAppend(db, 0, 0, 0);
88248     if( pSrc ){
88249       struct SrcList_item *pItem = pSrc->a;
88250       pItem->pTab = pFKey->pFrom;
88251       pItem->zName = pFKey->pFrom->zName;
88252       pItem->pTab->nRef++;
88253       pItem->iCursor = pParse->nTab++;
88254   
88255       if( regNew!=0 ){
88256         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88257       }
88258       if( regOld!=0 ){
88259         /* If there is a RESTRICT action configured for the current operation
88260         ** on the parent table of this FK, then throw an exception 
88261         ** immediately if the FK constraint is violated, even if this is a
88262         ** deferred trigger. That's what RESTRICT means. To defer checking
88263         ** the constraint, the FK should specify NO ACTION (represented
88264         ** using OE_None). NO ACTION is the default.  */
88265         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88266       }
88267       pItem->zName = 0;
88268       sqlcipher3SrcListDelete(db, pSrc);
88269     }
88270     sqlcipher3DbFree(db, aiCol);
88271   }
88272 }
88273
88274 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88275
88276 /*
88277 ** This function is called before generating code to update or delete a 
88278 ** row contained in table pTab.
88279 */
88280 SQLCIPHER_PRIVATE u32 sqlcipher3FkOldmask(
88281   Parse *pParse,                  /* Parse context */
88282   Table *pTab                     /* Table being modified */
88283 ){
88284   u32 mask = 0;
88285   if( pParse->db->flags&SQLCIPHER_ForeignKeys ){
88286     FKey *p;
88287     int i;
88288     for(p=pTab->pFKey; p; p=p->pNextFrom){
88289       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88290     }
88291     for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
88292       Index *pIdx = 0;
88293       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
88294       if( pIdx ){
88295         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88296       }
88297     }
88298   }
88299   return mask;
88300 }
88301
88302 /*
88303 ** This function is called before generating code to update or delete a 
88304 ** row contained in table pTab. If the operation is a DELETE, then
88305 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88306 ** to an array of size N, where N is the number of columns in table pTab.
88307 ** If the i'th column is not modified by the UPDATE, then the corresponding 
88308 ** entry in the aChange[] array is set to -1. If the column is modified,
88309 ** the value is 0 or greater. Parameter chngRowid is set to true if the
88310 ** UPDATE statement modifies the rowid fields of the table.
88311 **
88312 ** If any foreign key processing will be required, this function returns
88313 ** true. If there is no foreign key related processing, this function 
88314 ** returns false.
88315 */
88316 SQLCIPHER_PRIVATE int sqlcipher3FkRequired(
88317   Parse *pParse,                  /* Parse context */
88318   Table *pTab,                    /* Table being modified */
88319   int *aChange,                   /* Non-NULL for UPDATE operations */
88320   int chngRowid                   /* True for UPDATE that affects rowid */
88321 ){
88322   if( pParse->db->flags&SQLCIPHER_ForeignKeys ){
88323     if( !aChange ){
88324       /* A DELETE operation. Foreign key processing is required if the 
88325       ** table in question is either the child or parent table for any 
88326       ** foreign key constraint.  */
88327       return (sqlcipher3FkReferences(pTab) || pTab->pFKey);
88328     }else{
88329       /* This is an UPDATE. Foreign key processing is only required if the
88330       ** operation modifies one or more child or parent key columns. */
88331       int i;
88332       FKey *p;
88333
88334       /* Check if any child key columns are being modified. */
88335       for(p=pTab->pFKey; p; p=p->pNextFrom){
88336         for(i=0; i<p->nCol; i++){
88337           int iChildKey = p->aCol[i].iFrom;
88338           if( aChange[iChildKey]>=0 ) return 1;
88339           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88340         }
88341       }
88342
88343       /* Check if any parent key columns are being modified. */
88344       for(p=sqlcipher3FkReferences(pTab); p; p=p->pNextTo){
88345         for(i=0; i<p->nCol; i++){
88346           char *zKey = p->aCol[i].zCol;
88347           int iKey;
88348           for(iKey=0; iKey<pTab->nCol; iKey++){
88349             Column *pCol = &pTab->aCol[iKey];
88350             if( (zKey ? !sqlcipher3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
88351               if( aChange[iKey]>=0 ) return 1;
88352               if( iKey==pTab->iPKey && chngRowid ) return 1;
88353             }
88354           }
88355         }
88356       }
88357     }
88358   }
88359   return 0;
88360 }
88361
88362 /*
88363 ** This function is called when an UPDATE or DELETE operation is being 
88364 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
88365 ** If the current operation is an UPDATE, then the pChanges parameter is
88366 ** passed a pointer to the list of columns being modified. If it is a
88367 ** DELETE, pChanges is passed a NULL pointer.
88368 **
88369 ** It returns a pointer to a Trigger structure containing a trigger
88370 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88371 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88372 ** returned (these actions require no special handling by the triggers
88373 ** sub-system, code for them is created by fkScanChildren()).
88374 **
88375 ** For example, if pFKey is the foreign key and pTab is table "p" in 
88376 ** the following schema:
88377 **
88378 **   CREATE TABLE p(pk PRIMARY KEY);
88379 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88380 **
88381 ** then the returned trigger structure is equivalent to:
88382 **
88383 **   CREATE TRIGGER ... DELETE ON p BEGIN
88384 **     DELETE FROM c WHERE ck = old.pk;
88385 **   END;
88386 **
88387 ** The returned pointer is cached as part of the foreign key object. It
88388 ** is eventually freed along with the rest of the foreign key object by 
88389 ** sqlcipher3FkDelete().
88390 */
88391 static Trigger *fkActionTrigger(
88392   Parse *pParse,                  /* Parse context */
88393   Table *pTab,                    /* Table being updated or deleted from */
88394   FKey *pFKey,                    /* Foreign key to get action for */
88395   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88396 ){
88397   sqlcipher3 *db = pParse->db;       /* Database handle */
88398   int action;                     /* One of OE_None, OE_Cascade etc. */
88399   Trigger *pTrigger;              /* Trigger definition to return */
88400   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88401
88402   action = pFKey->aAction[iAction];
88403   pTrigger = pFKey->apTrigger[iAction];
88404
88405   if( action!=OE_None && !pTrigger ){
88406     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88407     char const *zFrom;            /* Name of child table */
88408     int nFrom;                    /* Length in bytes of zFrom */
88409     Index *pIdx = 0;              /* Parent key index for this FK */
88410     int *aiCol = 0;               /* child table cols -> parent key cols */
88411     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88412     Expr *pWhere = 0;             /* WHERE clause of trigger step */
88413     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88414     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88415     int i;                        /* Iterator variable */
88416     Expr *pWhen = 0;              /* WHEN clause for the trigger */
88417
88418     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88419     assert( aiCol || pFKey->nCol==1 );
88420
88421     for(i=0; i<pFKey->nCol; i++){
88422       Token tOld = { "old", 3 };  /* Literal "old" token */
88423       Token tNew = { "new", 3 };  /* Literal "new" token */
88424       Token tFromCol;             /* Name of column in child table */
88425       Token tToCol;               /* Name of column in parent table */
88426       int iFromCol;               /* Idx of column in child table */
88427       Expr *pEq;                  /* tFromCol = OLD.tToCol */
88428
88429       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88430       assert( iFromCol>=0 );
88431       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88432       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88433
88434       tToCol.n = sqlcipher3Strlen30(tToCol.z);
88435       tFromCol.n = sqlcipher3Strlen30(tFromCol.z);
88436
88437       /* Create the expression "OLD.zToCol = zFromCol". It is important
88438       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88439       ** that the affinity and collation sequence associated with the
88440       ** parent table are used for the comparison. */
88441       pEq = sqlcipher3PExpr(pParse, TK_EQ,
88442           sqlcipher3PExpr(pParse, TK_DOT, 
88443             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tOld),
88444             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88445           , 0),
88446           sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88447       , 0);
88448       pWhere = sqlcipher3ExprAnd(db, pWhere, pEq);
88449
88450       /* For ON UPDATE, construct the next term of the WHEN clause.
88451       ** The final WHEN clause will be like this:
88452       **
88453       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88454       */
88455       if( pChanges ){
88456         pEq = sqlcipher3PExpr(pParse, TK_IS,
88457             sqlcipher3PExpr(pParse, TK_DOT, 
88458               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tOld),
88459               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88460               0),
88461             sqlcipher3PExpr(pParse, TK_DOT, 
88462               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tNew),
88463               sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88464               0),
88465             0);
88466         pWhen = sqlcipher3ExprAnd(db, pWhen, pEq);
88467       }
88468   
88469       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88470         Expr *pNew;
88471         if( action==OE_Cascade ){
88472           pNew = sqlcipher3PExpr(pParse, TK_DOT, 
88473             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tNew),
88474             sqlcipher3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88475           , 0);
88476         }else if( action==OE_SetDflt ){
88477           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88478           if( pDflt ){
88479             pNew = sqlcipher3ExprDup(db, pDflt, 0);
88480           }else{
88481             pNew = sqlcipher3PExpr(pParse, TK_NULL, 0, 0, 0);
88482           }
88483         }else{
88484           pNew = sqlcipher3PExpr(pParse, TK_NULL, 0, 0, 0);
88485         }
88486         pList = sqlcipher3ExprListAppend(pParse, pList, pNew);
88487         sqlcipher3ExprListSetName(pParse, pList, &tFromCol, 0);
88488       }
88489     }
88490     sqlcipher3DbFree(db, aiCol);
88491
88492     zFrom = pFKey->pFrom->zName;
88493     nFrom = sqlcipher3Strlen30(zFrom);
88494
88495     if( action==OE_Restrict ){
88496       Token tFrom;
88497       Expr *pRaise; 
88498
88499       tFrom.z = zFrom;
88500       tFrom.n = nFrom;
88501       pRaise = sqlcipher3Expr(db, TK_RAISE, "foreign key constraint failed");
88502       if( pRaise ){
88503         pRaise->affinity = OE_Abort;
88504       }
88505       pSelect = sqlcipher3SelectNew(pParse, 
88506           sqlcipher3ExprListAppend(pParse, 0, pRaise),
88507           sqlcipher3SrcListAppend(db, 0, &tFrom, 0),
88508           pWhere,
88509           0, 0, 0, 0, 0, 0
88510       );
88511       pWhere = 0;
88512     }
88513
88514     /* Disable lookaside memory allocation */
88515     enableLookaside = db->lookaside.bEnabled;
88516     db->lookaside.bEnabled = 0;
88517
88518     pTrigger = (Trigger *)sqlcipher3DbMallocZero(db, 
88519         sizeof(Trigger) +         /* struct Trigger */
88520         sizeof(TriggerStep) +     /* Single step in trigger program */
88521         nFrom + 1                 /* Space for pStep->target.z */
88522     );
88523     if( pTrigger ){
88524       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88525       pStep->target.z = (char *)&pStep[1];
88526       pStep->target.n = nFrom;
88527       memcpy((char *)pStep->target.z, zFrom, nFrom);
88528   
88529       pStep->pWhere = sqlcipher3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88530       pStep->pExprList = sqlcipher3ExprListDup(db, pList, EXPRDUP_REDUCE);
88531       pStep->pSelect = sqlcipher3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88532       if( pWhen ){
88533         pWhen = sqlcipher3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88534         pTrigger->pWhen = sqlcipher3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88535       }
88536     }
88537
88538     /* Re-enable the lookaside buffer, if it was disabled earlier. */
88539     db->lookaside.bEnabled = enableLookaside;
88540
88541     sqlcipher3ExprDelete(db, pWhere);
88542     sqlcipher3ExprDelete(db, pWhen);
88543     sqlcipher3ExprListDelete(db, pList);
88544     sqlcipher3SelectDelete(db, pSelect);
88545     if( db->mallocFailed==1 ){
88546       fkTriggerDelete(db, pTrigger);
88547       return 0;
88548     }
88549     assert( pStep!=0 );
88550
88551     switch( action ){
88552       case OE_Restrict:
88553         pStep->op = TK_SELECT; 
88554         break;
88555       case OE_Cascade: 
88556         if( !pChanges ){ 
88557           pStep->op = TK_DELETE; 
88558           break; 
88559         }
88560       default:
88561         pStep->op = TK_UPDATE;
88562     }
88563     pStep->pTrig = pTrigger;
88564     pTrigger->pSchema = pTab->pSchema;
88565     pTrigger->pTabSchema = pTab->pSchema;
88566     pFKey->apTrigger[iAction] = pTrigger;
88567     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88568   }
88569
88570   return pTrigger;
88571 }
88572
88573 /*
88574 ** This function is called when deleting or updating a row to implement
88575 ** any required CASCADE, SET NULL or SET DEFAULT actions.
88576 */
88577 SQLCIPHER_PRIVATE void sqlcipher3FkActions(
88578   Parse *pParse,                  /* Parse context */
88579   Table *pTab,                    /* Table being updated or deleted from */
88580   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88581   int regOld                      /* Address of array containing old row */
88582 ){
88583   /* If foreign-key support is enabled, iterate through all FKs that 
88584   ** refer to table pTab. If there is an action associated with the FK 
88585   ** for this operation (either update or delete), invoke the associated 
88586   ** trigger sub-program.  */
88587   if( pParse->db->flags&SQLCIPHER_ForeignKeys ){
88588     FKey *pFKey;                  /* Iterator variable */
88589     for(pFKey = sqlcipher3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88590       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88591       if( pAction ){
88592         sqlcipher3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88593       }
88594     }
88595   }
88596 }
88597
88598 #endif /* ifndef SQLCIPHER_OMIT_TRIGGER */
88599
88600 /*
88601 ** Free all memory associated with foreign key definitions attached to
88602 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88603 ** hash table.
88604 */
88605 SQLCIPHER_PRIVATE void sqlcipher3FkDelete(sqlcipher3 *db, Table *pTab){
88606   FKey *pFKey;                    /* Iterator variable */
88607   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88608
88609   assert( db==0 || sqlcipher3SchemaMutexHeld(db, 0, pTab->pSchema) );
88610   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88611
88612     /* Remove the FK from the fkeyHash hash table. */
88613     if( !db || db->pnBytesFreed==0 ){
88614       if( pFKey->pPrevTo ){
88615         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88616       }else{
88617         void *p = (void *)pFKey->pNextTo;
88618         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88619         sqlcipher3HashInsert(&pTab->pSchema->fkeyHash, z, sqlcipher3Strlen30(z), p);
88620       }
88621       if( pFKey->pNextTo ){
88622         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88623       }
88624     }
88625
88626     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88627     ** classified as either immediate or deferred.
88628     */
88629     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88630
88631     /* Delete any triggers created to implement actions for this FK. */
88632 #ifndef SQLCIPHER_OMIT_TRIGGER
88633     fkTriggerDelete(db, pFKey->apTrigger[0]);
88634     fkTriggerDelete(db, pFKey->apTrigger[1]);
88635 #endif
88636
88637     pNext = pFKey->pNextFrom;
88638     sqlcipher3DbFree(db, pFKey);
88639   }
88640 }
88641 #endif /* ifndef SQLCIPHER_OMIT_FOREIGN_KEY */
88642
88643 /************** End of fkey.c ************************************************/
88644 /************** Begin file insert.c ******************************************/
88645 /*
88646 ** 2001 September 15
88647 **
88648 ** The author disclaims copyright to this source code.  In place of
88649 ** a legal notice, here is a blessing:
88650 **
88651 **    May you do good and not evil.
88652 **    May you find forgiveness for yourself and forgive others.
88653 **    May you share freely, never taking more than you give.
88654 **
88655 *************************************************************************
88656 ** This file contains C code routines that are called by the parser
88657 ** to handle INSERT statements in SQLite.
88658 */
88659
88660 /*
88661 ** Generate code that will open a table for reading.
88662 */
88663 SQLCIPHER_PRIVATE void sqlcipher3OpenTable(
88664   Parse *p,       /* Generate code into this VDBE */
88665   int iCur,       /* The cursor number of the table */
88666   int iDb,        /* The database index in sqlcipher3.aDb[] */
88667   Table *pTab,    /* The table to be opened */
88668   int opcode      /* OP_OpenRead or OP_OpenWrite */
88669 ){
88670   Vdbe *v;
88671   if( IsVirtual(pTab) ) return;
88672   v = sqlcipher3GetVdbe(p);
88673   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
88674   sqlcipher3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
88675   sqlcipher3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
88676   sqlcipher3VdbeChangeP4(v, -1, SQLCIPHER_INT_TO_PTR(pTab->nCol), P4_INT32);
88677   VdbeComment((v, "%s", pTab->zName));
88678 }
88679
88680 /*
88681 ** Return a pointer to the column affinity string associated with index
88682 ** pIdx. A column affinity string has one character for each column in 
88683 ** the table, according to the affinity of the column:
88684 **
88685 **  Character      Column affinity
88686 **  ------------------------------
88687 **  'a'            TEXT
88688 **  'b'            NONE
88689 **  'c'            NUMERIC
88690 **  'd'            INTEGER
88691 **  'e'            REAL
88692 **
88693 ** An extra 'b' is appended to the end of the string to cover the
88694 ** rowid that appears as the last column in every index.
88695 **
88696 ** Memory for the buffer containing the column index affinity string
88697 ** is managed along with the rest of the Index structure. It will be
88698 ** released when sqlcipher3DeleteIndex() is called.
88699 */
88700 SQLCIPHER_PRIVATE const char *sqlcipher3IndexAffinityStr(Vdbe *v, Index *pIdx){
88701   if( !pIdx->zColAff ){
88702     /* The first time a column affinity string for a particular index is
88703     ** required, it is allocated and populated here. It is then stored as
88704     ** a member of the Index structure for subsequent use.
88705     **
88706     ** The column affinity string will eventually be deleted by
88707     ** sqlcipherDeleteIndex() when the Index structure itself is cleaned
88708     ** up.
88709     */
88710     int n;
88711     Table *pTab = pIdx->pTable;
88712     sqlcipher3 *db = sqlcipher3VdbeDb(v);
88713     pIdx->zColAff = (char *)sqlcipher3DbMallocRaw(0, pIdx->nColumn+2);
88714     if( !pIdx->zColAff ){
88715       db->mallocFailed = 1;
88716       return 0;
88717     }
88718     for(n=0; n<pIdx->nColumn; n++){
88719       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
88720     }
88721     pIdx->zColAff[n++] = SQLCIPHER_AFF_NONE;
88722     pIdx->zColAff[n] = 0;
88723   }
88724  
88725   return pIdx->zColAff;
88726 }
88727
88728 /*
88729 ** Set P4 of the most recently inserted opcode to a column affinity
88730 ** string for table pTab. A column affinity string has one character
88731 ** for each column indexed by the index, according to the affinity of the
88732 ** column:
88733 **
88734 **  Character      Column affinity
88735 **  ------------------------------
88736 **  'a'            TEXT
88737 **  'b'            NONE
88738 **  'c'            NUMERIC
88739 **  'd'            INTEGER
88740 **  'e'            REAL
88741 */
88742 SQLCIPHER_PRIVATE void sqlcipher3TableAffinityStr(Vdbe *v, Table *pTab){
88743   /* The first time a column affinity string for a particular table
88744   ** is required, it is allocated and populated here. It is then 
88745   ** stored as a member of the Table structure for subsequent use.
88746   **
88747   ** The column affinity string will eventually be deleted by
88748   ** sqlcipher3DeleteTable() when the Table structure itself is cleaned up.
88749   */
88750   if( !pTab->zColAff ){
88751     char *zColAff;
88752     int i;
88753     sqlcipher3 *db = sqlcipher3VdbeDb(v);
88754
88755     zColAff = (char *)sqlcipher3DbMallocRaw(0, pTab->nCol+1);
88756     if( !zColAff ){
88757       db->mallocFailed = 1;
88758       return;
88759     }
88760
88761     for(i=0; i<pTab->nCol; i++){
88762       zColAff[i] = pTab->aCol[i].affinity;
88763     }
88764     zColAff[pTab->nCol] = '\0';
88765
88766     pTab->zColAff = zColAff;
88767   }
88768
88769   sqlcipher3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
88770 }
88771
88772 /*
88773 ** Return non-zero if the table pTab in database iDb or any of its indices
88774 ** have been opened at any point in the VDBE program beginning at location
88775 ** iStartAddr throught the end of the program.  This is used to see if 
88776 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
88777 ** run without using temporary table for the results of the SELECT. 
88778 */
88779 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
88780   Vdbe *v = sqlcipher3GetVdbe(p);
88781   int i;
88782   int iEnd = sqlcipher3VdbeCurrentAddr(v);
88783 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
88784   VTable *pVTab = IsVirtual(pTab) ? sqlcipher3GetVTable(p->db, pTab) : 0;
88785 #endif
88786
88787   for(i=iStartAddr; i<iEnd; i++){
88788     VdbeOp *pOp = sqlcipher3VdbeGetOp(v, i);
88789     assert( pOp!=0 );
88790     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
88791       Index *pIndex;
88792       int tnum = pOp->p2;
88793       if( tnum==pTab->tnum ){
88794         return 1;
88795       }
88796       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
88797         if( tnum==pIndex->tnum ){
88798           return 1;
88799         }
88800       }
88801     }
88802 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
88803     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
88804       assert( pOp->p4.pVtab!=0 );
88805       assert( pOp->p4type==P4_VTAB );
88806       return 1;
88807     }
88808 #endif
88809   }
88810   return 0;
88811 }
88812
88813 #ifndef SQLCIPHER_OMIT_AUTOINCREMENT
88814 /*
88815 ** Locate or create an AutoincInfo structure associated with table pTab
88816 ** which is in database iDb.  Return the register number for the register
88817 ** that holds the maximum rowid.
88818 **
88819 ** There is at most one AutoincInfo structure per table even if the
88820 ** same table is autoincremented multiple times due to inserts within
88821 ** triggers.  A new AutoincInfo structure is created if this is the
88822 ** first use of table pTab.  On 2nd and subsequent uses, the original
88823 ** AutoincInfo structure is used.
88824 **
88825 ** Three memory locations are allocated:
88826 **
88827 **   (1)  Register to hold the name of the pTab table.
88828 **   (2)  Register to hold the maximum ROWID of pTab.
88829 **   (3)  Register to hold the rowid in sqlcipher_sequence of pTab
88830 **
88831 ** The 2nd register is the one that is returned.  That is all the
88832 ** insert routine needs to know about.
88833 */
88834 static int autoIncBegin(
88835   Parse *pParse,      /* Parsing context */
88836   int iDb,            /* Index of the database holding pTab */
88837   Table *pTab         /* The table we are writing to */
88838 ){
88839   int memId = 0;      /* Register holding maximum rowid */
88840   if( pTab->tabFlags & TF_Autoincrement ){
88841     Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
88842     AutoincInfo *pInfo;
88843
88844     pInfo = pToplevel->pAinc;
88845     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
88846     if( pInfo==0 ){
88847       pInfo = sqlcipher3DbMallocRaw(pParse->db, sizeof(*pInfo));
88848       if( pInfo==0 ) return 0;
88849       pInfo->pNext = pToplevel->pAinc;
88850       pToplevel->pAinc = pInfo;
88851       pInfo->pTab = pTab;
88852       pInfo->iDb = iDb;
88853       pToplevel->nMem++;                  /* Register to hold name of table */
88854       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
88855       pToplevel->nMem++;                  /* Rowid in sqlcipher_sequence */
88856     }
88857     memId = pInfo->regCtr;
88858   }
88859   return memId;
88860 }
88861
88862 /*
88863 ** This routine generates code that will initialize all of the
88864 ** register used by the autoincrement tracker.  
88865 */
88866 SQLCIPHER_PRIVATE void sqlcipher3AutoincrementBegin(Parse *pParse){
88867   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
88868   sqlcipher3 *db = pParse->db;  /* The database connection */
88869   Db *pDb;                   /* Database only autoinc table */
88870   int memId;                 /* Register holding max rowid */
88871   int addr;                  /* A VDBE address */
88872   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
88873
88874   /* This routine is never called during trigger-generation.  It is
88875   ** only called from the top-level */
88876   assert( pParse->pTriggerTab==0 );
88877   assert( pParse==sqlcipher3ParseToplevel(pParse) );
88878
88879   assert( v );   /* We failed long ago if this is not so */
88880   for(p = pParse->pAinc; p; p = p->pNext){
88881     pDb = &db->aDb[p->iDb];
88882     memId = p->regCtr;
88883     assert( sqlcipher3SchemaMutexHeld(db, 0, pDb->pSchema) );
88884     sqlcipher3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
88885     addr = sqlcipher3VdbeCurrentAddr(v);
88886     sqlcipher3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
88887     sqlcipher3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
88888     sqlcipher3VdbeAddOp3(v, OP_Column, 0, 0, memId);
88889     sqlcipher3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
88890     sqlcipher3VdbeChangeP5(v, SQLCIPHER_JUMPIFNULL);
88891     sqlcipher3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88892     sqlcipher3VdbeAddOp3(v, OP_Column, 0, 1, memId);
88893     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addr+9);
88894     sqlcipher3VdbeAddOp2(v, OP_Next, 0, addr+2);
88895     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, memId);
88896     sqlcipher3VdbeAddOp0(v, OP_Close);
88897   }
88898 }
88899
88900 /*
88901 ** Update the maximum rowid for an autoincrement calculation.
88902 **
88903 ** This routine should be called when the top of the stack holds a
88904 ** new rowid that is about to be inserted.  If that new rowid is
88905 ** larger than the maximum rowid in the memId memory cell, then the
88906 ** memory cell is updated.  The stack is unchanged.
88907 */
88908 static void autoIncStep(Parse *pParse, int memId, int regRowid){
88909   if( memId>0 ){
88910     sqlcipher3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
88911   }
88912 }
88913
88914 /*
88915 ** This routine generates the code needed to write autoincrement
88916 ** maximum rowid values back into the sqlcipher_sequence register.
88917 ** Every statement that might do an INSERT into an autoincrement
88918 ** table (either directly or through triggers) needs to call this
88919 ** routine just before the "exit" code.
88920 */
88921 SQLCIPHER_PRIVATE void sqlcipher3AutoincrementEnd(Parse *pParse){
88922   AutoincInfo *p;
88923   Vdbe *v = pParse->pVdbe;
88924   sqlcipher3 *db = pParse->db;
88925
88926   assert( v );
88927   for(p = pParse->pAinc; p; p = p->pNext){
88928     Db *pDb = &db->aDb[p->iDb];
88929     int j1, j2, j3, j4, j5;
88930     int iRec;
88931     int memId = p->regCtr;
88932
88933     iRec = sqlcipher3GetTempReg(pParse);
88934     assert( sqlcipher3SchemaMutexHeld(db, 0, pDb->pSchema) );
88935     sqlcipher3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
88936     j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, memId+1);
88937     j2 = sqlcipher3VdbeAddOp0(v, OP_Rewind);
88938     j3 = sqlcipher3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
88939     j4 = sqlcipher3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
88940     sqlcipher3VdbeAddOp2(v, OP_Next, 0, j3);
88941     sqlcipher3VdbeJumpHere(v, j2);
88942     sqlcipher3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
88943     j5 = sqlcipher3VdbeAddOp0(v, OP_Goto);
88944     sqlcipher3VdbeJumpHere(v, j4);
88945     sqlcipher3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88946     sqlcipher3VdbeJumpHere(v, j1);
88947     sqlcipher3VdbeJumpHere(v, j5);
88948     sqlcipher3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
88949     sqlcipher3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
88950     sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
88951     sqlcipher3VdbeAddOp0(v, OP_Close);
88952     sqlcipher3ReleaseTempReg(pParse, iRec);
88953   }
88954 }
88955 #else
88956 /*
88957 ** If SQLCIPHER_OMIT_AUTOINCREMENT is defined, then the three routines
88958 ** above are all no-ops
88959 */
88960 # define autoIncBegin(A,B,C) (0)
88961 # define autoIncStep(A,B,C)
88962 #endif /* SQLCIPHER_OMIT_AUTOINCREMENT */
88963
88964
88965 /* Forward declaration */
88966 static int xferOptimization(
88967   Parse *pParse,        /* Parser context */
88968   Table *pDest,         /* The table we are inserting into */
88969   Select *pSelect,      /* A SELECT statement to use as the data source */
88970   int onError,          /* How to handle constraint errors */
88971   int iDbDest           /* The database of pDest */
88972 );
88973
88974 /*
88975 ** This routine is call to handle SQL of the following forms:
88976 **
88977 **    insert into TABLE (IDLIST) values(EXPRLIST)
88978 **    insert into TABLE (IDLIST) select
88979 **
88980 ** The IDLIST following the table name is always optional.  If omitted,
88981 ** then a list of all columns for the table is substituted.  The IDLIST
88982 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
88983 **
88984 ** The pList parameter holds EXPRLIST in the first form of the INSERT
88985 ** statement above, and pSelect is NULL.  For the second form, pList is
88986 ** NULL and pSelect is a pointer to the select statement used to generate
88987 ** data for the insert.
88988 **
88989 ** The code generated follows one of four templates.  For a simple
88990 ** select with data coming from a VALUES clause, the code executes
88991 ** once straight down through.  Pseudo-code follows (we call this
88992 ** the "1st template"):
88993 **
88994 **         open write cursor to <table> and its indices
88995 **         puts VALUES clause expressions onto the stack
88996 **         write the resulting record into <table>
88997 **         cleanup
88998 **
88999 ** The three remaining templates assume the statement is of the form
89000 **
89001 **   INSERT INTO <table> SELECT ...
89002 **
89003 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
89004 ** in other words if the SELECT pulls all columns from a single table
89005 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
89006 ** if <table2> and <table1> are distinct tables but have identical
89007 ** schemas, including all the same indices, then a special optimization
89008 ** is invoked that copies raw records from <table2> over to <table1>.
89009 ** See the xferOptimization() function for the implementation of this
89010 ** template.  This is the 2nd template.
89011 **
89012 **         open a write cursor to <table>
89013 **         open read cursor on <table2>
89014 **         transfer all records in <table2> over to <table>
89015 **         close cursors
89016 **         foreach index on <table>
89017 **           open a write cursor on the <table> index
89018 **           open a read cursor on the corresponding <table2> index
89019 **           transfer all records from the read to the write cursors
89020 **           close cursors
89021 **         end foreach
89022 **
89023 ** The 3rd template is for when the second template does not apply
89024 ** and the SELECT clause does not read from <table> at any time.
89025 ** The generated code follows this template:
89026 **
89027 **         EOF <- 0
89028 **         X <- A
89029 **         goto B
89030 **      A: setup for the SELECT
89031 **         loop over the rows in the SELECT
89032 **           load values into registers R..R+n
89033 **           yield X
89034 **         end loop
89035 **         cleanup after the SELECT
89036 **         EOF <- 1
89037 **         yield X
89038 **         goto A
89039 **      B: open write cursor to <table> and its indices
89040 **      C: yield X
89041 **         if EOF goto D
89042 **         insert the select result into <table> from R..R+n
89043 **         goto C
89044 **      D: cleanup
89045 **
89046 ** The 4th template is used if the insert statement takes its
89047 ** values from a SELECT but the data is being inserted into a table
89048 ** that is also read as part of the SELECT.  In the third form,
89049 ** we have to use a intermediate table to store the results of
89050 ** the select.  The template is like this:
89051 **
89052 **         EOF <- 0
89053 **         X <- A
89054 **         goto B
89055 **      A: setup for the SELECT
89056 **         loop over the tables in the SELECT
89057 **           load value into register R..R+n
89058 **           yield X
89059 **         end loop
89060 **         cleanup after the SELECT
89061 **         EOF <- 1
89062 **         yield X
89063 **         halt-error
89064 **      B: open temp table
89065 **      L: yield X
89066 **         if EOF goto M
89067 **         insert row from R..R+n into temp table
89068 **         goto L
89069 **      M: open write cursor to <table> and its indices
89070 **         rewind temp table
89071 **      C: loop over rows of intermediate table
89072 **           transfer values form intermediate table into <table>
89073 **         end loop
89074 **      D: cleanup
89075 */
89076 SQLCIPHER_PRIVATE void sqlcipher3Insert(
89077   Parse *pParse,        /* Parser context */
89078   SrcList *pTabList,    /* Name of table into which we are inserting */
89079   ExprList *pList,      /* List of values to be inserted */
89080   Select *pSelect,      /* A SELECT statement to use as the data source */
89081   IdList *pColumn,      /* Column names corresponding to IDLIST. */
89082   int onError           /* How to handle constraint errors */
89083 ){
89084   sqlcipher3 *db;          /* The main database structure */
89085   Table *pTab;          /* The table to insert into.  aka TABLE */
89086   char *zTab;           /* Name of the table into which we are inserting */
89087   const char *zDb;      /* Name of the database holding this table */
89088   int i, j, idx;        /* Loop counters */
89089   Vdbe *v;              /* Generate code into this virtual machine */
89090   Index *pIdx;          /* For looping over indices of the table */
89091   int nColumn;          /* Number of columns in the data */
89092   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89093   int baseCur = 0;      /* VDBE Cursor number for pTab */
89094   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89095   int endOfLoop;        /* Label for the end of the insertion loop */
89096   int useTempTable = 0; /* Store SELECT results in intermediate table */
89097   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89098   int addrInsTop = 0;   /* Jump to label "D" */
89099   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89100   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89101   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89102   int iDb;              /* Index of database holding TABLE */
89103   Db *pDb;              /* The database containing table being inserted into */
89104   int appendFlag = 0;   /* True if the insert is likely to be an append */
89105
89106   /* Register allocations */
89107   int regFromSelect = 0;/* Base register for data coming from SELECT */
89108   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89109   int regRowCount = 0;  /* Memory cell used for the row counter */
89110   int regIns;           /* Block of regs holding rowid+data being inserted */
89111   int regRowid;         /* registers holding insert rowid */
89112   int regData;          /* register holding first column to insert */
89113   int regEof = 0;       /* Register recording end of SELECT data */
89114   int *aRegIdx = 0;     /* One register allocated to each index */
89115
89116 #ifndef SQLCIPHER_OMIT_TRIGGER
89117   int isView;                 /* True if attempting to insert into a view */
89118   Trigger *pTrigger;          /* List of triggers on pTab, if required */
89119   int tmask;                  /* Mask of trigger times */
89120 #endif
89121
89122   db = pParse->db;
89123   memset(&dest, 0, sizeof(dest));
89124   if( pParse->nErr || db->mallocFailed ){
89125     goto insert_cleanup;
89126   }
89127
89128   /* Locate the table into which we will be inserting new information.
89129   */
89130   assert( pTabList->nSrc==1 );
89131   zTab = pTabList->a[0].zName;
89132   if( NEVER(zTab==0) ) goto insert_cleanup;
89133   pTab = sqlcipher3SrcListLookup(pParse, pTabList);
89134   if( pTab==0 ){
89135     goto insert_cleanup;
89136   }
89137   iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
89138   assert( iDb<db->nDb );
89139   pDb = &db->aDb[iDb];
89140   zDb = pDb->zName;
89141   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, pTab->zName, 0, zDb) ){
89142     goto insert_cleanup;
89143   }
89144
89145   /* Figure out if we have any triggers and if the table being
89146   ** inserted into is a view
89147   */
89148 #ifndef SQLCIPHER_OMIT_TRIGGER
89149   pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89150   isView = pTab->pSelect!=0;
89151 #else
89152 # define pTrigger 0
89153 # define tmask 0
89154 # define isView 0
89155 #endif
89156 #ifdef SQLCIPHER_OMIT_VIEW
89157 # undef isView
89158 # define isView 0
89159 #endif
89160   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89161
89162   /* If pTab is really a view, make sure it has been initialized.
89163   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
89164   ** module table).
89165   */
89166   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
89167     goto insert_cleanup;
89168   }
89169
89170   /* Ensure that:
89171   *  (a) the table is not read-only, 
89172   *  (b) that if it is a view then ON INSERT triggers exist
89173   */
89174   if( sqlcipher3IsReadOnly(pParse, pTab, tmask) ){
89175     goto insert_cleanup;
89176   }
89177
89178   /* Allocate a VDBE
89179   */
89180   v = sqlcipher3GetVdbe(pParse);
89181   if( v==0 ) goto insert_cleanup;
89182   if( pParse->nested==0 ) sqlcipher3VdbeCountChanges(v);
89183   sqlcipher3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89184
89185 #ifndef SQLCIPHER_OMIT_XFER_OPT
89186   /* If the statement is of the form
89187   **
89188   **       INSERT INTO <table1> SELECT * FROM <table2>;
89189   **
89190   ** Then special optimizations can be applied that make the transfer
89191   ** very fast and which reduce fragmentation of indices.
89192   **
89193   ** This is the 2nd template.
89194   */
89195   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89196     assert( !pTrigger );
89197     assert( pList==0 );
89198     goto insert_end;
89199   }
89200 #endif /* SQLCIPHER_OMIT_XFER_OPT */
89201
89202   /* If this is an AUTOINCREMENT table, look up the sequence number in the
89203   ** sqlcipher_sequence table and store it in memory cell regAutoinc.
89204   */
89205   regAutoinc = autoIncBegin(pParse, iDb, pTab);
89206
89207   /* Figure out how many columns of data are supplied.  If the data
89208   ** is coming from a SELECT statement, then generate a co-routine that
89209   ** produces a single row of the SELECT on each invocation.  The
89210   ** co-routine is the common header to the 3rd and 4th templates.
89211   */
89212   if( pSelect ){
89213     /* Data is coming from a SELECT.  Generate code to implement that SELECT
89214     ** as a co-routine.  The code is common to both the 3rd and 4th
89215     ** templates:
89216     **
89217     **         EOF <- 0
89218     **         X <- A
89219     **         goto B
89220     **      A: setup for the SELECT
89221     **         loop over the tables in the SELECT
89222     **           load value into register R..R+n
89223     **           yield X
89224     **         end loop
89225     **         cleanup after the SELECT
89226     **         EOF <- 1
89227     **         yield X
89228     **         halt-error
89229     **
89230     ** On each invocation of the co-routine, it puts a single row of the
89231     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
89232     ** (These output registers are allocated by sqlcipher3Select().)  When
89233     ** the SELECT completes, it sets the EOF flag stored in regEof.
89234     */
89235     int rc, j1;
89236
89237     regEof = ++pParse->nMem;
89238     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
89239     VdbeComment((v, "SELECT eof flag"));
89240     sqlcipher3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
89241     addrSelect = sqlcipher3VdbeCurrentAddr(v)+2;
89242     sqlcipher3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
89243     j1 = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, 0);
89244     VdbeComment((v, "Jump over SELECT coroutine"));
89245
89246     /* Resolve the expressions in the SELECT statement and execute it. */
89247     rc = sqlcipher3Select(pParse, pSelect, &dest);
89248     assert( pParse->nErr==0 || rc );
89249     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
89250       goto insert_cleanup;
89251     }
89252     sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
89253     sqlcipher3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
89254     sqlcipher3VdbeAddOp2(v, OP_Halt, SQLCIPHER_INTERNAL, OE_Abort);
89255     VdbeComment((v, "End of SELECT coroutine"));
89256     sqlcipher3VdbeJumpHere(v, j1);                          /* label B: */
89257
89258     regFromSelect = dest.iMem;
89259     assert( pSelect->pEList );
89260     nColumn = pSelect->pEList->nExpr;
89261     assert( dest.nMem==nColumn );
89262
89263     /* Set useTempTable to TRUE if the result of the SELECT statement
89264     ** should be written into a temporary table (template 4).  Set to
89265     ** FALSE if each* row of the SELECT can be written directly into
89266     ** the destination table (template 3).
89267     **
89268     ** A temp table must be used if the table being updated is also one
89269     ** of the tables being read by the SELECT statement.  Also use a 
89270     ** temp table in the case of row triggers.
89271     */
89272     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89273       useTempTable = 1;
89274     }
89275
89276     if( useTempTable ){
89277       /* Invoke the coroutine to extract information from the SELECT
89278       ** and add it to a transient table srcTab.  The code generated
89279       ** here is from the 4th template:
89280       **
89281       **      B: open temp table
89282       **      L: yield X
89283       **         if EOF goto M
89284       **         insert row from R..R+n into temp table
89285       **         goto L
89286       **      M: ...
89287       */
89288       int regRec;          /* Register to hold packed record */
89289       int regTempRowid;    /* Register to hold temp table ROWID */
89290       int addrTop;         /* Label "L" */
89291       int addrIf;          /* Address of jump to M */
89292
89293       srcTab = pParse->nTab++;
89294       regRec = sqlcipher3GetTempReg(pParse);
89295       regTempRowid = sqlcipher3GetTempReg(pParse);
89296       sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89297       addrTop = sqlcipher3VdbeAddOp1(v, OP_Yield, dest.iParm);
89298       addrIf = sqlcipher3VdbeAddOp1(v, OP_If, regEof);
89299       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89300       sqlcipher3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89301       sqlcipher3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89302       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89303       sqlcipher3VdbeJumpHere(v, addrIf);
89304       sqlcipher3ReleaseTempReg(pParse, regRec);
89305       sqlcipher3ReleaseTempReg(pParse, regTempRowid);
89306     }
89307   }else{
89308     /* This is the case if the data for the INSERT is coming from a VALUES
89309     ** clause
89310     */
89311     NameContext sNC;
89312     memset(&sNC, 0, sizeof(sNC));
89313     sNC.pParse = pParse;
89314     srcTab = -1;
89315     assert( useTempTable==0 );
89316     nColumn = pList ? pList->nExpr : 0;
89317     for(i=0; i<nColumn; i++){
89318       if( sqlcipher3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89319         goto insert_cleanup;
89320       }
89321     }
89322   }
89323
89324   /* Make sure the number of columns in the source data matches the number
89325   ** of columns to be inserted into the table.
89326   */
89327   if( IsVirtual(pTab) ){
89328     for(i=0; i<pTab->nCol; i++){
89329       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89330     }
89331   }
89332   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89333     sqlcipher3ErrorMsg(pParse, 
89334        "table %S has %d columns but %d values were supplied",
89335        pTabList, 0, pTab->nCol-nHidden, nColumn);
89336     goto insert_cleanup;
89337   }
89338   if( pColumn!=0 && nColumn!=pColumn->nId ){
89339     sqlcipher3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89340     goto insert_cleanup;
89341   }
89342
89343   /* If the INSERT statement included an IDLIST term, then make sure
89344   ** all elements of the IDLIST really are columns of the table and 
89345   ** remember the column indices.
89346   **
89347   ** If the table has an INTEGER PRIMARY KEY column and that column
89348   ** is named in the IDLIST, then record in the keyColumn variable
89349   ** the index into IDLIST of the primary key column.  keyColumn is
89350   ** the index of the primary key as it appears in IDLIST, not as
89351   ** is appears in the original table.  (The index of the primary
89352   ** key in the original table is pTab->iPKey.)
89353   */
89354   if( pColumn ){
89355     for(i=0; i<pColumn->nId; i++){
89356       pColumn->a[i].idx = -1;
89357     }
89358     for(i=0; i<pColumn->nId; i++){
89359       for(j=0; j<pTab->nCol; j++){
89360         if( sqlcipher3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89361           pColumn->a[i].idx = j;
89362           if( j==pTab->iPKey ){
89363             keyColumn = i;
89364           }
89365           break;
89366         }
89367       }
89368       if( j>=pTab->nCol ){
89369         if( sqlcipher3IsRowid(pColumn->a[i].zName) ){
89370           keyColumn = i;
89371         }else{
89372           sqlcipher3ErrorMsg(pParse, "table %S has no column named %s",
89373               pTabList, 0, pColumn->a[i].zName);
89374           pParse->checkSchema = 1;
89375           goto insert_cleanup;
89376         }
89377       }
89378     }
89379   }
89380
89381   /* If there is no IDLIST term but the table has an integer primary
89382   ** key, the set the keyColumn variable to the primary key column index
89383   ** in the original table definition.
89384   */
89385   if( pColumn==0 && nColumn>0 ){
89386     keyColumn = pTab->iPKey;
89387   }
89388     
89389   /* Initialize the count of rows to be inserted
89390   */
89391   if( db->flags & SQLCIPHER_CountRows ){
89392     regRowCount = ++pParse->nMem;
89393     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89394   }
89395
89396   /* If this is not a view, open the table and and all indices */
89397   if( !isView ){
89398     int nIdx;
89399
89400     baseCur = pParse->nTab;
89401     nIdx = sqlcipher3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89402     aRegIdx = sqlcipher3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89403     if( aRegIdx==0 ){
89404       goto insert_cleanup;
89405     }
89406     for(i=0; i<nIdx; i++){
89407       aRegIdx[i] = ++pParse->nMem;
89408     }
89409   }
89410
89411   /* This is the top of the main insertion loop */
89412   if( useTempTable ){
89413     /* This block codes the top of loop only.  The complete loop is the
89414     ** following pseudocode (template 4):
89415     **
89416     **         rewind temp table
89417     **      C: loop over rows of intermediate table
89418     **           transfer values form intermediate table into <table>
89419     **         end loop
89420     **      D: ...
89421     */
89422     addrInsTop = sqlcipher3VdbeAddOp1(v, OP_Rewind, srcTab);
89423     addrCont = sqlcipher3VdbeCurrentAddr(v);
89424   }else if( pSelect ){
89425     /* This block codes the top of loop only.  The complete loop is the
89426     ** following pseudocode (template 3):
89427     **
89428     **      C: yield X
89429     **         if EOF goto D
89430     **         insert the select result into <table> from R..R+n
89431     **         goto C
89432     **      D: ...
89433     */
89434     addrCont = sqlcipher3VdbeAddOp1(v, OP_Yield, dest.iParm);
89435     addrInsTop = sqlcipher3VdbeAddOp1(v, OP_If, regEof);
89436   }
89437
89438   /* Allocate registers for holding the rowid of the new row,
89439   ** the content of the new row, and the assemblied row record.
89440   */
89441   regRowid = regIns = pParse->nMem+1;
89442   pParse->nMem += pTab->nCol + 1;
89443   if( IsVirtual(pTab) ){
89444     regRowid++;
89445     pParse->nMem++;
89446   }
89447   regData = regRowid+1;
89448
89449   /* Run the BEFORE and INSTEAD OF triggers, if there are any
89450   */
89451   endOfLoop = sqlcipher3VdbeMakeLabel(v);
89452   if( tmask & TRIGGER_BEFORE ){
89453     int regCols = sqlcipher3GetTempRange(pParse, pTab->nCol+1);
89454
89455     /* build the NEW.* reference row.  Note that if there is an INTEGER
89456     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89457     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89458     ** we do not know what the unique ID will be (because the insert has
89459     ** not happened yet) so we substitute a rowid of -1
89460     */
89461     if( keyColumn<0 ){
89462       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regCols);
89463     }else{
89464       int j1;
89465       if( useTempTable ){
89466         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89467       }else{
89468         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89469         sqlcipher3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89470       }
89471       j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regCols);
89472       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, regCols);
89473       sqlcipher3VdbeJumpHere(v, j1);
89474       sqlcipher3VdbeAddOp1(v, OP_MustBeInt, regCols);
89475     }
89476
89477     /* Cannot have triggers on a virtual table. If it were possible,
89478     ** this block would have to account for hidden column.
89479     */
89480     assert( !IsVirtual(pTab) );
89481
89482     /* Create the new column data
89483     */
89484     for(i=0; i<pTab->nCol; i++){
89485       if( pColumn==0 ){
89486         j = i;
89487       }else{
89488         for(j=0; j<pColumn->nId; j++){
89489           if( pColumn->a[j].idx==i ) break;
89490         }
89491       }
89492       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89493         sqlcipher3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89494       }else if( useTempTable ){
89495         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
89496       }else{
89497         assert( pSelect==0 ); /* Otherwise useTempTable is true */
89498         sqlcipher3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89499       }
89500     }
89501
89502     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89503     ** do not attempt any conversions before assembling the record.
89504     ** If this is a real table, attempt conversions as required by the
89505     ** table column affinities.
89506     */
89507     if( !isView ){
89508       sqlcipher3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89509       sqlcipher3TableAffinityStr(v, pTab);
89510     }
89511
89512     /* Fire BEFORE or INSTEAD OF triggers */
89513     sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
89514         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89515
89516     sqlcipher3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89517   }
89518
89519   /* Push the record number for the new entry onto the stack.  The
89520   ** record number is a randomly generate integer created by NewRowid
89521   ** except when the table has an INTEGER PRIMARY KEY column, in which
89522   ** case the record number is the same as that column. 
89523   */
89524   if( !isView ){
89525     if( IsVirtual(pTab) ){
89526       /* The row that the VUpdate opcode will delete: none */
89527       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regIns);
89528     }
89529     if( keyColumn>=0 ){
89530       if( useTempTable ){
89531         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89532       }else if( pSelect ){
89533         sqlcipher3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89534       }else{
89535         VdbeOp *pOp;
89536         sqlcipher3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89537         pOp = sqlcipher3VdbeGetOp(v, -1);
89538         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89539           appendFlag = 1;
89540           pOp->opcode = OP_NewRowid;
89541           pOp->p1 = baseCur;
89542           pOp->p2 = regRowid;
89543           pOp->p3 = regAutoinc;
89544         }
89545       }
89546       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89547       ** to generate a unique primary key value.
89548       */
89549       if( !appendFlag ){
89550         int j1;
89551         if( !IsVirtual(pTab) ){
89552           j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regRowid);
89553           sqlcipher3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89554           sqlcipher3VdbeJumpHere(v, j1);
89555         }else{
89556           j1 = sqlcipher3VdbeCurrentAddr(v);
89557           sqlcipher3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89558         }
89559         sqlcipher3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89560       }
89561     }else if( IsVirtual(pTab) ){
89562       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regRowid);
89563     }else{
89564       sqlcipher3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89565       appendFlag = 1;
89566     }
89567     autoIncStep(pParse, regAutoinc, regRowid);
89568
89569     /* Push onto the stack, data for all columns of the new entry, beginning
89570     ** with the first column.
89571     */
89572     nHidden = 0;
89573     for(i=0; i<pTab->nCol; i++){
89574       int iRegStore = regRowid+1+i;
89575       if( i==pTab->iPKey ){
89576         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89577         ** Whenever this column is read, the record number will be substituted
89578         ** in its place.  So will fill this column with a NULL to avoid
89579         ** taking up data space with information that will never be used. */
89580         sqlcipher3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89581         continue;
89582       }
89583       if( pColumn==0 ){
89584         if( IsHiddenColumn(&pTab->aCol[i]) ){
89585           assert( IsVirtual(pTab) );
89586           j = -1;
89587           nHidden++;
89588         }else{
89589           j = i - nHidden;
89590         }
89591       }else{
89592         for(j=0; j<pColumn->nId; j++){
89593           if( pColumn->a[j].idx==i ) break;
89594         }
89595       }
89596       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89597         sqlcipher3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89598       }else if( useTempTable ){
89599         sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
89600       }else if( pSelect ){
89601         sqlcipher3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89602       }else{
89603         sqlcipher3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89604       }
89605     }
89606
89607     /* Generate code to check constraints and generate index keys and
89608     ** do the insertion.
89609     */
89610 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
89611     if( IsVirtual(pTab) ){
89612       const char *pVTab = (const char *)sqlcipher3GetVTable(db, pTab);
89613       sqlcipher3VtabMakeWritable(pParse, pTab);
89614       sqlcipher3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89615       sqlcipher3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89616       sqlcipher3MayAbort(pParse);
89617     }else
89618 #endif
89619     {
89620       int isReplace;    /* Set to true if constraints may cause a replace */
89621       sqlcipher3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89622           keyColumn>=0, 0, onError, endOfLoop, &isReplace
89623       );
89624       sqlcipher3FkCheck(pParse, pTab, 0, regIns);
89625       sqlcipher3CompleteInsertion(
89626           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89627       );
89628     }
89629   }
89630
89631   /* Update the count of rows that are inserted
89632   */
89633   if( (db->flags & SQLCIPHER_CountRows)!=0 ){
89634     sqlcipher3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89635   }
89636
89637   if( pTrigger ){
89638     /* Code AFTER triggers */
89639     sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
89640         pTab, regData-2-pTab->nCol, onError, endOfLoop);
89641   }
89642
89643   /* The bottom of the main insertion loop, if the data source
89644   ** is a SELECT statement.
89645   */
89646   sqlcipher3VdbeResolveLabel(v, endOfLoop);
89647   if( useTempTable ){
89648     sqlcipher3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89649     sqlcipher3VdbeJumpHere(v, addrInsTop);
89650     sqlcipher3VdbeAddOp1(v, OP_Close, srcTab);
89651   }else if( pSelect ){
89652     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89653     sqlcipher3VdbeJumpHere(v, addrInsTop);
89654   }
89655
89656   if( !IsVirtual(pTab) && !isView ){
89657     /* Close all tables opened */
89658     sqlcipher3VdbeAddOp1(v, OP_Close, baseCur);
89659     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89660       sqlcipher3VdbeAddOp1(v, OP_Close, idx+baseCur);
89661     }
89662   }
89663
89664 insert_end:
89665   /* Update the sqlcipher_sequence table by storing the content of the
89666   ** maximum rowid counter values recorded while inserting into
89667   ** autoincrement tables.
89668   */
89669   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89670     sqlcipher3AutoincrementEnd(pParse);
89671   }
89672
89673   /*
89674   ** Return the number of rows inserted. If this routine is 
89675   ** generating code because of a call to sqlcipher3NestedParse(), do not
89676   ** invoke the callback function.
89677   */
89678   if( (db->flags&SQLCIPHER_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89679     sqlcipher3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
89680     sqlcipher3VdbeSetNumCols(v, 1);
89681     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLCIPHER_STATIC);
89682   }
89683
89684 insert_cleanup:
89685   sqlcipher3SrcListDelete(db, pTabList);
89686   sqlcipher3ExprListDelete(db, pList);
89687   sqlcipher3SelectDelete(db, pSelect);
89688   sqlcipher3IdListDelete(db, pColumn);
89689   sqlcipher3DbFree(db, aRegIdx);
89690 }
89691
89692 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89693 ** thely may interfere with compilation of other functions in this file
89694 ** (or in another file, if this file becomes part of the amalgamation).  */
89695 #ifdef isView
89696  #undef isView
89697 #endif
89698 #ifdef pTrigger
89699  #undef pTrigger
89700 #endif
89701 #ifdef tmask
89702  #undef tmask
89703 #endif
89704
89705
89706 /*
89707 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
89708 **
89709 ** The input is a range of consecutive registers as follows:
89710 **
89711 **    1.  The rowid of the row after the update.
89712 **
89713 **    2.  The data in the first column of the entry after the update.
89714 **
89715 **    i.  Data from middle columns...
89716 **
89717 **    N.  The data in the last column of the entry after the update.
89718 **
89719 ** The regRowid parameter is the index of the register containing (1).
89720 **
89721 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
89722 ** the address of a register containing the rowid before the update takes
89723 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
89724 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
89725 ** indicates that the rowid was explicitly specified as part of the
89726 ** INSERT statement. If rowidChng is false, it means that  the rowid is
89727 ** computed automatically in an insert or that the rowid value is not 
89728 ** modified by an update.
89729 **
89730 ** The code generated by this routine store new index entries into
89731 ** registers identified by aRegIdx[].  No index entry is created for
89732 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
89733 ** the same as the order of indices on the linked list of indices
89734 ** attached to the table.
89735 **
89736 ** This routine also generates code to check constraints.  NOT NULL,
89737 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
89738 ** then the appropriate action is performed.  There are five possible
89739 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
89740 **
89741 **  Constraint type  Action       What Happens
89742 **  ---------------  ----------   ----------------------------------------
89743 **  any              ROLLBACK     The current transaction is rolled back and
89744 **                                sqlcipher3_exec() returns immediately with a
89745 **                                return code of SQLCIPHER_CONSTRAINT.
89746 **
89747 **  any              ABORT        Back out changes from the current command
89748 **                                only (do not do a complete rollback) then
89749 **                                cause sqlcipher3_exec() to return immediately
89750 **                                with SQLCIPHER_CONSTRAINT.
89751 **
89752 **  any              FAIL         Sqlite_exec() returns immediately with a
89753 **                                return code of SQLCIPHER_CONSTRAINT.  The
89754 **                                transaction is not rolled back and any
89755 **                                prior changes are retained.
89756 **
89757 **  any              IGNORE       The record number and data is popped from
89758 **                                the stack and there is an immediate jump
89759 **                                to label ignoreDest.
89760 **
89761 **  NOT NULL         REPLACE      The NULL value is replace by the default
89762 **                                value for that column.  If the default value
89763 **                                is NULL, the action is the same as ABORT.
89764 **
89765 **  UNIQUE           REPLACE      The other row that conflicts with the row
89766 **                                being inserted is removed.
89767 **
89768 **  CHECK            REPLACE      Illegal.  The results in an exception.
89769 **
89770 ** Which action to take is determined by the overrideError parameter.
89771 ** Or if overrideError==OE_Default, then the pParse->onError parameter
89772 ** is used.  Or if pParse->onError==OE_Default then the onError value
89773 ** for the constraint is used.
89774 **
89775 ** The calling routine must open a read/write cursor for pTab with
89776 ** cursor number "baseCur".  All indices of pTab must also have open
89777 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
89778 ** Except, if there is no possibility of a REPLACE action then
89779 ** cursors do not need to be open for indices where aRegIdx[i]==0.
89780 */
89781 SQLCIPHER_PRIVATE void sqlcipher3GenerateConstraintChecks(
89782   Parse *pParse,      /* The parser context */
89783   Table *pTab,        /* the table into which we are inserting */
89784   int baseCur,        /* Index of a read/write cursor pointing at pTab */
89785   int regRowid,       /* Index of the range of input registers */
89786   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
89787   int rowidChng,      /* True if the rowid might collide with existing entry */
89788   int isUpdate,       /* True for UPDATE, False for INSERT */
89789   int overrideError,  /* Override onError to this if not OE_Default */
89790   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
89791   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
89792 ){
89793   int i;              /* loop counter */
89794   Vdbe *v;            /* VDBE under constrution */
89795   int nCol;           /* Number of columns */
89796   int onError;        /* Conflict resolution strategy */
89797   int j1;             /* Addresss of jump instruction */
89798   int j2 = 0, j3;     /* Addresses of jump instructions */
89799   int regData;        /* Register containing first data column */
89800   int iCur;           /* Table cursor number */
89801   Index *pIdx;         /* Pointer to one of the indices */
89802   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
89803   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
89804
89805   v = sqlcipher3GetVdbe(pParse);
89806   assert( v!=0 );
89807   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
89808   nCol = pTab->nCol;
89809   regData = regRowid + 1;
89810
89811   /* Test all NOT NULL constraints.
89812   */
89813   for(i=0; i<nCol; i++){
89814     if( i==pTab->iPKey ){
89815       continue;
89816     }
89817     onError = pTab->aCol[i].notNull;
89818     if( onError==OE_None ) continue;
89819     if( overrideError!=OE_Default ){
89820       onError = overrideError;
89821     }else if( onError==OE_Default ){
89822       onError = OE_Abort;
89823     }
89824     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
89825       onError = OE_Abort;
89826     }
89827     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
89828         || onError==OE_Ignore || onError==OE_Replace );
89829     switch( onError ){
89830       case OE_Abort:
89831         sqlcipher3MayAbort(pParse);
89832       case OE_Rollback:
89833       case OE_Fail: {
89834         char *zMsg;
89835         sqlcipher3VdbeAddOp3(v, OP_HaltIfNull,
89836                                   SQLCIPHER_CONSTRAINT, onError, regData+i);
89837         zMsg = sqlcipher3MPrintf(pParse->db, "%s.%s may not be NULL",
89838                               pTab->zName, pTab->aCol[i].zName);
89839         sqlcipher3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
89840         break;
89841       }
89842       case OE_Ignore: {
89843         sqlcipher3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
89844         break;
89845       }
89846       default: {
89847         assert( onError==OE_Replace );
89848         j1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regData+i);
89849         sqlcipher3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
89850         sqlcipher3VdbeJumpHere(v, j1);
89851         break;
89852       }
89853     }
89854   }
89855
89856   /* Test all CHECK constraints
89857   */
89858 #ifndef SQLCIPHER_OMIT_CHECK
89859   if( pTab->pCheck && (pParse->db->flags & SQLCIPHER_IgnoreChecks)==0 ){
89860     int allOk = sqlcipher3VdbeMakeLabel(v);
89861     pParse->ckBase = regData;
89862     sqlcipher3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLCIPHER_JUMPIFNULL);
89863     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
89864     if( onError==OE_Ignore ){
89865       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89866     }else{
89867       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
89868       sqlcipher3HaltConstraint(pParse, onError, 0, 0);
89869     }
89870     sqlcipher3VdbeResolveLabel(v, allOk);
89871   }
89872 #endif /* !defined(SQLCIPHER_OMIT_CHECK) */
89873
89874   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
89875   ** of the new record does not previously exist.  Except, if this
89876   ** is an UPDATE and the primary key is not changing, that is OK.
89877   */
89878   if( rowidChng ){
89879     onError = pTab->keyConf;
89880     if( overrideError!=OE_Default ){
89881       onError = overrideError;
89882     }else if( onError==OE_Default ){
89883       onError = OE_Abort;
89884     }
89885     
89886     if( isUpdate ){
89887       j2 = sqlcipher3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
89888     }
89889     j3 = sqlcipher3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
89890     switch( onError ){
89891       default: {
89892         onError = OE_Abort;
89893         /* Fall thru into the next case */
89894       }
89895       case OE_Rollback:
89896       case OE_Abort:
89897       case OE_Fail: {
89898         sqlcipher3HaltConstraint(
89899           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
89900         break;
89901       }
89902       case OE_Replace: {
89903         /* If there are DELETE triggers on this table and the
89904         ** recursive-triggers flag is set, call GenerateRowDelete() to
89905         ** remove the conflicting row from the the table. This will fire
89906         ** the triggers and remove both the table and index b-tree entries.
89907         **
89908         ** Otherwise, if there are no triggers or the recursive-triggers
89909         ** flag is not set, but the table has one or more indexes, call 
89910         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
89911         ** only. The table b-tree entry will be replaced by the new entry 
89912         ** when it is inserted.  
89913         **
89914         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
89915         ** also invoke MultiWrite() to indicate that this VDBE may require
89916         ** statement rollback (if the statement is aborted after the delete
89917         ** takes place). Earlier versions called sqlcipher3MultiWrite() regardless,
89918         ** but being more selective here allows statements like:
89919         **
89920         **   REPLACE INTO t(rowid) VALUES($newrowid)
89921         **
89922         ** to run without a statement journal if there are no indexes on the
89923         ** table.
89924         */
89925         Trigger *pTrigger = 0;
89926         if( pParse->db->flags&SQLCIPHER_RecTriggers ){
89927           pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
89928         }
89929         if( pTrigger || sqlcipher3FkRequired(pParse, pTab, 0, 0) ){
89930           sqlcipher3MultiWrite(pParse);
89931           sqlcipher3GenerateRowDelete(
89932               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
89933           );
89934         }else if( pTab->pIndex ){
89935           sqlcipher3MultiWrite(pParse);
89936           sqlcipher3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
89937         }
89938         seenReplace = 1;
89939         break;
89940       }
89941       case OE_Ignore: {
89942         assert( seenReplace==0 );
89943         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89944         break;
89945       }
89946     }
89947     sqlcipher3VdbeJumpHere(v, j3);
89948     if( isUpdate ){
89949       sqlcipher3VdbeJumpHere(v, j2);
89950     }
89951   }
89952
89953   /* Test all UNIQUE constraints by creating entries for each UNIQUE
89954   ** index and making sure that duplicate entries do not already exist.
89955   ** Add the new records to the indices as we go.
89956   */
89957   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
89958     int regIdx;
89959     int regR;
89960
89961     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
89962
89963     /* Create a key for accessing the index entry */
89964     regIdx = sqlcipher3GetTempRange(pParse, pIdx->nColumn+1);
89965     for(i=0; i<pIdx->nColumn; i++){
89966       int idx = pIdx->aiColumn[i];
89967       if( idx==pTab->iPKey ){
89968         sqlcipher3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
89969       }else{
89970         sqlcipher3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
89971       }
89972     }
89973     sqlcipher3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
89974     sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
89975     sqlcipher3VdbeChangeP4(v, -1, sqlcipher3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
89976     sqlcipher3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
89977
89978     /* Find out what action to take in case there is an indexing conflict */
89979     onError = pIdx->onError;
89980     if( onError==OE_None ){ 
89981       sqlcipher3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
89982       continue;  /* pIdx is not a UNIQUE index */
89983     }
89984     if( overrideError!=OE_Default ){
89985       onError = overrideError;
89986     }else if( onError==OE_Default ){
89987       onError = OE_Abort;
89988     }
89989     if( seenReplace ){
89990       if( onError==OE_Ignore ) onError = OE_Replace;
89991       else if( onError==OE_Fail ) onError = OE_Abort;
89992     }
89993     
89994     /* Check to see if the new index entry will be unique */
89995     regR = sqlcipher3GetTempReg(pParse);
89996     sqlcipher3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
89997     j3 = sqlcipher3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
89998                            regR, SQLCIPHER_INT_TO_PTR(regIdx),
89999                            P4_INT32);
90000     sqlcipher3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90001
90002     /* Generate code that executes if the new index entry is not unique */
90003     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90004         || onError==OE_Ignore || onError==OE_Replace );
90005     switch( onError ){
90006       case OE_Rollback:
90007       case OE_Abort:
90008       case OE_Fail: {
90009         int j;
90010         StrAccum errMsg;
90011         const char *zSep;
90012         char *zErr;
90013
90014         sqlcipher3StrAccumInit(&errMsg, 0, 0, 200);
90015         errMsg.db = pParse->db;
90016         zSep = pIdx->nColumn>1 ? "columns " : "column ";
90017         for(j=0; j<pIdx->nColumn; j++){
90018           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90019           sqlcipher3StrAccumAppend(&errMsg, zSep, -1);
90020           zSep = ", ";
90021           sqlcipher3StrAccumAppend(&errMsg, zCol, -1);
90022         }
90023         sqlcipher3StrAccumAppend(&errMsg,
90024             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
90025         zErr = sqlcipher3StrAccumFinish(&errMsg);
90026         sqlcipher3HaltConstraint(pParse, onError, zErr, 0);
90027         sqlcipher3DbFree(errMsg.db, zErr);
90028         break;
90029       }
90030       case OE_Ignore: {
90031         assert( seenReplace==0 );
90032         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90033         break;
90034       }
90035       default: {
90036         Trigger *pTrigger = 0;
90037         assert( onError==OE_Replace );
90038         sqlcipher3MultiWrite(pParse);
90039         if( pParse->db->flags&SQLCIPHER_RecTriggers ){
90040           pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90041         }
90042         sqlcipher3GenerateRowDelete(
90043             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90044         );
90045         seenReplace = 1;
90046         break;
90047       }
90048     }
90049     sqlcipher3VdbeJumpHere(v, j3);
90050     sqlcipher3ReleaseTempReg(pParse, regR);
90051   }
90052   
90053   if( pbMayReplace ){
90054     *pbMayReplace = seenReplace;
90055   }
90056 }
90057
90058 /*
90059 ** This routine generates code to finish the INSERT or UPDATE operation
90060 ** that was started by a prior call to sqlcipher3GenerateConstraintChecks.
90061 ** A consecutive range of registers starting at regRowid contains the
90062 ** rowid and the content to be inserted.
90063 **
90064 ** The arguments to this routine should be the same as the first six
90065 ** arguments to sqlcipher3GenerateConstraintChecks.
90066 */
90067 SQLCIPHER_PRIVATE void sqlcipher3CompleteInsertion(
90068   Parse *pParse,      /* The parser context */
90069   Table *pTab,        /* the table into which we are inserting */
90070   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90071   int regRowid,       /* Range of content */
90072   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90073   int isUpdate,       /* True for UPDATE, False for INSERT */
90074   int appendBias,     /* True if this is likely to be an append */
90075   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90076 ){
90077   int i;
90078   Vdbe *v;
90079   int nIdx;
90080   Index *pIdx;
90081   u8 pik_flags;
90082   int regData;
90083   int regRec;
90084
90085   v = sqlcipher3GetVdbe(pParse);
90086   assert( v!=0 );
90087   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90088   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90089   for(i=nIdx-1; i>=0; i--){
90090     if( aRegIdx[i]==0 ) continue;
90091     sqlcipher3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90092     if( useSeekResult ){
90093       sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90094     }
90095   }
90096   regData = regRowid + 1;
90097   regRec = sqlcipher3GetTempReg(pParse);
90098   sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90099   sqlcipher3TableAffinityStr(v, pTab);
90100   sqlcipher3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90101   if( pParse->nested ){
90102     pik_flags = 0;
90103   }else{
90104     pik_flags = OPFLAG_NCHANGE;
90105     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90106   }
90107   if( appendBias ){
90108     pik_flags |= OPFLAG_APPEND;
90109   }
90110   if( useSeekResult ){
90111     pik_flags |= OPFLAG_USESEEKRESULT;
90112   }
90113   sqlcipher3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90114   if( !pParse->nested ){
90115     sqlcipher3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90116   }
90117   sqlcipher3VdbeChangeP5(v, pik_flags);
90118 }
90119
90120 /*
90121 ** Generate code that will open cursors for a table and for all
90122 ** indices of that table.  The "baseCur" parameter is the cursor number used
90123 ** for the table.  Indices are opened on subsequent cursors.
90124 **
90125 ** Return the number of indices on the table.
90126 */
90127 SQLCIPHER_PRIVATE int sqlcipher3OpenTableAndIndices(
90128   Parse *pParse,   /* Parsing context */
90129   Table *pTab,     /* Table to be opened */
90130   int baseCur,     /* Cursor number assigned to the table */
90131   int op           /* OP_OpenRead or OP_OpenWrite */
90132 ){
90133   int i;
90134   int iDb;
90135   Index *pIdx;
90136   Vdbe *v;
90137
90138   if( IsVirtual(pTab) ) return 0;
90139   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
90140   v = sqlcipher3GetVdbe(pParse);
90141   assert( v!=0 );
90142   sqlcipher3OpenTable(pParse, baseCur, iDb, pTab, op);
90143   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90144     KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
90145     assert( pIdx->pSchema==pTab->pSchema );
90146     sqlcipher3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90147                       (char*)pKey, P4_KEYINFO_HANDOFF);
90148     VdbeComment((v, "%s", pIdx->zName));
90149   }
90150   if( pParse->nTab<baseCur+i ){
90151     pParse->nTab = baseCur+i;
90152   }
90153   return i-1;
90154 }
90155
90156
90157 #ifdef SQLCIPHER_TEST
90158 /*
90159 ** The following global variable is incremented whenever the
90160 ** transfer optimization is used.  This is used for testing
90161 ** purposes only - to make sure the transfer optimization really
90162 ** is happening when it is suppose to.
90163 */
90164 SQLCIPHER_API int sqlcipher3_xferopt_count;
90165 #endif /* SQLCIPHER_TEST */
90166
90167
90168 #ifndef SQLCIPHER_OMIT_XFER_OPT
90169 /*
90170 ** Check to collation names to see if they are compatible.
90171 */
90172 static int xferCompatibleCollation(const char *z1, const char *z2){
90173   if( z1==0 ){
90174     return z2==0;
90175   }
90176   if( z2==0 ){
90177     return 0;
90178   }
90179   return sqlcipher3StrICmp(z1, z2)==0;
90180 }
90181
90182
90183 /*
90184 ** Check to see if index pSrc is compatible as a source of data
90185 ** for index pDest in an insert transfer optimization.  The rules
90186 ** for a compatible index:
90187 **
90188 **    *   The index is over the same set of columns
90189 **    *   The same DESC and ASC markings occurs on all columns
90190 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90191 **    *   The same collating sequence on each column
90192 */
90193 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90194   int i;
90195   assert( pDest && pSrc );
90196   assert( pDest->pTable!=pSrc->pTable );
90197   if( pDest->nColumn!=pSrc->nColumn ){
90198     return 0;   /* Different number of columns */
90199   }
90200   if( pDest->onError!=pSrc->onError ){
90201     return 0;   /* Different conflict resolution strategies */
90202   }
90203   for(i=0; i<pSrc->nColumn; i++){
90204     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90205       return 0;   /* Different columns indexed */
90206     }
90207     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90208       return 0;   /* Different sort orders */
90209     }
90210     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90211       return 0;   /* Different collating sequences */
90212     }
90213   }
90214
90215   /* If no test above fails then the indices must be compatible */
90216   return 1;
90217 }
90218
90219 /*
90220 ** Attempt the transfer optimization on INSERTs of the form
90221 **
90222 **     INSERT INTO tab1 SELECT * FROM tab2;
90223 **
90224 ** This optimization is only attempted if
90225 **
90226 **    (1)  tab1 and tab2 have identical schemas including all the
90227 **         same indices and constraints
90228 **
90229 **    (2)  tab1 and tab2 are different tables
90230 **
90231 **    (3)  There must be no triggers on tab1
90232 **
90233 **    (4)  The result set of the SELECT statement is "*"
90234 **
90235 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
90236 **         or LIMIT clause.
90237 **
90238 **    (6)  The SELECT statement is a simple (not a compound) select that
90239 **         contains only tab2 in its FROM clause
90240 **
90241 ** This method for implementing the INSERT transfers raw records from
90242 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
90243 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
90244 ** the resulting tab1 has much less fragmentation.
90245 **
90246 ** This routine returns TRUE if the optimization is attempted.  If any
90247 ** of the conditions above fail so that the optimization should not
90248 ** be attempted, then this routine returns FALSE.
90249 */
90250 static int xferOptimization(
90251   Parse *pParse,        /* Parser context */
90252   Table *pDest,         /* The table we are inserting into */
90253   Select *pSelect,      /* A SELECT statement to use as the data source */
90254   int onError,          /* How to handle constraint errors */
90255   int iDbDest           /* The database of pDest */
90256 ){
90257   ExprList *pEList;                /* The result set of the SELECT */
90258   Table *pSrc;                     /* The table in the FROM clause of SELECT */
90259   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90260   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90261   int i;                           /* Loop counter */
90262   int iDbSrc;                      /* The database of pSrc */
90263   int iSrc, iDest;                 /* Cursors from source and destination */
90264   int addr1, addr2;                /* Loop addresses */
90265   int emptyDestTest;               /* Address of test for empty pDest */
90266   int emptySrcTest;                /* Address of test for empty pSrc */
90267   Vdbe *v;                         /* The VDBE we are building */
90268   KeyInfo *pKey;                   /* Key information for an index */
90269   int regAutoinc;                  /* Memory register used by AUTOINC */
90270   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90271   int regData, regRowid;           /* Registers holding data and rowid */
90272
90273   if( pSelect==0 ){
90274     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90275   }
90276   if( sqlcipher3TriggerList(pParse, pDest) ){
90277     return 0;   /* tab1 must not have triggers */
90278   }
90279 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
90280   if( pDest->tabFlags & TF_Virtual ){
90281     return 0;   /* tab1 must not be a virtual table */
90282   }
90283 #endif
90284   if( onError==OE_Default ){
90285     onError = OE_Abort;
90286   }
90287   if( onError!=OE_Abort && onError!=OE_Rollback ){
90288     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
90289   }
90290   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90291   if( pSelect->pSrc->nSrc!=1 ){
90292     return 0;   /* FROM clause must have exactly one term */
90293   }
90294   if( pSelect->pSrc->a[0].pSelect ){
90295     return 0;   /* FROM clause cannot contain a subquery */
90296   }
90297   if( pSelect->pWhere ){
90298     return 0;   /* SELECT may not have a WHERE clause */
90299   }
90300   if( pSelect->pOrderBy ){
90301     return 0;   /* SELECT may not have an ORDER BY clause */
90302   }
90303   /* Do not need to test for a HAVING clause.  If HAVING is present but
90304   ** there is no ORDER BY, we will get an error. */
90305   if( pSelect->pGroupBy ){
90306     return 0;   /* SELECT may not have a GROUP BY clause */
90307   }
90308   if( pSelect->pLimit ){
90309     return 0;   /* SELECT may not have a LIMIT clause */
90310   }
90311   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90312   if( pSelect->pPrior ){
90313     return 0;   /* SELECT may not be a compound query */
90314   }
90315   if( pSelect->selFlags & SF_Distinct ){
90316     return 0;   /* SELECT may not be DISTINCT */
90317   }
90318   pEList = pSelect->pEList;
90319   assert( pEList!=0 );
90320   if( pEList->nExpr!=1 ){
90321     return 0;   /* The result set must have exactly one column */
90322   }
90323   assert( pEList->a[0].pExpr );
90324   if( pEList->a[0].pExpr->op!=TK_ALL ){
90325     return 0;   /* The result set must be the special operator "*" */
90326   }
90327
90328   /* At this point we have established that the statement is of the
90329   ** correct syntactic form to participate in this optimization.  Now
90330   ** we have to check the semantics.
90331   */
90332   pItem = pSelect->pSrc->a;
90333   pSrc = sqlcipher3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
90334   if( pSrc==0 ){
90335     return 0;   /* FROM clause does not contain a real table */
90336   }
90337   if( pSrc==pDest ){
90338     return 0;   /* tab1 and tab2 may not be the same table */
90339   }
90340 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
90341   if( pSrc->tabFlags & TF_Virtual ){
90342     return 0;   /* tab2 must not be a virtual table */
90343   }
90344 #endif
90345   if( pSrc->pSelect ){
90346     return 0;   /* tab2 may not be a view */
90347   }
90348   if( pDest->nCol!=pSrc->nCol ){
90349     return 0;   /* Number of columns must be the same in tab1 and tab2 */
90350   }
90351   if( pDest->iPKey!=pSrc->iPKey ){
90352     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90353   }
90354   for(i=0; i<pDest->nCol; i++){
90355     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90356       return 0;    /* Affinity must be the same on all columns */
90357     }
90358     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90359       return 0;    /* Collating sequence must be the same on all columns */
90360     }
90361     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90362       return 0;    /* tab2 must be NOT NULL if tab1 is */
90363     }
90364   }
90365   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90366     if( pDestIdx->onError!=OE_None ){
90367       destHasUniqueIdx = 1;
90368     }
90369     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90370       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90371     }
90372     if( pSrcIdx==0 ){
90373       return 0;    /* pDestIdx has no corresponding index in pSrc */
90374     }
90375   }
90376 #ifndef SQLCIPHER_OMIT_CHECK
90377   if( pDest->pCheck && sqlcipher3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
90378     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90379   }
90380 #endif
90381 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
90382   /* Disallow the transfer optimization if the destination table constains
90383   ** any foreign key constraints.  This is more restrictive than necessary.
90384   ** But the main beneficiary of the transfer optimization is the VACUUM 
90385   ** command, and the VACUUM command disables foreign key constraints.  So
90386   ** the extra complication to make this rule less restrictive is probably
90387   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90388   */
90389   if( (pParse->db->flags & SQLCIPHER_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90390     return 0;
90391   }
90392 #endif
90393   if( (pParse->db->flags & SQLCIPHER_CountRows)!=0 ){
90394     return 0;
90395   }
90396
90397   /* If we get this far, it means either:
90398   **
90399   **    *   We can always do the transfer if the table contains an
90400   **        an integer primary key
90401   **
90402   **    *   We can conditionally do the transfer if the destination
90403   **        table is empty.
90404   */
90405 #ifdef SQLCIPHER_TEST
90406   sqlcipher3_xferopt_count++;
90407 #endif
90408   iDbSrc = sqlcipher3SchemaToIndex(pParse->db, pSrc->pSchema);
90409   v = sqlcipher3GetVdbe(pParse);
90410   sqlcipher3CodeVerifySchema(pParse, iDbSrc);
90411   iSrc = pParse->nTab++;
90412   iDest = pParse->nTab++;
90413   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90414   sqlcipher3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90415   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
90416     /* If tables do not have an INTEGER PRIMARY KEY and there
90417     ** are indices to be copied and the destination is not empty,
90418     ** we have to disallow the transfer optimization because the
90419     ** the rowids might change which will mess up indexing.
90420     **
90421     ** Or if the destination has a UNIQUE index and is not empty,
90422     ** we also disallow the transfer optimization because we cannot
90423     ** insure that all entries in the union of DEST and SRC will be
90424     ** unique.
90425     */
90426     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90427     emptyDestTest = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, 0);
90428     sqlcipher3VdbeJumpHere(v, addr1);
90429   }else{
90430     emptyDestTest = 0;
90431   }
90432   sqlcipher3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90433   emptySrcTest = sqlcipher3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90434   regData = sqlcipher3GetTempReg(pParse);
90435   regRowid = sqlcipher3GetTempReg(pParse);
90436   if( pDest->iPKey>=0 ){
90437     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90438     addr2 = sqlcipher3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90439     sqlcipher3HaltConstraint(
90440         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90441     sqlcipher3VdbeJumpHere(v, addr2);
90442     autoIncStep(pParse, regAutoinc, regRowid);
90443   }else if( pDest->pIndex==0 ){
90444     addr1 = sqlcipher3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90445   }else{
90446     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90447     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90448   }
90449   sqlcipher3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90450   sqlcipher3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90451   sqlcipher3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90452   sqlcipher3VdbeChangeP4(v, -1, pDest->zName, 0);
90453   sqlcipher3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90454   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90455     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90456       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90457     }
90458     assert( pSrcIdx );
90459     sqlcipher3VdbeAddOp2(v, OP_Close, iSrc, 0);
90460     sqlcipher3VdbeAddOp2(v, OP_Close, iDest, 0);
90461     pKey = sqlcipher3IndexKeyinfo(pParse, pSrcIdx);
90462     sqlcipher3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90463                       (char*)pKey, P4_KEYINFO_HANDOFF);
90464     VdbeComment((v, "%s", pSrcIdx->zName));
90465     pKey = sqlcipher3IndexKeyinfo(pParse, pDestIdx);
90466     sqlcipher3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90467                       (char*)pKey, P4_KEYINFO_HANDOFF);
90468     VdbeComment((v, "%s", pDestIdx->zName));
90469     addr1 = sqlcipher3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90470     sqlcipher3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90471     sqlcipher3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90472     sqlcipher3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90473     sqlcipher3VdbeJumpHere(v, addr1);
90474   }
90475   sqlcipher3VdbeJumpHere(v, emptySrcTest);
90476   sqlcipher3ReleaseTempReg(pParse, regRowid);
90477   sqlcipher3ReleaseTempReg(pParse, regData);
90478   sqlcipher3VdbeAddOp2(v, OP_Close, iSrc, 0);
90479   sqlcipher3VdbeAddOp2(v, OP_Close, iDest, 0);
90480   if( emptyDestTest ){
90481     sqlcipher3VdbeAddOp2(v, OP_Halt, SQLCIPHER_OK, 0);
90482     sqlcipher3VdbeJumpHere(v, emptyDestTest);
90483     sqlcipher3VdbeAddOp2(v, OP_Close, iDest, 0);
90484     return 0;
90485   }else{
90486     return 1;
90487   }
90488 }
90489 #endif /* SQLCIPHER_OMIT_XFER_OPT */
90490
90491 /************** End of insert.c **********************************************/
90492 /************** Begin file legacy.c ******************************************/
90493 /*
90494 ** 2001 September 15
90495 **
90496 ** The author disclaims copyright to this source code.  In place of
90497 ** a legal notice, here is a blessing:
90498 **
90499 **    May you do good and not evil.
90500 **    May you find forgiveness for yourself and forgive others.
90501 **    May you share freely, never taking more than you give.
90502 **
90503 *************************************************************************
90504 ** Main file for the SQLite library.  The routines in this file
90505 ** implement the programmer interface to the library.  Routines in
90506 ** other files are for internal use by SQLite and should not be
90507 ** accessed by users of the library.
90508 */
90509
90510
90511 /*
90512 ** Execute SQL code.  Return one of the SQLCIPHER_ success/failure
90513 ** codes.  Also write an error message into memory obtained from
90514 ** malloc() and make *pzErrMsg point to that message.
90515 **
90516 ** If the SQL is a query, then for each row in the query result
90517 ** the xCallback() function is called.  pArg becomes the first
90518 ** argument to xCallback().  If xCallback=NULL then no callback
90519 ** is invoked, even for queries.
90520 */
90521 SQLCIPHER_API int sqlcipher3_exec(
90522   sqlcipher3 *db,                /* The database on which the SQL executes */
90523   const char *zSql,           /* The SQL to be executed */
90524   sqlcipher3_callback xCallback, /* Invoke this callback routine */
90525   void *pArg,                 /* First argument to xCallback() */
90526   char **pzErrMsg             /* Write error messages here */
90527 ){
90528   int rc = SQLCIPHER_OK;         /* Return code */
90529   const char *zLeftover;      /* Tail of unprocessed SQL */
90530   sqlcipher3_stmt *pStmt = 0;    /* The current SQL statement */
90531   char **azCols = 0;          /* Names of result columns */
90532   int nRetry = 0;             /* Number of retry attempts */
90533   int callbackIsInit;         /* True if callback data is initialized */
90534
90535   if( !sqlcipher3SafetyCheckOk(db) ) return SQLCIPHER_MISUSE_BKPT;
90536   if( zSql==0 ) zSql = "";
90537
90538   sqlcipher3_mutex_enter(db->mutex);
90539   sqlcipher3Error(db, SQLCIPHER_OK, 0);
90540   while( (rc==SQLCIPHER_OK || (rc==SQLCIPHER_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90541     int nCol;
90542     char **azVals = 0;
90543
90544     pStmt = 0;
90545     rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90546     assert( rc==SQLCIPHER_OK || pStmt==0 );
90547     if( rc!=SQLCIPHER_OK ){
90548       continue;
90549     }
90550     if( !pStmt ){
90551       /* this happens for a comment or white-space */
90552       zSql = zLeftover;
90553       continue;
90554     }
90555
90556     callbackIsInit = 0;
90557     nCol = sqlcipher3_column_count(pStmt);
90558
90559     while( 1 ){
90560       int i;
90561       rc = sqlcipher3_step(pStmt);
90562
90563       /* Invoke the callback function if required */
90564       if( xCallback && (SQLCIPHER_ROW==rc || 
90565           (SQLCIPHER_DONE==rc && !callbackIsInit
90566                            && db->flags&SQLCIPHER_NullCallback)) ){
90567         if( !callbackIsInit ){
90568           azCols = sqlcipher3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90569           if( azCols==0 ){
90570             goto exec_out;
90571           }
90572           for(i=0; i<nCol; i++){
90573             azCols[i] = (char *)sqlcipher3_column_name(pStmt, i);
90574             /* sqlcipher3VdbeSetColName() installs column names as UTF8
90575             ** strings so there is no way for sqlcipher3_column_name() to fail. */
90576             assert( azCols[i]!=0 );
90577           }
90578           callbackIsInit = 1;
90579         }
90580         if( rc==SQLCIPHER_ROW ){
90581           azVals = &azCols[nCol];
90582           for(i=0; i<nCol; i++){
90583             azVals[i] = (char *)sqlcipher3_column_text(pStmt, i);
90584             if( !azVals[i] && sqlcipher3_column_type(pStmt, i)!=SQLCIPHER_NULL ){
90585               db->mallocFailed = 1;
90586               goto exec_out;
90587             }
90588           }
90589         }
90590         if( xCallback(pArg, nCol, azVals, azCols) ){
90591           rc = SQLCIPHER_ABORT;
90592           sqlcipher3VdbeFinalize((Vdbe *)pStmt);
90593           pStmt = 0;
90594           sqlcipher3Error(db, SQLCIPHER_ABORT, 0);
90595           goto exec_out;
90596         }
90597       }
90598
90599       if( rc!=SQLCIPHER_ROW ){
90600         rc = sqlcipher3VdbeFinalize((Vdbe *)pStmt);
90601         pStmt = 0;
90602         if( rc!=SQLCIPHER_SCHEMA ){
90603           nRetry = 0;
90604           zSql = zLeftover;
90605           while( sqlcipher3Isspace(zSql[0]) ) zSql++;
90606         }
90607         break;
90608       }
90609     }
90610
90611     sqlcipher3DbFree(db, azCols);
90612     azCols = 0;
90613   }
90614
90615 exec_out:
90616   if( pStmt ) sqlcipher3VdbeFinalize((Vdbe *)pStmt);
90617   sqlcipher3DbFree(db, azCols);
90618
90619   rc = sqlcipher3ApiExit(db, rc);
90620   if( rc!=SQLCIPHER_OK && ALWAYS(rc==sqlcipher3_errcode(db)) && pzErrMsg ){
90621     int nErrMsg = 1 + sqlcipher3Strlen30(sqlcipher3_errmsg(db));
90622     *pzErrMsg = sqlcipher3Malloc(nErrMsg);
90623     if( *pzErrMsg ){
90624       memcpy(*pzErrMsg, sqlcipher3_errmsg(db), nErrMsg);
90625     }else{
90626       rc = SQLCIPHER_NOMEM;
90627       sqlcipher3Error(db, SQLCIPHER_NOMEM, 0);
90628     }
90629   }else if( pzErrMsg ){
90630     *pzErrMsg = 0;
90631   }
90632
90633   assert( (rc&db->errMask)==rc );
90634   sqlcipher3_mutex_leave(db->mutex);
90635   return rc;
90636 }
90637
90638 /************** End of legacy.c **********************************************/
90639 /************** Begin file loadext.c *****************************************/
90640 /*
90641 ** 2006 June 7
90642 **
90643 ** The author disclaims copyright to this source code.  In place of
90644 ** a legal notice, here is a blessing:
90645 **
90646 **    May you do good and not evil.
90647 **    May you find forgiveness for yourself and forgive others.
90648 **    May you share freely, never taking more than you give.
90649 **
90650 *************************************************************************
90651 ** This file contains code used to dynamically load extensions into
90652 ** the SQLite library.
90653 */
90654
90655 #ifndef SQLCIPHER_CORE
90656   #define SQLCIPHER_CORE 1  /* Disable the API redefinition in sqlcipher3ext.h */
90657 #endif
90658 /************** Include sqlcipher3ext.h in the middle of loadext.c **************/
90659 /************** Begin file sqlcipher3ext.h **************************************/
90660 /*
90661 ** 2006 June 7
90662 **
90663 ** The author disclaims copyright to this source code.  In place of
90664 ** a legal notice, here is a blessing:
90665 **
90666 **    May you do good and not evil.
90667 **    May you find forgiveness for yourself and forgive others.
90668 **    May you share freely, never taking more than you give.
90669 **
90670 *************************************************************************
90671 ** This header file defines the SQLite interface for use by
90672 ** shared libraries that want to be imported as extensions into
90673 ** an SQLite instance.  Shared libraries that intend to be loaded
90674 ** as extensions by SQLite should #include this file instead of 
90675 ** sqlcipher3.h.
90676 */
90677 #ifndef _SQLCIPHER3EXT_H_
90678 #define _SQLCIPHER3EXT_H_
90679
90680 typedef struct sqlcipher3_api_routines sqlcipher3_api_routines;
90681
90682 /*
90683 ** The following structure holds pointers to all of the SQLite API
90684 ** routines.
90685 **
90686 ** WARNING:  In order to maintain backwards compatibility, add new
90687 ** interfaces to the end of this structure only.  If you insert new
90688 ** interfaces in the middle of this structure, then older different
90689 ** versions of SQLite will not be able to load each others' shared
90690 ** libraries!
90691 */
90692 struct sqlcipher3_api_routines {
90693   void * (*aggregate_context)(sqlcipher3_context*,int nBytes);
90694   int  (*aggregate_count)(sqlcipher3_context*);
90695   int  (*bind_blob)(sqlcipher3_stmt*,int,const void*,int n,void(*)(void*));
90696   int  (*bind_double)(sqlcipher3_stmt*,int,double);
90697   int  (*bind_int)(sqlcipher3_stmt*,int,int);
90698   int  (*bind_int64)(sqlcipher3_stmt*,int,sqlcipher_int64);
90699   int  (*bind_null)(sqlcipher3_stmt*,int);
90700   int  (*bind_parameter_count)(sqlcipher3_stmt*);
90701   int  (*bind_parameter_index)(sqlcipher3_stmt*,const char*zName);
90702   const char * (*bind_parameter_name)(sqlcipher3_stmt*,int);
90703   int  (*bind_text)(sqlcipher3_stmt*,int,const char*,int n,void(*)(void*));
90704   int  (*bind_text16)(sqlcipher3_stmt*,int,const void*,int,void(*)(void*));
90705   int  (*bind_value)(sqlcipher3_stmt*,int,const sqlcipher3_value*);
90706   int  (*busy_handler)(sqlcipher3*,int(*)(void*,int),void*);
90707   int  (*busy_timeout)(sqlcipher3*,int ms);
90708   int  (*changes)(sqlcipher3*);
90709   int  (*close)(sqlcipher3*);
90710   int  (*collation_needed)(sqlcipher3*,void*,void(*)(void*,sqlcipher3*,
90711                            int eTextRep,const char*));
90712   int  (*collation_needed16)(sqlcipher3*,void*,void(*)(void*,sqlcipher3*,
90713                              int eTextRep,const void*));
90714   const void * (*column_blob)(sqlcipher3_stmt*,int iCol);
90715   int  (*column_bytes)(sqlcipher3_stmt*,int iCol);
90716   int  (*column_bytes16)(sqlcipher3_stmt*,int iCol);
90717   int  (*column_count)(sqlcipher3_stmt*pStmt);
90718   const char * (*column_database_name)(sqlcipher3_stmt*,int);
90719   const void * (*column_database_name16)(sqlcipher3_stmt*,int);
90720   const char * (*column_decltype)(sqlcipher3_stmt*,int i);
90721   const void * (*column_decltype16)(sqlcipher3_stmt*,int);
90722   double  (*column_double)(sqlcipher3_stmt*,int iCol);
90723   int  (*column_int)(sqlcipher3_stmt*,int iCol);
90724   sqlcipher_int64  (*column_int64)(sqlcipher3_stmt*,int iCol);
90725   const char * (*column_name)(sqlcipher3_stmt*,int);
90726   const void * (*column_name16)(sqlcipher3_stmt*,int);
90727   const char * (*column_origin_name)(sqlcipher3_stmt*,int);
90728   const void * (*column_origin_name16)(sqlcipher3_stmt*,int);
90729   const char * (*column_table_name)(sqlcipher3_stmt*,int);
90730   const void * (*column_table_name16)(sqlcipher3_stmt*,int);
90731   const unsigned char * (*column_text)(sqlcipher3_stmt*,int iCol);
90732   const void * (*column_text16)(sqlcipher3_stmt*,int iCol);
90733   int  (*column_type)(sqlcipher3_stmt*,int iCol);
90734   sqlcipher3_value* (*column_value)(sqlcipher3_stmt*,int iCol);
90735   void * (*commit_hook)(sqlcipher3*,int(*)(void*),void*);
90736   int  (*complete)(const char*sql);
90737   int  (*complete16)(const void*sql);
90738   int  (*create_collation)(sqlcipher3*,const char*,int,void*,
90739                            int(*)(void*,int,const void*,int,const void*));
90740   int  (*create_collation16)(sqlcipher3*,const void*,int,void*,
90741                              int(*)(void*,int,const void*,int,const void*));
90742   int  (*create_function)(sqlcipher3*,const char*,int,int,void*,
90743                           void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
90744                           void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
90745                           void (*xFinal)(sqlcipher3_context*));
90746   int  (*create_function16)(sqlcipher3*,const void*,int,int,void*,
90747                             void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
90748                             void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
90749                             void (*xFinal)(sqlcipher3_context*));
90750   int (*create_module)(sqlcipher3*,const char*,const sqlcipher3_module*,void*);
90751   int  (*data_count)(sqlcipher3_stmt*pStmt);
90752   sqlcipher3 * (*db_handle)(sqlcipher3_stmt*);
90753   int (*declare_vtab)(sqlcipher3*,const char*);
90754   int  (*enable_shared_cache)(int);
90755   int  (*errcode)(sqlcipher3*db);
90756   const char * (*errmsg)(sqlcipher3*);
90757   const void * (*errmsg16)(sqlcipher3*);
90758   int  (*exec)(sqlcipher3*,const char*,sqlcipher3_callback,void*,char**);
90759   int  (*expired)(sqlcipher3_stmt*);
90760   int  (*finalize)(sqlcipher3_stmt*pStmt);
90761   void  (*free)(void*);
90762   void  (*free_table)(char**result);
90763   int  (*get_autocommit)(sqlcipher3*);
90764   void * (*get_auxdata)(sqlcipher3_context*,int);
90765   int  (*get_table)(sqlcipher3*,const char*,char***,int*,int*,char**);
90766   int  (*global_recover)(void);
90767   void  (*interruptx)(sqlcipher3*);
90768   sqlcipher_int64  (*last_insert_rowid)(sqlcipher3*);
90769   const char * (*libversion)(void);
90770   int  (*libversion_number)(void);
90771   void *(*malloc)(int);
90772   char * (*mprintf)(const char*,...);
90773   int  (*open)(const char*,sqlcipher3**);
90774   int  (*open16)(const void*,sqlcipher3**);
90775   int  (*prepare)(sqlcipher3*,const char*,int,sqlcipher3_stmt**,const char**);
90776   int  (*prepare16)(sqlcipher3*,const void*,int,sqlcipher3_stmt**,const void**);
90777   void * (*profile)(sqlcipher3*,void(*)(void*,const char*,sqlcipher_uint64),void*);
90778   void  (*progress_handler)(sqlcipher3*,int,int(*)(void*),void*);
90779   void *(*realloc)(void*,int);
90780   int  (*reset)(sqlcipher3_stmt*pStmt);
90781   void  (*result_blob)(sqlcipher3_context*,const void*,int,void(*)(void*));
90782   void  (*result_double)(sqlcipher3_context*,double);
90783   void  (*result_error)(sqlcipher3_context*,const char*,int);
90784   void  (*result_error16)(sqlcipher3_context*,const void*,int);
90785   void  (*result_int)(sqlcipher3_context*,int);
90786   void  (*result_int64)(sqlcipher3_context*,sqlcipher_int64);
90787   void  (*result_null)(sqlcipher3_context*);
90788   void  (*result_text)(sqlcipher3_context*,const char*,int,void(*)(void*));
90789   void  (*result_text16)(sqlcipher3_context*,const void*,int,void(*)(void*));
90790   void  (*result_text16be)(sqlcipher3_context*,const void*,int,void(*)(void*));
90791   void  (*result_text16le)(sqlcipher3_context*,const void*,int,void(*)(void*));
90792   void  (*result_value)(sqlcipher3_context*,sqlcipher3_value*);
90793   void * (*rollback_hook)(sqlcipher3*,void(*)(void*),void*);
90794   int  (*set_authorizer)(sqlcipher3*,int(*)(void*,int,const char*,const char*,
90795                          const char*,const char*),void*);
90796   void  (*set_auxdata)(sqlcipher3_context*,int,void*,void (*)(void*));
90797   char * (*snprintf)(int,char*,const char*,...);
90798   int  (*step)(sqlcipher3_stmt*);
90799   int  (*table_column_metadata)(sqlcipher3*,const char*,const char*,const char*,
90800                                 char const**,char const**,int*,int*,int*);
90801   void  (*thread_cleanup)(void);
90802   int  (*total_changes)(sqlcipher3*);
90803   void * (*trace)(sqlcipher3*,void(*xTrace)(void*,const char*),void*);
90804   int  (*transfer_bindings)(sqlcipher3_stmt*,sqlcipher3_stmt*);
90805   void * (*update_hook)(sqlcipher3*,void(*)(void*,int ,char const*,char const*,
90806                                          sqlcipher_int64),void*);
90807   void * (*user_data)(sqlcipher3_context*);
90808   const void * (*value_blob)(sqlcipher3_value*);
90809   int  (*value_bytes)(sqlcipher3_value*);
90810   int  (*value_bytes16)(sqlcipher3_value*);
90811   double  (*value_double)(sqlcipher3_value*);
90812   int  (*value_int)(sqlcipher3_value*);
90813   sqlcipher_int64  (*value_int64)(sqlcipher3_value*);
90814   int  (*value_numeric_type)(sqlcipher3_value*);
90815   const unsigned char * (*value_text)(sqlcipher3_value*);
90816   const void * (*value_text16)(sqlcipher3_value*);
90817   const void * (*value_text16be)(sqlcipher3_value*);
90818   const void * (*value_text16le)(sqlcipher3_value*);
90819   int  (*value_type)(sqlcipher3_value*);
90820   char *(*vmprintf)(const char*,va_list);
90821   /* Added ??? */
90822   int (*overload_function)(sqlcipher3*, const char *zFuncName, int nArg);
90823   /* Added by 3.3.13 */
90824   int (*prepare_v2)(sqlcipher3*,const char*,int,sqlcipher3_stmt**,const char**);
90825   int (*prepare16_v2)(sqlcipher3*,const void*,int,sqlcipher3_stmt**,const void**);
90826   int (*clear_bindings)(sqlcipher3_stmt*);
90827   /* Added by 3.4.1 */
90828   int (*create_module_v2)(sqlcipher3*,const char*,const sqlcipher3_module*,void*,
90829                           void (*xDestroy)(void *));
90830   /* Added by 3.5.0 */
90831   int (*bind_zeroblob)(sqlcipher3_stmt*,int,int);
90832   int (*blob_bytes)(sqlcipher3_blob*);
90833   int (*blob_close)(sqlcipher3_blob*);
90834   int (*blob_open)(sqlcipher3*,const char*,const char*,const char*,sqlcipher3_int64,
90835                    int,sqlcipher3_blob**);
90836   int (*blob_read)(sqlcipher3_blob*,void*,int,int);
90837   int (*blob_write)(sqlcipher3_blob*,const void*,int,int);
90838   int (*create_collation_v2)(sqlcipher3*,const char*,int,void*,
90839                              int(*)(void*,int,const void*,int,const void*),
90840                              void(*)(void*));
90841   int (*file_control)(sqlcipher3*,const char*,int,void*);
90842   sqlcipher3_int64 (*memory_highwater)(int);
90843   sqlcipher3_int64 (*memory_used)(void);
90844   sqlcipher3_mutex *(*mutex_alloc)(int);
90845   void (*mutex_enter)(sqlcipher3_mutex*);
90846   void (*mutex_free)(sqlcipher3_mutex*);
90847   void (*mutex_leave)(sqlcipher3_mutex*);
90848   int (*mutex_try)(sqlcipher3_mutex*);
90849   int (*open_v2)(const char*,sqlcipher3**,int,const char*);
90850   int (*release_memory)(int);
90851   void (*result_error_nomem)(sqlcipher3_context*);
90852   void (*result_error_toobig)(sqlcipher3_context*);
90853   int (*sleep)(int);
90854   void (*soft_heap_limit)(int);
90855   sqlcipher3_vfs *(*vfs_find)(const char*);
90856   int (*vfs_register)(sqlcipher3_vfs*,int);
90857   int (*vfs_unregister)(sqlcipher3_vfs*);
90858   int (*xthreadsafe)(void);
90859   void (*result_zeroblob)(sqlcipher3_context*,int);
90860   void (*result_error_code)(sqlcipher3_context*,int);
90861   int (*test_control)(int, ...);
90862   void (*randomness)(int,void*);
90863   sqlcipher3 *(*context_db_handle)(sqlcipher3_context*);
90864   int (*extended_result_codes)(sqlcipher3*,int);
90865   int (*limit)(sqlcipher3*,int,int);
90866   sqlcipher3_stmt *(*next_stmt)(sqlcipher3*,sqlcipher3_stmt*);
90867   const char *(*sql)(sqlcipher3_stmt*);
90868   int (*status)(int,int*,int*,int);
90869   int (*backup_finish)(sqlcipher3_backup*);
90870   sqlcipher3_backup *(*backup_init)(sqlcipher3*,const char*,sqlcipher3*,const char*);
90871   int (*backup_pagecount)(sqlcipher3_backup*);
90872   int (*backup_remaining)(sqlcipher3_backup*);
90873   int (*backup_step)(sqlcipher3_backup*,int);
90874   const char *(*compileoption_get)(int);
90875   int (*compileoption_used)(const char*);
90876   int (*create_function_v2)(sqlcipher3*,const char*,int,int,void*,
90877                             void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
90878                             void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
90879                             void (*xFinal)(sqlcipher3_context*),
90880                             void(*xDestroy)(void*));
90881   int (*db_config)(sqlcipher3*,int,...);
90882   sqlcipher3_mutex *(*db_mutex)(sqlcipher3*);
90883   int (*db_status)(sqlcipher3*,int,int*,int*,int);
90884   int (*extended_errcode)(sqlcipher3*);
90885   void (*log)(int,const char*,...);
90886   sqlcipher3_int64 (*soft_heap_limit64)(sqlcipher3_int64);
90887   const char *(*sourceid)(void);
90888   int (*stmt_status)(sqlcipher3_stmt*,int,int);
90889   int (*strnicmp)(const char*,const char*,int);
90890   int (*unlock_notify)(sqlcipher3*,void(*)(void**,int),void*);
90891   int (*wal_autocheckpoint)(sqlcipher3*,int);
90892   int (*wal_checkpoint)(sqlcipher3*,const char*);
90893   void *(*wal_hook)(sqlcipher3*,int(*)(void*,sqlcipher3*,const char*,int),void*);
90894   int (*blob_reopen)(sqlcipher3_blob*,sqlcipher3_int64);
90895   int (*vtab_config)(sqlcipher3*,int op,...);
90896   int (*vtab_on_conflict)(sqlcipher3*);
90897 };
90898
90899 /*
90900 ** The following macros redefine the API routines so that they are
90901 ** redirected throught the global sqlcipher3_api structure.
90902 **
90903 ** This header file is also used by the loadext.c source file
90904 ** (part of the main SQLite library - not an extension) so that
90905 ** it can get access to the sqlcipher3_api_routines structure
90906 ** definition.  But the main library does not want to redefine
90907 ** the API.  So the redefinition macros are only valid if the
90908 ** SQLCIPHER_CORE macros is undefined.
90909 */
90910 #ifndef SQLCIPHER_CORE
90911 #define sqlcipher3_aggregate_context      sqlcipher3_api->aggregate_context
90912 #ifndef SQLCIPHER_OMIT_DEPRECATED
90913 #define sqlcipher3_aggregate_count        sqlcipher3_api->aggregate_count
90914 #endif
90915 #define sqlcipher3_bind_blob              sqlcipher3_api->bind_blob
90916 #define sqlcipher3_bind_double            sqlcipher3_api->bind_double
90917 #define sqlcipher3_bind_int               sqlcipher3_api->bind_int
90918 #define sqlcipher3_bind_int64             sqlcipher3_api->bind_int64
90919 #define sqlcipher3_bind_null              sqlcipher3_api->bind_null
90920 #define sqlcipher3_bind_parameter_count   sqlcipher3_api->bind_parameter_count
90921 #define sqlcipher3_bind_parameter_index   sqlcipher3_api->bind_parameter_index
90922 #define sqlcipher3_bind_parameter_name    sqlcipher3_api->bind_parameter_name
90923 #define sqlcipher3_bind_text              sqlcipher3_api->bind_text
90924 #define sqlcipher3_bind_text16            sqlcipher3_api->bind_text16
90925 #define sqlcipher3_bind_value             sqlcipher3_api->bind_value
90926 #define sqlcipher3_busy_handler           sqlcipher3_api->busy_handler
90927 #define sqlcipher3_busy_timeout           sqlcipher3_api->busy_timeout
90928 #define sqlcipher3_changes                sqlcipher3_api->changes
90929 #define sqlcipher3_close                  sqlcipher3_api->close
90930 #define sqlcipher3_collation_needed       sqlcipher3_api->collation_needed
90931 #define sqlcipher3_collation_needed16     sqlcipher3_api->collation_needed16
90932 #define sqlcipher3_column_blob            sqlcipher3_api->column_blob
90933 #define sqlcipher3_column_bytes           sqlcipher3_api->column_bytes
90934 #define sqlcipher3_column_bytes16         sqlcipher3_api->column_bytes16
90935 #define sqlcipher3_column_count           sqlcipher3_api->column_count
90936 #define sqlcipher3_column_database_name   sqlcipher3_api->column_database_name
90937 #define sqlcipher3_column_database_name16 sqlcipher3_api->column_database_name16
90938 #define sqlcipher3_column_decltype        sqlcipher3_api->column_decltype
90939 #define sqlcipher3_column_decltype16      sqlcipher3_api->column_decltype16
90940 #define sqlcipher3_column_double          sqlcipher3_api->column_double
90941 #define sqlcipher3_column_int             sqlcipher3_api->column_int
90942 #define sqlcipher3_column_int64           sqlcipher3_api->column_int64
90943 #define sqlcipher3_column_name            sqlcipher3_api->column_name
90944 #define sqlcipher3_column_name16          sqlcipher3_api->column_name16
90945 #define sqlcipher3_column_origin_name     sqlcipher3_api->column_origin_name
90946 #define sqlcipher3_column_origin_name16   sqlcipher3_api->column_origin_name16
90947 #define sqlcipher3_column_table_name      sqlcipher3_api->column_table_name
90948 #define sqlcipher3_column_table_name16    sqlcipher3_api->column_table_name16
90949 #define sqlcipher3_column_text            sqlcipher3_api->column_text
90950 #define sqlcipher3_column_text16          sqlcipher3_api->column_text16
90951 #define sqlcipher3_column_type            sqlcipher3_api->column_type
90952 #define sqlcipher3_column_value           sqlcipher3_api->column_value
90953 #define sqlcipher3_commit_hook            sqlcipher3_api->commit_hook
90954 #define sqlcipher3_complete               sqlcipher3_api->complete
90955 #define sqlcipher3_complete16             sqlcipher3_api->complete16
90956 #define sqlcipher3_create_collation       sqlcipher3_api->create_collation
90957 #define sqlcipher3_create_collation16     sqlcipher3_api->create_collation16
90958 #define sqlcipher3_create_function        sqlcipher3_api->create_function
90959 #define sqlcipher3_create_function16      sqlcipher3_api->create_function16
90960 #define sqlcipher3_create_module          sqlcipher3_api->create_module
90961 #define sqlcipher3_create_module_v2       sqlcipher3_api->create_module_v2
90962 #define sqlcipher3_data_count             sqlcipher3_api->data_count
90963 #define sqlcipher3_db_handle              sqlcipher3_api->db_handle
90964 #define sqlcipher3_declare_vtab           sqlcipher3_api->declare_vtab
90965 #define sqlcipher3_enable_shared_cache    sqlcipher3_api->enable_shared_cache
90966 #define sqlcipher3_errcode                sqlcipher3_api->errcode
90967 #define sqlcipher3_errmsg                 sqlcipher3_api->errmsg
90968 #define sqlcipher3_errmsg16               sqlcipher3_api->errmsg16
90969 #define sqlcipher3_exec                   sqlcipher3_api->exec
90970 #ifndef SQLCIPHER_OMIT_DEPRECATED
90971 #define sqlcipher3_expired                sqlcipher3_api->expired
90972 #endif
90973 #define sqlcipher3_finalize               sqlcipher3_api->finalize
90974 #define sqlcipher3_free                   sqlcipher3_api->free
90975 #define sqlcipher3_free_table             sqlcipher3_api->free_table
90976 #define sqlcipher3_get_autocommit         sqlcipher3_api->get_autocommit
90977 #define sqlcipher3_get_auxdata            sqlcipher3_api->get_auxdata
90978 #define sqlcipher3_get_table              sqlcipher3_api->get_table
90979 #ifndef SQLCIPHER_OMIT_DEPRECATED
90980 #define sqlcipher3_global_recover         sqlcipher3_api->global_recover
90981 #endif
90982 #define sqlcipher3_interrupt              sqlcipher3_api->interruptx
90983 #define sqlcipher3_last_insert_rowid      sqlcipher3_api->last_insert_rowid
90984 #define sqlcipher3_libversion             sqlcipher3_api->libversion
90985 #define sqlcipher3_libversion_number      sqlcipher3_api->libversion_number
90986 #define sqlcipher3_malloc                 sqlcipher3_api->malloc
90987 #define sqlcipher3_mprintf                sqlcipher3_api->mprintf
90988 #define sqlcipher3_open                   sqlcipher3_api->open
90989 #define sqlcipher3_open16                 sqlcipher3_api->open16
90990 #define sqlcipher3_prepare                sqlcipher3_api->prepare
90991 #define sqlcipher3_prepare16              sqlcipher3_api->prepare16
90992 #define sqlcipher3_prepare_v2             sqlcipher3_api->prepare_v2
90993 #define sqlcipher3_prepare16_v2           sqlcipher3_api->prepare16_v2
90994 #define sqlcipher3_profile                sqlcipher3_api->profile
90995 #define sqlcipher3_progress_handler       sqlcipher3_api->progress_handler
90996 #define sqlcipher3_realloc                sqlcipher3_api->realloc
90997 #define sqlcipher3_reset                  sqlcipher3_api->reset
90998 #define sqlcipher3_result_blob            sqlcipher3_api->result_blob
90999 #define sqlcipher3_result_double          sqlcipher3_api->result_double
91000 #define sqlcipher3_result_error           sqlcipher3_api->result_error
91001 #define sqlcipher3_result_error16         sqlcipher3_api->result_error16
91002 #define sqlcipher3_result_int             sqlcipher3_api->result_int
91003 #define sqlcipher3_result_int64           sqlcipher3_api->result_int64
91004 #define sqlcipher3_result_null            sqlcipher3_api->result_null
91005 #define sqlcipher3_result_text            sqlcipher3_api->result_text
91006 #define sqlcipher3_result_text16          sqlcipher3_api->result_text16
91007 #define sqlcipher3_result_text16be        sqlcipher3_api->result_text16be
91008 #define sqlcipher3_result_text16le        sqlcipher3_api->result_text16le
91009 #define sqlcipher3_result_value           sqlcipher3_api->result_value
91010 #define sqlcipher3_rollback_hook          sqlcipher3_api->rollback_hook
91011 #define sqlcipher3_set_authorizer         sqlcipher3_api->set_authorizer
91012 #define sqlcipher3_set_auxdata            sqlcipher3_api->set_auxdata
91013 #define sqlcipher3_snprintf               sqlcipher3_api->snprintf
91014 #define sqlcipher3_step                   sqlcipher3_api->step
91015 #define sqlcipher3_table_column_metadata  sqlcipher3_api->table_column_metadata
91016 #define sqlcipher3_thread_cleanup         sqlcipher3_api->thread_cleanup
91017 #define sqlcipher3_total_changes          sqlcipher3_api->total_changes
91018 #define sqlcipher3_trace                  sqlcipher3_api->trace
91019 #ifndef SQLCIPHER_OMIT_DEPRECATED
91020 #define sqlcipher3_transfer_bindings      sqlcipher3_api->transfer_bindings
91021 #endif
91022 #define sqlcipher3_update_hook            sqlcipher3_api->update_hook
91023 #define sqlcipher3_user_data              sqlcipher3_api->user_data
91024 #define sqlcipher3_value_blob             sqlcipher3_api->value_blob
91025 #define sqlcipher3_value_bytes            sqlcipher3_api->value_bytes
91026 #define sqlcipher3_value_bytes16          sqlcipher3_api->value_bytes16
91027 #define sqlcipher3_value_double           sqlcipher3_api->value_double
91028 #define sqlcipher3_value_int              sqlcipher3_api->value_int
91029 #define sqlcipher3_value_int64            sqlcipher3_api->value_int64
91030 #define sqlcipher3_value_numeric_type     sqlcipher3_api->value_numeric_type
91031 #define sqlcipher3_value_text             sqlcipher3_api->value_text
91032 #define sqlcipher3_value_text16           sqlcipher3_api->value_text16
91033 #define sqlcipher3_value_text16be         sqlcipher3_api->value_text16be
91034 #define sqlcipher3_value_text16le         sqlcipher3_api->value_text16le
91035 #define sqlcipher3_value_type             sqlcipher3_api->value_type
91036 #define sqlcipher3_vmprintf               sqlcipher3_api->vmprintf
91037 #define sqlcipher3_overload_function      sqlcipher3_api->overload_function
91038 #define sqlcipher3_prepare_v2             sqlcipher3_api->prepare_v2
91039 #define sqlcipher3_prepare16_v2           sqlcipher3_api->prepare16_v2
91040 #define sqlcipher3_clear_bindings         sqlcipher3_api->clear_bindings
91041 #define sqlcipher3_bind_zeroblob          sqlcipher3_api->bind_zeroblob
91042 #define sqlcipher3_blob_bytes             sqlcipher3_api->blob_bytes
91043 #define sqlcipher3_blob_close             sqlcipher3_api->blob_close
91044 #define sqlcipher3_blob_open              sqlcipher3_api->blob_open
91045 #define sqlcipher3_blob_read              sqlcipher3_api->blob_read
91046 #define sqlcipher3_blob_write             sqlcipher3_api->blob_write
91047 #define sqlcipher3_create_collation_v2    sqlcipher3_api->create_collation_v2
91048 #define sqlcipher3_file_control           sqlcipher3_api->file_control
91049 #define sqlcipher3_memory_highwater       sqlcipher3_api->memory_highwater
91050 #define sqlcipher3_memory_used            sqlcipher3_api->memory_used
91051 #define sqlcipher3_mutex_alloc            sqlcipher3_api->mutex_alloc
91052 #define sqlcipher3_mutex_enter            sqlcipher3_api->mutex_enter
91053 #define sqlcipher3_mutex_free             sqlcipher3_api->mutex_free
91054 #define sqlcipher3_mutex_leave            sqlcipher3_api->mutex_leave
91055 #define sqlcipher3_mutex_try              sqlcipher3_api->mutex_try
91056 #define sqlcipher3_open_v2                sqlcipher3_api->open_v2
91057 #define sqlcipher3_release_memory         sqlcipher3_api->release_memory
91058 #define sqlcipher3_result_error_nomem     sqlcipher3_api->result_error_nomem
91059 #define sqlcipher3_result_error_toobig    sqlcipher3_api->result_error_toobig
91060 #define sqlcipher3_sleep                  sqlcipher3_api->sleep
91061 #define sqlcipher3_soft_heap_limit        sqlcipher3_api->soft_heap_limit
91062 #define sqlcipher3_vfs_find               sqlcipher3_api->vfs_find
91063 #define sqlcipher3_vfs_register           sqlcipher3_api->vfs_register
91064 #define sqlcipher3_vfs_unregister         sqlcipher3_api->vfs_unregister
91065 #define sqlcipher3_threadsafe             sqlcipher3_api->xthreadsafe
91066 #define sqlcipher3_result_zeroblob        sqlcipher3_api->result_zeroblob
91067 #define sqlcipher3_result_error_code      sqlcipher3_api->result_error_code
91068 #define sqlcipher3_test_control           sqlcipher3_api->test_control
91069 #define sqlcipher3_randomness             sqlcipher3_api->randomness
91070 #define sqlcipher3_context_db_handle      sqlcipher3_api->context_db_handle
91071 #define sqlcipher3_extended_result_codes  sqlcipher3_api->extended_result_codes
91072 #define sqlcipher3_limit                  sqlcipher3_api->limit
91073 #define sqlcipher3_next_stmt              sqlcipher3_api->next_stmt
91074 #define sqlcipher3_sql                    sqlcipher3_api->sql
91075 #define sqlcipher3_status                 sqlcipher3_api->status
91076 #define sqlcipher3_backup_finish          sqlcipher3_api->backup_finish
91077 #define sqlcipher3_backup_init            sqlcipher3_api->backup_init
91078 #define sqlcipher3_backup_pagecount       sqlcipher3_api->backup_pagecount
91079 #define sqlcipher3_backup_remaining       sqlcipher3_api->backup_remaining
91080 #define sqlcipher3_backup_step            sqlcipher3_api->backup_step
91081 #define sqlcipher3_compileoption_get      sqlcipher3_api->compileoption_get
91082 #define sqlcipher3_compileoption_used     sqlcipher3_api->compileoption_used
91083 #define sqlcipher3_create_function_v2     sqlcipher3_api->create_function_v2
91084 #define sqlcipher3_db_config              sqlcipher3_api->db_config
91085 #define sqlcipher3_db_mutex               sqlcipher3_api->db_mutex
91086 #define sqlcipher3_db_status              sqlcipher3_api->db_status
91087 #define sqlcipher3_extended_errcode       sqlcipher3_api->extended_errcode
91088 #define sqlcipher3_log                    sqlcipher3_api->log
91089 #define sqlcipher3_soft_heap_limit64      sqlcipher3_api->soft_heap_limit64
91090 #define sqlcipher3_sourceid               sqlcipher3_api->sourceid
91091 #define sqlcipher3_stmt_status            sqlcipher3_api->stmt_status
91092 #define sqlcipher3_strnicmp               sqlcipher3_api->strnicmp
91093 #define sqlcipher3_unlock_notify          sqlcipher3_api->unlock_notify
91094 #define sqlcipher3_wal_autocheckpoint     sqlcipher3_api->wal_autocheckpoint
91095 #define sqlcipher3_wal_checkpoint         sqlcipher3_api->wal_checkpoint
91096 #define sqlcipher3_wal_hook               sqlcipher3_api->wal_hook
91097 #define sqlcipher3_blob_reopen            sqlcipher3_api->blob_reopen
91098 #define sqlcipher3_vtab_config            sqlcipher3_api->vtab_config
91099 #define sqlcipher3_vtab_on_conflict       sqlcipher3_api->vtab_on_conflict
91100 #endif /* SQLCIPHER_CORE */
91101
91102 #define SQLCIPHER_EXTENSION_INIT1     const sqlcipher3_api_routines *sqlcipher3_api = 0;
91103 #define SQLCIPHER_EXTENSION_INIT2(v)  sqlcipher3_api = v;
91104
91105 #endif /* _SQLCIPHER3EXT_H_ */
91106
91107 /************** End of sqlcipher3ext.h ******************************************/
91108 /************** Continuing where we left off in loadext.c ********************/
91109 /* #include <string.h> */
91110
91111 #ifndef SQLCIPHER_OMIT_LOAD_EXTENSION
91112
91113 /*
91114 ** Some API routines are omitted when various features are
91115 ** excluded from a build of SQLite.  Substitute a NULL pointer
91116 ** for any missing APIs.
91117 */
91118 #ifndef SQLCIPHER_ENABLE_COLUMN_METADATA
91119 # define sqlcipher3_column_database_name   0
91120 # define sqlcipher3_column_database_name16 0
91121 # define sqlcipher3_column_table_name      0
91122 # define sqlcipher3_column_table_name16    0
91123 # define sqlcipher3_column_origin_name     0
91124 # define sqlcipher3_column_origin_name16   0
91125 # define sqlcipher3_table_column_metadata  0
91126 #endif
91127
91128 #ifdef SQLCIPHER_OMIT_AUTHORIZATION
91129 # define sqlcipher3_set_authorizer         0
91130 #endif
91131
91132 #ifdef SQLCIPHER_OMIT_UTF16
91133 # define sqlcipher3_bind_text16            0
91134 # define sqlcipher3_collation_needed16     0
91135 # define sqlcipher3_column_decltype16      0
91136 # define sqlcipher3_column_name16          0
91137 # define sqlcipher3_column_text16          0
91138 # define sqlcipher3_complete16             0
91139 # define sqlcipher3_create_collation16     0
91140 # define sqlcipher3_create_function16      0
91141 # define sqlcipher3_errmsg16               0
91142 # define sqlcipher3_open16                 0
91143 # define sqlcipher3_prepare16              0
91144 # define sqlcipher3_prepare16_v2           0
91145 # define sqlcipher3_result_error16         0
91146 # define sqlcipher3_result_text16          0
91147 # define sqlcipher3_result_text16be        0
91148 # define sqlcipher3_result_text16le        0
91149 # define sqlcipher3_value_text16           0
91150 # define sqlcipher3_value_text16be         0
91151 # define sqlcipher3_value_text16le         0
91152 # define sqlcipher3_column_database_name16 0
91153 # define sqlcipher3_column_table_name16    0
91154 # define sqlcipher3_column_origin_name16   0
91155 #endif
91156
91157 #ifdef SQLCIPHER_OMIT_COMPLETE
91158 # define sqlcipher3_complete 0
91159 # define sqlcipher3_complete16 0
91160 #endif
91161
91162 #ifdef SQLCIPHER_OMIT_DECLTYPE
91163 # define sqlcipher3_column_decltype16      0
91164 # define sqlcipher3_column_decltype        0
91165 #endif
91166
91167 #ifdef SQLCIPHER_OMIT_PROGRESS_CALLBACK
91168 # define sqlcipher3_progress_handler 0
91169 #endif
91170
91171 #ifdef SQLCIPHER_OMIT_VIRTUALTABLE
91172 # define sqlcipher3_create_module 0
91173 # define sqlcipher3_create_module_v2 0
91174 # define sqlcipher3_declare_vtab 0
91175 # define sqlcipher3_vtab_config 0
91176 # define sqlcipher3_vtab_on_conflict 0
91177 #endif
91178
91179 #ifdef SQLCIPHER_OMIT_SHARED_CACHE
91180 # define sqlcipher3_enable_shared_cache 0
91181 #endif
91182
91183 #ifdef SQLCIPHER_OMIT_TRACE
91184 # define sqlcipher3_profile       0
91185 # define sqlcipher3_trace         0
91186 #endif
91187
91188 #ifdef SQLCIPHER_OMIT_GET_TABLE
91189 # define sqlcipher3_free_table    0
91190 # define sqlcipher3_get_table     0
91191 #endif
91192
91193 #ifdef SQLCIPHER_OMIT_INCRBLOB
91194 #define sqlcipher3_bind_zeroblob  0
91195 #define sqlcipher3_blob_bytes     0
91196 #define sqlcipher3_blob_close     0
91197 #define sqlcipher3_blob_open      0
91198 #define sqlcipher3_blob_read      0
91199 #define sqlcipher3_blob_write     0
91200 #define sqlcipher3_blob_reopen    0
91201 #endif
91202
91203 /*
91204 ** The following structure contains pointers to all SQLite API routines.
91205 ** A pointer to this structure is passed into extensions when they are
91206 ** loaded so that the extension can make calls back into the SQLite
91207 ** library.
91208 **
91209 ** When adding new APIs, add them to the bottom of this structure
91210 ** in order to preserve backwards compatibility.
91211 **
91212 ** Extensions that use newer APIs should first call the
91213 ** sqlcipher3_libversion_number() to make sure that the API they
91214 ** intend to use is supported by the library.  Extensions should
91215 ** also check to make sure that the pointer to the function is
91216 ** not NULL before calling it.
91217 */
91218 static const sqlcipher3_api_routines sqlcipher3Apis = {
91219   sqlcipher3_aggregate_context,
91220 #ifndef SQLCIPHER_OMIT_DEPRECATED
91221   sqlcipher3_aggregate_count,
91222 #else
91223   0,
91224 #endif
91225   sqlcipher3_bind_blob,
91226   sqlcipher3_bind_double,
91227   sqlcipher3_bind_int,
91228   sqlcipher3_bind_int64,
91229   sqlcipher3_bind_null,
91230   sqlcipher3_bind_parameter_count,
91231   sqlcipher3_bind_parameter_index,
91232   sqlcipher3_bind_parameter_name,
91233   sqlcipher3_bind_text,
91234   sqlcipher3_bind_text16,
91235   sqlcipher3_bind_value,
91236   sqlcipher3_busy_handler,
91237   sqlcipher3_busy_timeout,
91238   sqlcipher3_changes,
91239   sqlcipher3_close,
91240   sqlcipher3_collation_needed,
91241   sqlcipher3_collation_needed16,
91242   sqlcipher3_column_blob,
91243   sqlcipher3_column_bytes,
91244   sqlcipher3_column_bytes16,
91245   sqlcipher3_column_count,
91246   sqlcipher3_column_database_name,
91247   sqlcipher3_column_database_name16,
91248   sqlcipher3_column_decltype,
91249   sqlcipher3_column_decltype16,
91250   sqlcipher3_column_double,
91251   sqlcipher3_column_int,
91252   sqlcipher3_column_int64,
91253   sqlcipher3_column_name,
91254   sqlcipher3_column_name16,
91255   sqlcipher3_column_origin_name,
91256   sqlcipher3_column_origin_name16,
91257   sqlcipher3_column_table_name,
91258   sqlcipher3_column_table_name16,
91259   sqlcipher3_column_text,
91260   sqlcipher3_column_text16,
91261   sqlcipher3_column_type,
91262   sqlcipher3_column_value,
91263   sqlcipher3_commit_hook,
91264   sqlcipher3_complete,
91265   sqlcipher3_complete16,
91266   sqlcipher3_create_collation,
91267   sqlcipher3_create_collation16,
91268   sqlcipher3_create_function,
91269   sqlcipher3_create_function16,
91270   sqlcipher3_create_module,
91271   sqlcipher3_data_count,
91272   sqlcipher3_db_handle,
91273   sqlcipher3_declare_vtab,
91274   sqlcipher3_enable_shared_cache,
91275   sqlcipher3_errcode,
91276   sqlcipher3_errmsg,
91277   sqlcipher3_errmsg16,
91278   sqlcipher3_exec,
91279 #ifndef SQLCIPHER_OMIT_DEPRECATED
91280   sqlcipher3_expired,
91281 #else
91282   0,
91283 #endif
91284   sqlcipher3_finalize,
91285   sqlcipher3_free,
91286   sqlcipher3_free_table,
91287   sqlcipher3_get_autocommit,
91288   sqlcipher3_get_auxdata,
91289   sqlcipher3_get_table,
91290   0,     /* Was sqlcipher3_global_recover(), but that function is deprecated */
91291   sqlcipher3_interrupt,
91292   sqlcipher3_last_insert_rowid,
91293   sqlcipher3_libversion,
91294   sqlcipher3_libversion_number,
91295   sqlcipher3_malloc,
91296   sqlcipher3_mprintf,
91297   sqlcipher3_open,
91298   sqlcipher3_open16,
91299   sqlcipher3_prepare,
91300   sqlcipher3_prepare16,
91301   sqlcipher3_profile,
91302   sqlcipher3_progress_handler,
91303   sqlcipher3_realloc,
91304   sqlcipher3_reset,
91305   sqlcipher3_result_blob,
91306   sqlcipher3_result_double,
91307   sqlcipher3_result_error,
91308   sqlcipher3_result_error16,
91309   sqlcipher3_result_int,
91310   sqlcipher3_result_int64,
91311   sqlcipher3_result_null,
91312   sqlcipher3_result_text,
91313   sqlcipher3_result_text16,
91314   sqlcipher3_result_text16be,
91315   sqlcipher3_result_text16le,
91316   sqlcipher3_result_value,
91317   sqlcipher3_rollback_hook,
91318   sqlcipher3_set_authorizer,
91319   sqlcipher3_set_auxdata,
91320   sqlcipher3_snprintf,
91321   sqlcipher3_step,
91322   sqlcipher3_table_column_metadata,
91323 #ifndef SQLCIPHER_OMIT_DEPRECATED
91324   sqlcipher3_thread_cleanup,
91325 #else
91326   0,
91327 #endif
91328   sqlcipher3_total_changes,
91329   sqlcipher3_trace,
91330 #ifndef SQLCIPHER_OMIT_DEPRECATED
91331   sqlcipher3_transfer_bindings,
91332 #else
91333   0,
91334 #endif
91335   sqlcipher3_update_hook,
91336   sqlcipher3_user_data,
91337   sqlcipher3_value_blob,
91338   sqlcipher3_value_bytes,
91339   sqlcipher3_value_bytes16,
91340   sqlcipher3_value_double,
91341   sqlcipher3_value_int,
91342   sqlcipher3_value_int64,
91343   sqlcipher3_value_numeric_type,
91344   sqlcipher3_value_text,
91345   sqlcipher3_value_text16,
91346   sqlcipher3_value_text16be,
91347   sqlcipher3_value_text16le,
91348   sqlcipher3_value_type,
91349   sqlcipher3_vmprintf,
91350   /*
91351   ** The original API set ends here.  All extensions can call any
91352   ** of the APIs above provided that the pointer is not NULL.  But
91353   ** before calling APIs that follow, extension should check the
91354   ** sqlcipher3_libversion_number() to make sure they are dealing with
91355   ** a library that is new enough to support that API.
91356   *************************************************************************
91357   */
91358   sqlcipher3_overload_function,
91359
91360   /*
91361   ** Added after 3.3.13
91362   */
91363   sqlcipher3_prepare_v2,
91364   sqlcipher3_prepare16_v2,
91365   sqlcipher3_clear_bindings,
91366
91367   /*
91368   ** Added for 3.4.1
91369   */
91370   sqlcipher3_create_module_v2,
91371
91372   /*
91373   ** Added for 3.5.0
91374   */
91375   sqlcipher3_bind_zeroblob,
91376   sqlcipher3_blob_bytes,
91377   sqlcipher3_blob_close,
91378   sqlcipher3_blob_open,
91379   sqlcipher3_blob_read,
91380   sqlcipher3_blob_write,
91381   sqlcipher3_create_collation_v2,
91382   sqlcipher3_file_control,
91383   sqlcipher3_memory_highwater,
91384   sqlcipher3_memory_used,
91385 #ifdef SQLCIPHER_MUTEX_OMIT
91386   0, 
91387   0, 
91388   0,
91389   0,
91390   0,
91391 #else
91392   sqlcipher3_mutex_alloc,
91393   sqlcipher3_mutex_enter,
91394   sqlcipher3_mutex_free,
91395   sqlcipher3_mutex_leave,
91396   sqlcipher3_mutex_try,
91397 #endif
91398   sqlcipher3_open_v2,
91399   sqlcipher3_release_memory,
91400   sqlcipher3_result_error_nomem,
91401   sqlcipher3_result_error_toobig,
91402   sqlcipher3_sleep,
91403   sqlcipher3_soft_heap_limit,
91404   sqlcipher3_vfs_find,
91405   sqlcipher3_vfs_register,
91406   sqlcipher3_vfs_unregister,
91407
91408   /*
91409   ** Added for 3.5.8
91410   */
91411   sqlcipher3_threadsafe,
91412   sqlcipher3_result_zeroblob,
91413   sqlcipher3_result_error_code,
91414   sqlcipher3_test_control,
91415   sqlcipher3_randomness,
91416   sqlcipher3_context_db_handle,
91417
91418   /*
91419   ** Added for 3.6.0
91420   */
91421   sqlcipher3_extended_result_codes,
91422   sqlcipher3_limit,
91423   sqlcipher3_next_stmt,
91424   sqlcipher3_sql,
91425   sqlcipher3_status,
91426
91427   /*
91428   ** Added for 3.7.4
91429   */
91430   sqlcipher3_backup_finish,
91431   sqlcipher3_backup_init,
91432   sqlcipher3_backup_pagecount,
91433   sqlcipher3_backup_remaining,
91434   sqlcipher3_backup_step,
91435 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
91436   sqlcipher3_compileoption_get,
91437   sqlcipher3_compileoption_used,
91438 #else
91439   0,
91440   0,
91441 #endif
91442   sqlcipher3_create_function_v2,
91443   sqlcipher3_db_config,
91444   sqlcipher3_db_mutex,
91445   sqlcipher3_db_status,
91446   sqlcipher3_extended_errcode,
91447   sqlcipher3_log,
91448   sqlcipher3_soft_heap_limit64,
91449   sqlcipher3_sourceid,
91450   sqlcipher3_stmt_status,
91451   sqlcipher3_strnicmp,
91452 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
91453   sqlcipher3_unlock_notify,
91454 #else
91455   0,
91456 #endif
91457 #ifndef SQLCIPHER_OMIT_WAL
91458   sqlcipher3_wal_autocheckpoint,
91459   sqlcipher3_wal_checkpoint,
91460   sqlcipher3_wal_hook,
91461 #else
91462   0,
91463   0,
91464   0,
91465 #endif
91466   sqlcipher3_blob_reopen,
91467   sqlcipher3_vtab_config,
91468   sqlcipher3_vtab_on_conflict,
91469 };
91470
91471 /*
91472 ** Attempt to load an SQLite extension library contained in the file
91473 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91474 ** default entry point name (sqlcipher3_extension_init) is used.  Use
91475 ** of the default name is recommended.
91476 **
91477 ** Return SQLCIPHER_OK on success and SQLCIPHER_ERROR if something goes wrong.
91478 **
91479 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
91480 ** error message text.  The calling function should free this memory
91481 ** by calling sqlcipher3DbFree(db, ).
91482 */
91483 static int sqlcipher3LoadExtension(
91484   sqlcipher3 *db,          /* Load the extension into this database connection */
91485   const char *zFile,    /* Name of the shared library containing extension */
91486   const char *zProc,    /* Entry point.  Use "sqlcipher3_extension_init" if 0 */
91487   char **pzErrMsg       /* Put error message here if not 0 */
91488 ){
91489   sqlcipher3_vfs *pVfs = db->pVfs;
91490   void *handle;
91491   int (*xInit)(sqlcipher3*,char**,const sqlcipher3_api_routines*);
91492   char *zErrmsg = 0;
91493   void **aHandle;
91494   int nMsg = 300 + sqlcipher3Strlen30(zFile);
91495
91496   if( pzErrMsg ) *pzErrMsg = 0;
91497
91498   /* Ticket #1863.  To avoid a creating security problems for older
91499   ** applications that relink against newer versions of SQLite, the
91500   ** ability to run load_extension is turned off by default.  One
91501   ** must call sqlcipher3_enable_load_extension() to turn on extension
91502   ** loading.  Otherwise you get the following error.
91503   */
91504   if( (db->flags & SQLCIPHER_LoadExtension)==0 ){
91505     if( pzErrMsg ){
91506       *pzErrMsg = sqlcipher3_mprintf("not authorized");
91507     }
91508     return SQLCIPHER_ERROR;
91509   }
91510
91511   if( zProc==0 ){
91512     zProc = "sqlcipher3_extension_init";
91513   }
91514
91515   handle = sqlcipher3OsDlOpen(pVfs, zFile);
91516   if( handle==0 ){
91517     if( pzErrMsg ){
91518       *pzErrMsg = zErrmsg = sqlcipher3_malloc(nMsg);
91519       if( zErrmsg ){
91520         sqlcipher3_snprintf(nMsg, zErrmsg, 
91521             "unable to open shared library [%s]", zFile);
91522         sqlcipher3OsDlError(pVfs, nMsg-1, zErrmsg);
91523       }
91524     }
91525     return SQLCIPHER_ERROR;
91526   }
91527   xInit = (int(*)(sqlcipher3*,char**,const sqlcipher3_api_routines*))
91528                    sqlcipher3OsDlSym(pVfs, handle, zProc);
91529   if( xInit==0 ){
91530     if( pzErrMsg ){
91531       nMsg += sqlcipher3Strlen30(zProc);
91532       *pzErrMsg = zErrmsg = sqlcipher3_malloc(nMsg);
91533       if( zErrmsg ){
91534         sqlcipher3_snprintf(nMsg, zErrmsg,
91535             "no entry point [%s] in shared library [%s]", zProc,zFile);
91536         sqlcipher3OsDlError(pVfs, nMsg-1, zErrmsg);
91537       }
91538       sqlcipher3OsDlClose(pVfs, handle);
91539     }
91540     return SQLCIPHER_ERROR;
91541   }else if( xInit(db, &zErrmsg, &sqlcipher3Apis) ){
91542     if( pzErrMsg ){
91543       *pzErrMsg = sqlcipher3_mprintf("error during initialization: %s", zErrmsg);
91544     }
91545     sqlcipher3_free(zErrmsg);
91546     sqlcipher3OsDlClose(pVfs, handle);
91547     return SQLCIPHER_ERROR;
91548   }
91549
91550   /* Append the new shared library handle to the db->aExtension array. */
91551   aHandle = sqlcipher3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91552   if( aHandle==0 ){
91553     return SQLCIPHER_NOMEM;
91554   }
91555   if( db->nExtension>0 ){
91556     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91557   }
91558   sqlcipher3DbFree(db, db->aExtension);
91559   db->aExtension = aHandle;
91560
91561   db->aExtension[db->nExtension++] = handle;
91562   return SQLCIPHER_OK;
91563 }
91564 SQLCIPHER_API int sqlcipher3_load_extension(
91565   sqlcipher3 *db,          /* Load the extension into this database connection */
91566   const char *zFile,    /* Name of the shared library containing extension */
91567   const char *zProc,    /* Entry point.  Use "sqlcipher3_extension_init" if 0 */
91568   char **pzErrMsg       /* Put error message here if not 0 */
91569 ){
91570   int rc;
91571   sqlcipher3_mutex_enter(db->mutex);
91572   rc = sqlcipher3LoadExtension(db, zFile, zProc, pzErrMsg);
91573   rc = sqlcipher3ApiExit(db, rc);
91574   sqlcipher3_mutex_leave(db->mutex);
91575   return rc;
91576 }
91577
91578 /*
91579 ** Call this routine when the database connection is closing in order
91580 ** to clean up loaded extensions
91581 */
91582 SQLCIPHER_PRIVATE void sqlcipher3CloseExtensions(sqlcipher3 *db){
91583   int i;
91584   assert( sqlcipher3_mutex_held(db->mutex) );
91585   for(i=0; i<db->nExtension; i++){
91586     sqlcipher3OsDlClose(db->pVfs, db->aExtension[i]);
91587   }
91588   sqlcipher3DbFree(db, db->aExtension);
91589 }
91590
91591 /*
91592 ** Enable or disable extension loading.  Extension loading is disabled by
91593 ** default so as not to open security holes in older applications.
91594 */
91595 SQLCIPHER_API int sqlcipher3_enable_load_extension(sqlcipher3 *db, int onoff){
91596   sqlcipher3_mutex_enter(db->mutex);
91597   if( onoff ){
91598     db->flags |= SQLCIPHER_LoadExtension;
91599   }else{
91600     db->flags &= ~SQLCIPHER_LoadExtension;
91601   }
91602   sqlcipher3_mutex_leave(db->mutex);
91603   return SQLCIPHER_OK;
91604 }
91605
91606 #endif /* SQLCIPHER_OMIT_LOAD_EXTENSION */
91607
91608 /*
91609 ** The auto-extension code added regardless of whether or not extension
91610 ** loading is supported.  We need a dummy sqlcipher3Apis pointer for that
91611 ** code if regular extension loading is not available.  This is that
91612 ** dummy pointer.
91613 */
91614 #ifdef SQLCIPHER_OMIT_LOAD_EXTENSION
91615 static const sqlcipher3_api_routines sqlcipher3Apis = { 0 };
91616 #endif
91617
91618
91619 /*
91620 ** The following object holds the list of automatically loaded
91621 ** extensions.
91622 **
91623 ** This list is shared across threads.  The SQLCIPHER_MUTEX_STATIC_MASTER
91624 ** mutex must be held while accessing this list.
91625 */
91626 typedef struct sqlcipher3AutoExtList sqlcipher3AutoExtList;
91627 static SQLCIPHER_WSD struct sqlcipher3AutoExtList {
91628   int nExt;              /* Number of entries in aExt[] */          
91629   void (**aExt)(void);   /* Pointers to the extension init functions */
91630 } sqlcipher3Autoext = { 0, 0 };
91631
91632 /* The "wsdAutoext" macro will resolve to the autoextension
91633 ** state vector.  If writable static data is unsupported on the target,
91634 ** we have to locate the state vector at run-time.  In the more common
91635 ** case where writable static data is supported, wsdStat can refer directly
91636 ** to the "sqlcipher3Autoext" state vector declared above.
91637 */
91638 #ifdef SQLCIPHER_OMIT_WSD
91639 # define wsdAutoextInit \
91640   sqlcipher3AutoExtList *x = &GLOBAL(sqlcipher3AutoExtList,sqlcipher3Autoext)
91641 # define wsdAutoext x[0]
91642 #else
91643 # define wsdAutoextInit
91644 # define wsdAutoext sqlcipher3Autoext
91645 #endif
91646
91647
91648 /*
91649 ** Register a statically linked extension that is automatically
91650 ** loaded by every new database connection.
91651 */
91652 SQLCIPHER_API int sqlcipher3_auto_extension(void (*xInit)(void)){
91653   int rc = SQLCIPHER_OK;
91654 #ifndef SQLCIPHER_OMIT_AUTOINIT
91655   rc = sqlcipher3_initialize();
91656   if( rc ){
91657     return rc;
91658   }else
91659 #endif
91660   {
91661     int i;
91662 #if SQLCIPHER_THREADSAFE
91663     sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
91664 #endif
91665     wsdAutoextInit;
91666     sqlcipher3_mutex_enter(mutex);
91667     for(i=0; i<wsdAutoext.nExt; i++){
91668       if( wsdAutoext.aExt[i]==xInit ) break;
91669     }
91670     if( i==wsdAutoext.nExt ){
91671       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
91672       void (**aNew)(void);
91673       aNew = sqlcipher3_realloc(wsdAutoext.aExt, nByte);
91674       if( aNew==0 ){
91675         rc = SQLCIPHER_NOMEM;
91676       }else{
91677         wsdAutoext.aExt = aNew;
91678         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
91679         wsdAutoext.nExt++;
91680       }
91681     }
91682     sqlcipher3_mutex_leave(mutex);
91683     assert( (rc&0xff)==rc );
91684     return rc;
91685   }
91686 }
91687
91688 /*
91689 ** Reset the automatic extension loading mechanism.
91690 */
91691 SQLCIPHER_API void sqlcipher3_reset_auto_extension(void){
91692 #ifndef SQLCIPHER_OMIT_AUTOINIT
91693   if( sqlcipher3_initialize()==SQLCIPHER_OK )
91694 #endif
91695   {
91696 #if SQLCIPHER_THREADSAFE
91697     sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
91698 #endif
91699     wsdAutoextInit;
91700     sqlcipher3_mutex_enter(mutex);
91701     sqlcipher3_free(wsdAutoext.aExt);
91702     wsdAutoext.aExt = 0;
91703     wsdAutoext.nExt = 0;
91704     sqlcipher3_mutex_leave(mutex);
91705   }
91706 }
91707
91708 /*
91709 ** Load all automatic extensions.
91710 **
91711 ** If anything goes wrong, set an error in the database connection.
91712 */
91713 SQLCIPHER_PRIVATE void sqlcipher3AutoLoadExtensions(sqlcipher3 *db){
91714   int i;
91715   int go = 1;
91716   int (*xInit)(sqlcipher3*,char**,const sqlcipher3_api_routines*);
91717
91718   wsdAutoextInit;
91719   if( wsdAutoext.nExt==0 ){
91720     /* Common case: early out without every having to acquire a mutex */
91721     return;
91722   }
91723   for(i=0; go; i++){
91724     char *zErrmsg;
91725 #if SQLCIPHER_THREADSAFE
91726     sqlcipher3_mutex *mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER);
91727 #endif
91728     sqlcipher3_mutex_enter(mutex);
91729     if( i>=wsdAutoext.nExt ){
91730       xInit = 0;
91731       go = 0;
91732     }else{
91733       xInit = (int(*)(sqlcipher3*,char**,const sqlcipher3_api_routines*))
91734               wsdAutoext.aExt[i];
91735     }
91736     sqlcipher3_mutex_leave(mutex);
91737     zErrmsg = 0;
91738     if( xInit && xInit(db, &zErrmsg, &sqlcipher3Apis) ){
91739       sqlcipher3Error(db, SQLCIPHER_ERROR,
91740             "automatic extension loading failed: %s", zErrmsg);
91741       go = 0;
91742     }
91743     sqlcipher3_free(zErrmsg);
91744   }
91745 }
91746
91747 /************** End of loadext.c *********************************************/
91748 /************** Begin file pragma.c ******************************************/
91749 /*
91750 ** 2003 April 6
91751 **
91752 ** The author disclaims copyright to this source code.  In place of
91753 ** a legal notice, here is a blessing:
91754 **
91755 **    May you do good and not evil.
91756 **    May you find forgiveness for yourself and forgive others.
91757 **    May you share freely, never taking more than you give.
91758 **
91759 *************************************************************************
91760 ** This file contains code used to implement the PRAGMA command.
91761 */
91762
91763 /*
91764 ** Interpret the given string as a safety level.  Return 0 for OFF,
91765 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
91766 ** unrecognized string argument.
91767 **
91768 ** Note that the values returned are one less that the values that
91769 ** should be passed into sqlcipher3BtreeSetSafetyLevel().  The is done
91770 ** to support legacy SQL code.  The safety level used to be boolean
91771 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
91772 */
91773 static u8 getSafetyLevel(const char *z){
91774                              /* 123456789 123456789 */
91775   static const char zText[] = "onoffalseyestruefull";
91776   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
91777   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
91778   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
91779   int i, n;
91780   if( sqlcipher3Isdigit(*z) ){
91781     return (u8)sqlcipher3Atoi(z);
91782   }
91783   n = sqlcipher3Strlen30(z);
91784   for(i=0; i<ArraySize(iLength); i++){
91785     if( iLength[i]==n && sqlcipher3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
91786       return iValue[i];
91787     }
91788   }
91789   return 1;
91790 }
91791
91792 /*
91793 ** Interpret the given string as a boolean value.
91794 */
91795 SQLCIPHER_PRIVATE u8 sqlcipher3GetBoolean(const char *z){
91796   return getSafetyLevel(z)&1;
91797 }
91798
91799 /* The sqlcipher3GetBoolean() function is used by other modules but the
91800 ** remainder of this file is specific to PRAGMA processing.  So omit
91801 ** the rest of the file if PRAGMAs are omitted from the build.
91802 */
91803 #if !defined(SQLCIPHER_OMIT_PRAGMA)
91804
91805 /*
91806 ** Interpret the given string as a locking mode value.
91807 */
91808 static int getLockingMode(const char *z){
91809   if( z ){
91810     if( 0==sqlcipher3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
91811     if( 0==sqlcipher3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
91812   }
91813   return PAGER_LOCKINGMODE_QUERY;
91814 }
91815
91816 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
91817 /*
91818 ** Interpret the given string as an auto-vacuum mode value.
91819 **
91820 ** The following strings, "none", "full" and "incremental" are 
91821 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
91822 */
91823 static int getAutoVacuum(const char *z){
91824   int i;
91825   if( 0==sqlcipher3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
91826   if( 0==sqlcipher3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
91827   if( 0==sqlcipher3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
91828   i = sqlcipher3Atoi(z);
91829   return (u8)((i>=0&&i<=2)?i:0);
91830 }
91831 #endif /* ifndef SQLCIPHER_OMIT_AUTOVACUUM */
91832
91833 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
91834 /*
91835 ** Interpret the given string as a temp db location. Return 1 for file
91836 ** backed temporary databases, 2 for the Red-Black tree in memory database
91837 ** and 0 to use the compile-time default.
91838 */
91839 static int getTempStore(const char *z){
91840   if( z[0]>='0' && z[0]<='2' ){
91841     return z[0] - '0';
91842   }else if( sqlcipher3StrICmp(z, "file")==0 ){
91843     return 1;
91844   }else if( sqlcipher3StrICmp(z, "memory")==0 ){
91845     return 2;
91846   }else{
91847     return 0;
91848   }
91849 }
91850 #endif /* SQLCIPHER_PAGER_PRAGMAS */
91851
91852 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
91853 /*
91854 ** Invalidate temp storage, either when the temp storage is changed
91855 ** from default, or when 'file' and the temp_store_directory has changed
91856 */
91857 static int invalidateTempStorage(Parse *pParse){
91858   sqlcipher3 *db = pParse->db;
91859   if( db->aDb[1].pBt!=0 ){
91860     if( !db->autoCommit || sqlcipher3BtreeIsInReadTrans(db->aDb[1].pBt) ){
91861       sqlcipher3ErrorMsg(pParse, "temporary storage cannot be changed "
91862         "from within a transaction");
91863       return SQLCIPHER_ERROR;
91864     }
91865     sqlcipher3BtreeClose(db->aDb[1].pBt);
91866     db->aDb[1].pBt = 0;
91867     sqlcipher3ResetInternalSchema(db, -1);
91868   }
91869   return SQLCIPHER_OK;
91870 }
91871 #endif /* SQLCIPHER_PAGER_PRAGMAS */
91872
91873 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
91874 /*
91875 ** If the TEMP database is open, close it and mark the database schema
91876 ** as needing reloading.  This must be done when using the SQLCIPHER_TEMP_STORE
91877 ** or DEFAULT_TEMP_STORE pragmas.
91878 */
91879 static int changeTempStorage(Parse *pParse, const char *zStorageType){
91880   int ts = getTempStore(zStorageType);
91881   sqlcipher3 *db = pParse->db;
91882   if( db->temp_store==ts ) return SQLCIPHER_OK;
91883   if( invalidateTempStorage( pParse ) != SQLCIPHER_OK ){
91884     return SQLCIPHER_ERROR;
91885   }
91886   db->temp_store = (u8)ts;
91887   return SQLCIPHER_OK;
91888 }
91889 #endif /* SQLCIPHER_PAGER_PRAGMAS */
91890
91891 /*
91892 ** Generate code to return a single integer value.
91893 */
91894 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
91895   Vdbe *v = sqlcipher3GetVdbe(pParse);
91896   int mem = ++pParse->nMem;
91897   i64 *pI64 = sqlcipher3DbMallocRaw(pParse->db, sizeof(value));
91898   if( pI64 ){
91899     memcpy(pI64, &value, sizeof(value));
91900   }
91901   sqlcipher3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
91902   sqlcipher3VdbeSetNumCols(v, 1);
91903   sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLCIPHER_STATIC);
91904   sqlcipher3VdbeAddOp2(v, OP_ResultRow, mem, 1);
91905 }
91906
91907 #ifndef SQLCIPHER_OMIT_FLAG_PRAGMAS
91908 /*
91909 ** Check to see if zRight and zLeft refer to a pragma that queries
91910 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
91911 ** Also, implement the pragma.
91912 */
91913 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
91914   static const struct sPragmaType {
91915     const char *zName;  /* Name of the pragma */
91916     int mask;           /* Mask for the db->flags value */
91917   } aPragma[] = {
91918     { "full_column_names",        SQLCIPHER_FullColNames  },
91919     { "short_column_names",       SQLCIPHER_ShortColNames },
91920     { "count_changes",            SQLCIPHER_CountRows     },
91921     { "empty_result_callbacks",   SQLCIPHER_NullCallback  },
91922     { "legacy_file_format",       SQLCIPHER_LegacyFileFmt },
91923     { "fullfsync",                SQLCIPHER_FullFSync     },
91924     { "checkpoint_fullfsync",     SQLCIPHER_CkptFullFSync },
91925     { "reverse_unordered_selects", SQLCIPHER_ReverseOrder  },
91926 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
91927     { "automatic_index",          SQLCIPHER_AutoIndex     },
91928 #endif
91929 #ifdef SQLCIPHER_DEBUG
91930     { "sql_trace",                SQLCIPHER_SqlTrace      },
91931     { "vdbe_listing",             SQLCIPHER_VdbeListing   },
91932     { "vdbe_trace",               SQLCIPHER_VdbeTrace     },
91933 #endif
91934 #ifndef SQLCIPHER_OMIT_CHECK
91935     { "ignore_check_constraints", SQLCIPHER_IgnoreChecks  },
91936 #endif
91937     /* The following is VERY experimental */
91938     { "writable_schema",          SQLCIPHER_WriteSchema|SQLCIPHER_RecoveryMode },
91939     { "omit_readlock",            SQLCIPHER_NoReadlock    },
91940
91941     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
91942     ** flag if there are any active statements. */
91943     { "read_uncommitted",         SQLCIPHER_ReadUncommitted },
91944     { "recursive_triggers",       SQLCIPHER_RecTriggers },
91945
91946     /* This flag may only be set if both foreign-key and trigger support
91947     ** are present in the build.  */
91948 #if !defined(SQLCIPHER_OMIT_FOREIGN_KEY) && !defined(SQLCIPHER_OMIT_TRIGGER)
91949     { "foreign_keys",             SQLCIPHER_ForeignKeys },
91950 #endif
91951   };
91952   int i;
91953   const struct sPragmaType *p;
91954   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
91955     if( sqlcipher3StrICmp(zLeft, p->zName)==0 ){
91956       sqlcipher3 *db = pParse->db;
91957       Vdbe *v;
91958       v = sqlcipher3GetVdbe(pParse);
91959       assert( v!=0 );  /* Already allocated by sqlcipher3Pragma() */
91960       if( ALWAYS(v) ){
91961         if( zRight==0 ){
91962           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
91963         }else{
91964           int mask = p->mask;          /* Mask of bits to set or clear. */
91965           if( db->autoCommit==0 ){
91966             /* Foreign key support may not be enabled or disabled while not
91967             ** in auto-commit mode.  */
91968             mask &= ~(SQLCIPHER_ForeignKeys);
91969           }
91970
91971           if( sqlcipher3GetBoolean(zRight) ){
91972             db->flags |= mask;
91973           }else{
91974             db->flags &= ~mask;
91975           }
91976
91977           /* Many of the flag-pragmas modify the code generated by the SQL 
91978           ** compiler (eg. count_changes). So add an opcode to expire all
91979           ** compiled SQL statements after modifying a pragma value.
91980           */
91981           sqlcipher3VdbeAddOp2(v, OP_Expire, 0, 0);
91982         }
91983       }
91984
91985       return 1;
91986     }
91987   }
91988   return 0;
91989 }
91990 #endif /* SQLCIPHER_OMIT_FLAG_PRAGMAS */
91991
91992 /*
91993 ** Return a human-readable name for a constraint resolution action.
91994 */
91995 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
91996 static const char *actionName(u8 action){
91997   const char *zName;
91998   switch( action ){
91999     case OE_SetNull:  zName = "SET NULL";        break;
92000     case OE_SetDflt:  zName = "SET DEFAULT";     break;
92001     case OE_Cascade:  zName = "CASCADE";         break;
92002     case OE_Restrict: zName = "RESTRICT";        break;
92003     default:          zName = "NO ACTION";  
92004                       assert( action==OE_None ); break;
92005   }
92006   return zName;
92007 }
92008 #endif
92009
92010
92011 /*
92012 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
92013 ** defined in pager.h. This function returns the associated lowercase
92014 ** journal-mode name.
92015 */
92016 SQLCIPHER_PRIVATE const char *sqlcipher3JournalModename(int eMode){
92017   static char * const azModeName[] = {
92018     "delete", "persist", "off", "truncate", "memory"
92019 #ifndef SQLCIPHER_OMIT_WAL
92020      , "wal"
92021 #endif
92022   };
92023   assert( PAGER_JOURNALMODE_DELETE==0 );
92024   assert( PAGER_JOURNALMODE_PERSIST==1 );
92025   assert( PAGER_JOURNALMODE_OFF==2 );
92026   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
92027   assert( PAGER_JOURNALMODE_MEMORY==4 );
92028   assert( PAGER_JOURNALMODE_WAL==5 );
92029   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92030
92031   if( eMode==ArraySize(azModeName) ) return 0;
92032   return azModeName[eMode];
92033 }
92034
92035 /*
92036 ** Process a pragma statement.  
92037 **
92038 ** Pragmas are of this form:
92039 **
92040 **      PRAGMA [database.]id [= value]
92041 **
92042 ** The identifier might also be a string.  The value is a string, and
92043 ** identifier, or a number.  If minusFlag is true, then the value is
92044 ** a number that was preceded by a minus sign.
92045 **
92046 ** If the left side is "database.id" then pId1 is the database name
92047 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
92048 ** id and pId2 is any empty string.
92049 */
92050 SQLCIPHER_PRIVATE void sqlcipher3Pragma(
92051   Parse *pParse, 
92052   Token *pId1,        /* First part of [database.]id field */
92053   Token *pId2,        /* Second part of [database.]id field, or NULL */
92054   Token *pValue,      /* Token for <value>, or NULL */
92055   int minusFlag       /* True if a '-' sign preceded <value> */
92056 ){
92057   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92058   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92059   const char *zDb = 0;   /* The database name */
92060   Token *pId;            /* Pointer to <id> token */
92061   int iDb;               /* Database index for <database> */
92062   sqlcipher3 *db = pParse->db;
92063   Db *pDb;
92064   Vdbe *v = pParse->pVdbe = sqlcipher3VdbeCreate(db);
92065   if( v==0 ) return;
92066   sqlcipher3VdbeRunOnlyOnce(v);
92067   pParse->nMem = 2;
92068
92069   /* Interpret the [database.] part of the pragma statement. iDb is the
92070   ** index of the database this pragma is being applied to in db.aDb[]. */
92071   iDb = sqlcipher3TwoPartName(pParse, pId1, pId2, &pId);
92072   if( iDb<0 ) return;
92073   pDb = &db->aDb[iDb];
92074
92075   /* If the temp database has been explicitly named as part of the 
92076   ** pragma, make sure it is open. 
92077   */
92078   if( iDb==1 && sqlcipher3OpenTempDatabase(pParse) ){
92079     return;
92080   }
92081
92082   zLeft = sqlcipher3NameFromToken(db, pId);
92083   if( !zLeft ) return;
92084   if( minusFlag ){
92085     zRight = sqlcipher3MPrintf(db, "-%T", pValue);
92086   }else{
92087     zRight = sqlcipher3NameFromToken(db, pValue);
92088   }
92089
92090   assert( pId2 );
92091   zDb = pId2->n>0 ? pDb->zName : 0;
92092   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_PRAGMA, zLeft, zRight, zDb) ){
92093     goto pragma_out;
92094   }
92095  
92096 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
92097   /*
92098   **  PRAGMA [database.]default_cache_size
92099   **  PRAGMA [database.]default_cache_size=N
92100   **
92101   ** The first form reports the current persistent setting for the
92102   ** page cache size.  The value returned is the maximum number of
92103   ** pages in the page cache.  The second form sets both the current
92104   ** page cache size value and the persistent page cache size value
92105   ** stored in the database file.
92106   **
92107   ** Older versions of SQLite would set the default cache size to a
92108   ** negative number to indicate synchronous=OFF.  These days, synchronous
92109   ** is always on by default regardless of the sign of the default cache
92110   ** size.  But continue to take the absolute value of the default cache
92111   ** size of historical compatibility.
92112   */
92113   if( sqlcipher3StrICmp(zLeft,"default_cache_size")==0 ){
92114     static const VdbeOpList getCacheSize[] = {
92115       { OP_Transaction, 0, 0,        0},                         /* 0 */
92116       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92117       { OP_IfPos,       1, 7,        0},
92118       { OP_Integer,     0, 2,        0},
92119       { OP_Subtract,    1, 2,        1},
92120       { OP_IfPos,       1, 7,        0},
92121       { OP_Integer,     0, 1,        0},                         /* 6 */
92122       { OP_ResultRow,   1, 1,        0},
92123     };
92124     int addr;
92125     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92126     sqlcipher3VdbeUsesBtree(v, iDb);
92127     if( !zRight ){
92128       sqlcipher3VdbeSetNumCols(v, 1);
92129       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLCIPHER_STATIC);
92130       pParse->nMem += 2;
92131       addr = sqlcipher3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92132       sqlcipher3VdbeChangeP1(v, addr, iDb);
92133       sqlcipher3VdbeChangeP1(v, addr+1, iDb);
92134       sqlcipher3VdbeChangeP1(v, addr+6, SQLCIPHER_DEFAULT_CACHE_SIZE);
92135     }else{
92136       int size = sqlcipher3AbsInt32(sqlcipher3Atoi(zRight));
92137       sqlcipher3BeginWriteOperation(pParse, 0, iDb);
92138       sqlcipher3VdbeAddOp2(v, OP_Integer, size, 1);
92139       sqlcipher3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92140       assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
92141       pDb->pSchema->cache_size = size;
92142       sqlcipher3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92143     }
92144   }else
92145
92146   /*
92147   **  PRAGMA [database.]page_size
92148   **  PRAGMA [database.]page_size=N
92149   **
92150   ** The first form reports the current setting for the
92151   ** database page size in bytes.  The second form sets the
92152   ** database page size value.  The value can only be set if
92153   ** the database has not yet been created.
92154   */
92155   if( sqlcipher3StrICmp(zLeft,"page_size")==0 ){
92156     Btree *pBt = pDb->pBt;
92157     assert( pBt!=0 );
92158     if( !zRight ){
92159       int size = ALWAYS(pBt) ? sqlcipher3BtreeGetPageSize(pBt) : 0;
92160       returnSingleInt(pParse, "page_size", size);
92161     }else{
92162       /* Malloc may fail when setting the page-size, as there is an internal
92163       ** buffer that the pager module resizes using sqlcipher3_realloc().
92164       */
92165       db->nextPagesize = sqlcipher3Atoi(zRight);
92166       if( SQLCIPHER_NOMEM==sqlcipher3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
92167         db->mallocFailed = 1;
92168       }
92169     }
92170   }else
92171
92172   /*
92173   **  PRAGMA [database.]secure_delete
92174   **  PRAGMA [database.]secure_delete=ON/OFF
92175   **
92176   ** The first form reports the current setting for the
92177   ** secure_delete flag.  The second form changes the secure_delete
92178   ** flag setting and reports thenew value.
92179   */
92180   if( sqlcipher3StrICmp(zLeft,"secure_delete")==0 ){
92181     Btree *pBt = pDb->pBt;
92182     int b = -1;
92183     assert( pBt!=0 );
92184     if( zRight ){
92185       b = sqlcipher3GetBoolean(zRight);
92186     }
92187     if( pId2->n==0 && b>=0 ){
92188       int ii;
92189       for(ii=0; ii<db->nDb; ii++){
92190         sqlcipher3BtreeSecureDelete(db->aDb[ii].pBt, b);
92191       }
92192     }
92193     b = sqlcipher3BtreeSecureDelete(pBt, b);
92194     returnSingleInt(pParse, "secure_delete", b);
92195   }else
92196
92197   /*
92198   **  PRAGMA [database.]max_page_count
92199   **  PRAGMA [database.]max_page_count=N
92200   **
92201   ** The first form reports the current setting for the
92202   ** maximum number of pages in the database file.  The 
92203   ** second form attempts to change this setting.  Both
92204   ** forms return the current setting.
92205   **
92206   **  PRAGMA [database.]page_count
92207   **
92208   ** Return the number of pages in the specified database.
92209   */
92210   if( sqlcipher3StrICmp(zLeft,"page_count")==0
92211    || sqlcipher3StrICmp(zLeft,"max_page_count")==0
92212   ){
92213     int iReg;
92214     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92215     sqlcipher3CodeVerifySchema(pParse, iDb);
92216     iReg = ++pParse->nMem;
92217     if( sqlcipher3Tolower(zLeft[0])=='p' ){
92218       sqlcipher3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92219     }else{
92220       sqlcipher3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlcipher3Atoi(zRight));
92221     }
92222     sqlcipher3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92223     sqlcipher3VdbeSetNumCols(v, 1);
92224     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLCIPHER_TRANSIENT);
92225   }else
92226
92227   /*
92228   **  PRAGMA [database.]locking_mode
92229   **  PRAGMA [database.]locking_mode = (normal|exclusive)
92230   */
92231   if( sqlcipher3StrICmp(zLeft,"locking_mode")==0 ){
92232     const char *zRet = "normal";
92233     int eMode = getLockingMode(zRight);
92234
92235     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92236       /* Simple "PRAGMA locking_mode;" statement. This is a query for
92237       ** the current default locking mode (which may be different to
92238       ** the locking-mode of the main database).
92239       */
92240       eMode = db->dfltLockMode;
92241     }else{
92242       Pager *pPager;
92243       if( pId2->n==0 ){
92244         /* This indicates that no database name was specified as part
92245         ** of the PRAGMA command. In this case the locking-mode must be
92246         ** set on all attached databases, as well as the main db file.
92247         **
92248         ** Also, the sqlcipher3.dfltLockMode variable is set so that
92249         ** any subsequently attached databases also use the specified
92250         ** locking mode.
92251         */
92252         int ii;
92253         assert(pDb==&db->aDb[0]);
92254         for(ii=2; ii<db->nDb; ii++){
92255           pPager = sqlcipher3BtreePager(db->aDb[ii].pBt);
92256           sqlcipher3PagerLockingMode(pPager, eMode);
92257         }
92258         db->dfltLockMode = (u8)eMode;
92259       }
92260       pPager = sqlcipher3BtreePager(pDb->pBt);
92261       eMode = sqlcipher3PagerLockingMode(pPager, eMode);
92262     }
92263
92264     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92265     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92266       zRet = "exclusive";
92267     }
92268     sqlcipher3VdbeSetNumCols(v, 1);
92269     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLCIPHER_STATIC);
92270     sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92271     sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92272   }else
92273
92274   /*
92275   **  PRAGMA [database.]journal_mode
92276   **  PRAGMA [database.]journal_mode =
92277   **                      (delete|persist|off|truncate|memory|wal|off)
92278   */
92279   if( sqlcipher3StrICmp(zLeft,"journal_mode")==0 ){
92280     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92281     int ii;           /* Loop counter */
92282
92283     /* Force the schema to be loaded on all databases.  This causes all
92284     ** database files to be opened and the journal_modes set.  This is
92285     ** necessary because subsequent processing must know if the databases
92286     ** are in WAL mode. */
92287     if( sqlcipher3ReadSchema(pParse) ){
92288       goto pragma_out;
92289     }
92290
92291     sqlcipher3VdbeSetNumCols(v, 1);
92292     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLCIPHER_STATIC);
92293
92294     if( zRight==0 ){
92295       /* If there is no "=MODE" part of the pragma, do a query for the
92296       ** current mode */
92297       eMode = PAGER_JOURNALMODE_QUERY;
92298     }else{
92299       const char *zMode;
92300       int n = sqlcipher3Strlen30(zRight);
92301       for(eMode=0; (zMode = sqlcipher3JournalModename(eMode))!=0; eMode++){
92302         if( sqlcipher3StrNICmp(zRight, zMode, n)==0 ) break;
92303       }
92304       if( !zMode ){
92305         /* If the "=MODE" part does not match any known journal mode,
92306         ** then do a query */
92307         eMode = PAGER_JOURNALMODE_QUERY;
92308       }
92309     }
92310     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92311       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92312       iDb = 0;
92313       pId2->n = 1;
92314     }
92315     for(ii=db->nDb-1; ii>=0; ii--){
92316       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92317         sqlcipher3VdbeUsesBtree(v, ii);
92318         sqlcipher3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92319       }
92320     }
92321     sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92322   }else
92323
92324   /*
92325   **  PRAGMA [database.]journal_size_limit
92326   **  PRAGMA [database.]journal_size_limit=N
92327   **
92328   ** Get or set the size limit on rollback journal files.
92329   */
92330   if( sqlcipher3StrICmp(zLeft,"journal_size_limit")==0 ){
92331     Pager *pPager = sqlcipher3BtreePager(pDb->pBt);
92332     i64 iLimit = -2;
92333     if( zRight ){
92334       sqlcipher3Atoi64(zRight, &iLimit, 1000000, SQLCIPHER_UTF8);
92335       if( iLimit<-1 ) iLimit = -1;
92336     }
92337     iLimit = sqlcipher3PagerJournalSizeLimit(pPager, iLimit);
92338     returnSingleInt(pParse, "journal_size_limit", iLimit);
92339   }else
92340
92341 #endif /* SQLCIPHER_OMIT_PAGER_PRAGMAS */
92342
92343   /*
92344   **  PRAGMA [database.]auto_vacuum
92345   **  PRAGMA [database.]auto_vacuum=N
92346   **
92347   ** Get or set the value of the database 'auto-vacuum' parameter.
92348   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92349   */
92350 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
92351   if( sqlcipher3StrICmp(zLeft,"auto_vacuum")==0 ){
92352     Btree *pBt = pDb->pBt;
92353     assert( pBt!=0 );
92354     if( sqlcipher3ReadSchema(pParse) ){
92355       goto pragma_out;
92356     }
92357     if( !zRight ){
92358       int auto_vacuum;
92359       if( ALWAYS(pBt) ){
92360          auto_vacuum = sqlcipher3BtreeGetAutoVacuum(pBt);
92361       }else{
92362          auto_vacuum = SQLCIPHER_DEFAULT_AUTOVACUUM;
92363       }
92364       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92365     }else{
92366       int eAuto = getAutoVacuum(zRight);
92367       assert( eAuto>=0 && eAuto<=2 );
92368       db->nextAutovac = (u8)eAuto;
92369       if( ALWAYS(eAuto>=0) ){
92370         /* Call SetAutoVacuum() to set initialize the internal auto and
92371         ** incr-vacuum flags. This is required in case this connection
92372         ** creates the database file. It is important that it is created
92373         ** as an auto-vacuum capable db.
92374         */
92375         int rc = sqlcipher3BtreeSetAutoVacuum(pBt, eAuto);
92376         if( rc==SQLCIPHER_OK && (eAuto==1 || eAuto==2) ){
92377           /* When setting the auto_vacuum mode to either "full" or 
92378           ** "incremental", write the value of meta[6] in the database
92379           ** file. Before writing to meta[6], check that meta[3] indicates
92380           ** that this really is an auto-vacuum capable database.
92381           */
92382           static const VdbeOpList setMeta6[] = {
92383             { OP_Transaction,    0,         1,                 0},    /* 0 */
92384             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92385             { OP_If,             1,         0,                 0},    /* 2 */
92386             { OP_Halt,           SQLCIPHER_OK, OE_Abort,          0},    /* 3 */
92387             { OP_Integer,        0,         1,                 0},    /* 4 */
92388             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92389           };
92390           int iAddr;
92391           iAddr = sqlcipher3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92392           sqlcipher3VdbeChangeP1(v, iAddr, iDb);
92393           sqlcipher3VdbeChangeP1(v, iAddr+1, iDb);
92394           sqlcipher3VdbeChangeP2(v, iAddr+2, iAddr+4);
92395           sqlcipher3VdbeChangeP1(v, iAddr+4, eAuto-1);
92396           sqlcipher3VdbeChangeP1(v, iAddr+5, iDb);
92397           sqlcipher3VdbeUsesBtree(v, iDb);
92398         }
92399       }
92400     }
92401   }else
92402 #endif
92403
92404   /*
92405   **  PRAGMA [database.]incremental_vacuum(N)
92406   **
92407   ** Do N steps of incremental vacuuming on a database.
92408   */
92409 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
92410   if( sqlcipher3StrICmp(zLeft,"incremental_vacuum")==0 ){
92411     int iLimit, addr;
92412     if( sqlcipher3ReadSchema(pParse) ){
92413       goto pragma_out;
92414     }
92415     if( zRight==0 || !sqlcipher3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92416       iLimit = 0x7fffffff;
92417     }
92418     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
92419     sqlcipher3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92420     addr = sqlcipher3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92421     sqlcipher3VdbeAddOp1(v, OP_ResultRow, 1);
92422     sqlcipher3VdbeAddOp2(v, OP_AddImm, 1, -1);
92423     sqlcipher3VdbeAddOp2(v, OP_IfPos, 1, addr);
92424     sqlcipher3VdbeJumpHere(v, addr);
92425   }else
92426 #endif
92427
92428 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
92429   /*
92430   **  PRAGMA [database.]cache_size
92431   **  PRAGMA [database.]cache_size=N
92432   **
92433   ** The first form reports the current local setting for the
92434   ** page cache size.  The local setting can be different from
92435   ** the persistent cache size value that is stored in the database
92436   ** file itself.  The value returned is the maximum number of
92437   ** pages in the page cache.  The second form sets the local
92438   ** page cache size value.  It does not change the persistent
92439   ** cache size stored on the disk so the cache size will revert
92440   ** to its default value when the database is closed and reopened.
92441   ** N should be a positive integer.
92442   */
92443   if( sqlcipher3StrICmp(zLeft,"cache_size")==0 ){
92444     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92445     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
92446     if( !zRight ){
92447       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92448     }else{
92449       int size = sqlcipher3AbsInt32(sqlcipher3Atoi(zRight));
92450       pDb->pSchema->cache_size = size;
92451       sqlcipher3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92452     }
92453   }else
92454
92455   /*
92456   **   PRAGMA temp_store
92457   **   PRAGMA temp_store = "default"|"memory"|"file"
92458   **
92459   ** Return or set the local value of the temp_store flag.  Changing
92460   ** the local value does not make changes to the disk file and the default
92461   ** value will be restored the next time the database is opened.
92462   **
92463   ** Note that it is possible for the library compile-time options to
92464   ** override this setting
92465   */
92466   if( sqlcipher3StrICmp(zLeft, "temp_store")==0 ){
92467     if( !zRight ){
92468       returnSingleInt(pParse, "temp_store", db->temp_store);
92469     }else{
92470       changeTempStorage(pParse, zRight);
92471     }
92472   }else
92473
92474   /*
92475   **   PRAGMA temp_store_directory
92476   **   PRAGMA temp_store_directory = ""|"directory_name"
92477   **
92478   ** Return or set the local value of the temp_store_directory flag.  Changing
92479   ** the value sets a specific directory to be used for temporary files.
92480   ** Setting to a null string reverts to the default temporary directory search.
92481   ** If temporary directory is changed, then invalidateTempStorage.
92482   **
92483   */
92484   if( sqlcipher3StrICmp(zLeft, "temp_store_directory")==0 ){
92485     if( !zRight ){
92486       if( sqlcipher3_temp_directory ){
92487         sqlcipher3VdbeSetNumCols(v, 1);
92488         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, 
92489             "temp_store_directory", SQLCIPHER_STATIC);
92490         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlcipher3_temp_directory, 0);
92491         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92492       }
92493     }else{
92494 #ifndef SQLCIPHER_OMIT_WSD
92495       if( zRight[0] ){
92496         int rc;
92497         int res;
92498         rc = sqlcipher3OsAccess(db->pVfs, zRight, SQLCIPHER_ACCESS_READWRITE, &res);
92499         if( rc!=SQLCIPHER_OK || res==0 ){
92500           sqlcipher3ErrorMsg(pParse, "not a writable directory");
92501           goto pragma_out;
92502         }
92503       }
92504       if( SQLCIPHER_TEMP_STORE==0
92505        || (SQLCIPHER_TEMP_STORE==1 && db->temp_store<=1)
92506        || (SQLCIPHER_TEMP_STORE==2 && db->temp_store==1)
92507       ){
92508         invalidateTempStorage(pParse);
92509       }
92510       sqlcipher3_free(sqlcipher3_temp_directory);
92511       if( zRight[0] ){
92512         sqlcipher3_temp_directory = sqlcipher3_mprintf("%s", zRight);
92513       }else{
92514         sqlcipher3_temp_directory = 0;
92515       }
92516 #endif /* SQLCIPHER_OMIT_WSD */
92517     }
92518   }else
92519
92520 #if !defined(SQLCIPHER_ENABLE_LOCKING_STYLE)
92521 #  if defined(__APPLE__)
92522 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 1
92523 #  else
92524 #    define SQLCIPHER_ENABLE_LOCKING_STYLE 0
92525 #  endif
92526 #endif
92527 #if SQLCIPHER_ENABLE_LOCKING_STYLE
92528   /*
92529    **   PRAGMA [database.]lock_proxy_file
92530    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92531    **
92532    ** Return or set the value of the lock_proxy_file flag.  Changing
92533    ** the value sets a specific file to be used for database access locks.
92534    **
92535    */
92536   if( sqlcipher3StrICmp(zLeft, "lock_proxy_file")==0 ){
92537     if( !zRight ){
92538       Pager *pPager = sqlcipher3BtreePager(pDb->pBt);
92539       char *proxy_file_path = NULL;
92540       sqlcipher3_file *pFile = sqlcipher3PagerFile(pPager);
92541       sqlcipher3OsFileControl(pFile, SQLCIPHER_GET_LOCKPROXYFILE, 
92542                            &proxy_file_path);
92543       
92544       if( proxy_file_path ){
92545         sqlcipher3VdbeSetNumCols(v, 1);
92546         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, 
92547                               "lock_proxy_file", SQLCIPHER_STATIC);
92548         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92549         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92550       }
92551     }else{
92552       Pager *pPager = sqlcipher3BtreePager(pDb->pBt);
92553       sqlcipher3_file *pFile = sqlcipher3PagerFile(pPager);
92554       int res;
92555       if( zRight[0] ){
92556         res=sqlcipher3OsFileControl(pFile, SQLCIPHER_SET_LOCKPROXYFILE, 
92557                                      zRight);
92558       } else {
92559         res=sqlcipher3OsFileControl(pFile, SQLCIPHER_SET_LOCKPROXYFILE, 
92560                                      NULL);
92561       }
92562       if( res!=SQLCIPHER_OK ){
92563         sqlcipher3ErrorMsg(pParse, "failed to set lock proxy file");
92564         goto pragma_out;
92565       }
92566     }
92567   }else
92568 #endif /* SQLCIPHER_ENABLE_LOCKING_STYLE */      
92569     
92570   /*
92571   **   PRAGMA [database.]synchronous
92572   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92573   **
92574   ** Return or set the local value of the synchronous flag.  Changing
92575   ** the local value does not make changes to the disk file and the
92576   ** default value will be restored the next time the database is
92577   ** opened.
92578   */
92579   if( sqlcipher3StrICmp(zLeft,"synchronous")==0 ){
92580     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92581     if( !zRight ){
92582       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92583     }else{
92584       if( !db->autoCommit ){
92585         sqlcipher3ErrorMsg(pParse, 
92586             "Safety level may not be changed inside a transaction");
92587       }else{
92588         pDb->safety_level = getSafetyLevel(zRight)+1;
92589       }
92590     }
92591   }else
92592 #endif /* SQLCIPHER_OMIT_PAGER_PRAGMAS */
92593
92594 #ifndef SQLCIPHER_OMIT_FLAG_PRAGMAS
92595   if( flagPragma(pParse, zLeft, zRight) ){
92596     /* The flagPragma() subroutine also generates any necessary code
92597     ** there is nothing more to do here */
92598   }else
92599 #endif /* SQLCIPHER_OMIT_FLAG_PRAGMAS */
92600
92601 #ifndef SQLCIPHER_OMIT_SCHEMA_PRAGMAS
92602   /*
92603   **   PRAGMA table_info(<table>)
92604   **
92605   ** Return a single row for each column of the named table. The columns of
92606   ** the returned data set are:
92607   **
92608   ** cid:        Column id (numbered from left to right, starting at 0)
92609   ** name:       Column name
92610   ** type:       Column declaration type.
92611   ** notnull:    True if 'NOT NULL' is part of column declaration
92612   ** dflt_value: The default value for the column, if any.
92613   */
92614   if( sqlcipher3StrICmp(zLeft, "table_info")==0 && zRight ){
92615     Table *pTab;
92616     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92617     pTab = sqlcipher3FindTable(db, zRight, zDb);
92618     if( pTab ){
92619       int i;
92620       int nHidden = 0;
92621       Column *pCol;
92622       sqlcipher3VdbeSetNumCols(v, 6);
92623       pParse->nMem = 6;
92624       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLCIPHER_STATIC);
92625       sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92626       sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLCIPHER_STATIC);
92627       sqlcipher3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLCIPHER_STATIC);
92628       sqlcipher3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLCIPHER_STATIC);
92629       sqlcipher3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLCIPHER_STATIC);
92630       sqlcipher3ViewGetColumnNames(pParse, pTab);
92631       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
92632         if( IsHiddenColumn(pCol) ){
92633           nHidden++;
92634           continue;
92635         }
92636         sqlcipher3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
92637         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
92638         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92639            pCol->zType ? pCol->zType : "", 0);
92640         sqlcipher3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
92641         if( pCol->zDflt ){
92642           sqlcipher3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
92643         }else{
92644           sqlcipher3VdbeAddOp2(v, OP_Null, 0, 5);
92645         }
92646         sqlcipher3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
92647         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 6);
92648       }
92649     }
92650   }else
92651
92652   if( sqlcipher3StrICmp(zLeft, "index_info")==0 && zRight ){
92653     Index *pIdx;
92654     Table *pTab;
92655     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92656     pIdx = sqlcipher3FindIndex(db, zRight, zDb);
92657     if( pIdx ){
92658       int i;
92659       pTab = pIdx->pTable;
92660       sqlcipher3VdbeSetNumCols(v, 3);
92661       pParse->nMem = 3;
92662       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLCIPHER_STATIC);
92663       sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLCIPHER_STATIC);
92664       sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92665       for(i=0; i<pIdx->nColumn; i++){
92666         int cnum = pIdx->aiColumn[i];
92667         sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92668         sqlcipher3VdbeAddOp2(v, OP_Integer, cnum, 2);
92669         assert( pTab->nCol>cnum );
92670         sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
92671         sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92672       }
92673     }
92674   }else
92675
92676   if( sqlcipher3StrICmp(zLeft, "index_list")==0 && zRight ){
92677     Index *pIdx;
92678     Table *pTab;
92679     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92680     pTab = sqlcipher3FindTable(db, zRight, zDb);
92681     if( pTab ){
92682       v = sqlcipher3GetVdbe(pParse);
92683       pIdx = pTab->pIndex;
92684       if( pIdx ){
92685         int i = 0; 
92686         sqlcipher3VdbeSetNumCols(v, 3);
92687         pParse->nMem = 3;
92688         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92689         sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92690         sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLCIPHER_STATIC);
92691         while(pIdx){
92692           sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92693           sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
92694           sqlcipher3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
92695           sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92696           ++i;
92697           pIdx = pIdx->pNext;
92698         }
92699       }
92700     }
92701   }else
92702
92703   if( sqlcipher3StrICmp(zLeft, "database_list")==0 ){
92704     int i;
92705     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92706     sqlcipher3VdbeSetNumCols(v, 3);
92707     pParse->nMem = 3;
92708     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92709     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92710     sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLCIPHER_STATIC);
92711     for(i=0; i<db->nDb; i++){
92712       if( db->aDb[i].pBt==0 ) continue;
92713       assert( db->aDb[i].zName!=0 );
92714       sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92715       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
92716       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92717            sqlcipher3BtreeGetFilename(db->aDb[i].pBt), 0);
92718       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92719     }
92720   }else
92721
92722   if( sqlcipher3StrICmp(zLeft, "collation_list")==0 ){
92723     int i = 0;
92724     HashElem *p;
92725     sqlcipher3VdbeSetNumCols(v, 2);
92726     pParse->nMem = 2;
92727     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92728     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLCIPHER_STATIC);
92729     for(p=sqlcipherHashFirst(&db->aCollSeq); p; p=sqlcipherHashNext(p)){
92730       CollSeq *pColl = (CollSeq *)sqlcipherHashData(p);
92731       sqlcipher3VdbeAddOp2(v, OP_Integer, i++, 1);
92732       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
92733       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 2);
92734     }
92735   }else
92736 #endif /* SQLCIPHER_OMIT_SCHEMA_PRAGMAS */
92737
92738 #ifndef SQLCIPHER_OMIT_FOREIGN_KEY
92739   if( sqlcipher3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
92740     FKey *pFK;
92741     Table *pTab;
92742     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92743     pTab = sqlcipher3FindTable(db, zRight, zDb);
92744     if( pTab ){
92745       v = sqlcipher3GetVdbe(pParse);
92746       pFK = pTab->pFKey;
92747       if( pFK ){
92748         int i = 0; 
92749         sqlcipher3VdbeSetNumCols(v, 8);
92750         pParse->nMem = 8;
92751         sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLCIPHER_STATIC);
92752         sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLCIPHER_STATIC);
92753         sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLCIPHER_STATIC);
92754         sqlcipher3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLCIPHER_STATIC);
92755         sqlcipher3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLCIPHER_STATIC);
92756         sqlcipher3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLCIPHER_STATIC);
92757         sqlcipher3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLCIPHER_STATIC);
92758         sqlcipher3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLCIPHER_STATIC);
92759         while(pFK){
92760           int j;
92761           for(j=0; j<pFK->nCol; j++){
92762             char *zCol = pFK->aCol[j].zCol;
92763             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
92764             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
92765             sqlcipher3VdbeAddOp2(v, OP_Integer, i, 1);
92766             sqlcipher3VdbeAddOp2(v, OP_Integer, j, 2);
92767             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
92768             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 4, 0,
92769                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
92770             sqlcipher3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
92771             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
92772             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
92773             sqlcipher3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
92774             sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 8);
92775           }
92776           ++i;
92777           pFK = pFK->pNextFrom;
92778         }
92779       }
92780     }
92781   }else
92782 #endif /* !defined(SQLCIPHER_OMIT_FOREIGN_KEY) */
92783
92784 #ifndef NDEBUG
92785   if( sqlcipher3StrICmp(zLeft, "parser_trace")==0 ){
92786     if( zRight ){
92787       if( sqlcipher3GetBoolean(zRight) ){
92788         sqlcipher3ParserTrace(stderr, "parser: ");
92789       }else{
92790         sqlcipher3ParserTrace(0, 0);
92791       }
92792     }
92793   }else
92794 #endif
92795
92796   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
92797   ** used will be case sensitive or not depending on the RHS.
92798   */
92799   if( sqlcipher3StrICmp(zLeft, "case_sensitive_like")==0 ){
92800     if( zRight ){
92801       sqlcipher3RegisterLikeFunctions(db, sqlcipher3GetBoolean(zRight));
92802     }
92803   }else
92804
92805 #ifndef SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX
92806 # define SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX 100
92807 #endif
92808
92809 #ifndef SQLCIPHER_OMIT_INTEGRITY_CHECK
92810   /* Pragma "quick_check" is an experimental reduced version of 
92811   ** integrity_check designed to detect most database corruption
92812   ** without most of the overhead of a full integrity-check.
92813   */
92814   if( sqlcipher3StrICmp(zLeft, "integrity_check")==0
92815    || sqlcipher3StrICmp(zLeft, "quick_check")==0 
92816   ){
92817     int i, j, addr, mxErr;
92818
92819     /* Code that appears at the end of the integrity check.  If no error
92820     ** messages have been generated, output OK.  Otherwise output the
92821     ** error message
92822     */
92823     static const VdbeOpList endCode[] = {
92824       { OP_AddImm,      1, 0,        0},    /* 0 */
92825       { OP_IfNeg,       1, 0,        0},    /* 1 */
92826       { OP_String8,     0, 3,        0},    /* 2 */
92827       { OP_ResultRow,   3, 1,        0},
92828     };
92829
92830     int isQuick = (sqlcipher3Tolower(zLeft[0])=='q');
92831
92832     /* Initialize the VDBE program */
92833     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
92834     pParse->nMem = 6;
92835     sqlcipher3VdbeSetNumCols(v, 1);
92836     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLCIPHER_STATIC);
92837
92838     /* Set the maximum error count */
92839     mxErr = SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX;
92840     if( zRight ){
92841       sqlcipher3GetInt32(zRight, &mxErr);
92842       if( mxErr<=0 ){
92843         mxErr = SQLCIPHER_INTEGRITY_CHECK_ERROR_MAX;
92844       }
92845     }
92846     sqlcipher3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
92847
92848     /* Do an integrity check on each database file */
92849     for(i=0; i<db->nDb; i++){
92850       HashElem *x;
92851       Hash *pTbls;
92852       int cnt = 0;
92853
92854       if( OMIT_TEMPDB && i==1 ) continue;
92855
92856       sqlcipher3CodeVerifySchema(pParse, i);
92857       addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
92858       sqlcipher3VdbeAddOp2(v, OP_Halt, 0, 0);
92859       sqlcipher3VdbeJumpHere(v, addr);
92860
92861       /* Do an integrity check of the B-Tree
92862       **
92863       ** Begin by filling registers 2, 3, ... with the root pages numbers
92864       ** for all tables and indices in the database.
92865       */
92866       assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
92867       pTbls = &db->aDb[i].pSchema->tblHash;
92868       for(x=sqlcipherHashFirst(pTbls); x; x=sqlcipherHashNext(x)){
92869         Table *pTab = sqlcipherHashData(x);
92870         Index *pIdx;
92871         sqlcipher3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
92872         cnt++;
92873         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92874           sqlcipher3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
92875           cnt++;
92876         }
92877       }
92878
92879       /* Make sure sufficient number of registers have been allocated */
92880       if( pParse->nMem < cnt+4 ){
92881         pParse->nMem = cnt+4;
92882       }
92883
92884       /* Do the b-tree integrity checks */
92885       sqlcipher3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
92886       sqlcipher3VdbeChangeP5(v, (u8)i);
92887       addr = sqlcipher3VdbeAddOp1(v, OP_IsNull, 2);
92888       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92889          sqlcipher3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
92890          P4_DYNAMIC);
92891       sqlcipher3VdbeAddOp3(v, OP_Move, 2, 4, 1);
92892       sqlcipher3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
92893       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 2, 1);
92894       sqlcipher3VdbeJumpHere(v, addr);
92895
92896       /* Make sure all the indices are constructed correctly.
92897       */
92898       for(x=sqlcipherHashFirst(pTbls); x && !isQuick; x=sqlcipherHashNext(x)){
92899         Table *pTab = sqlcipherHashData(x);
92900         Index *pIdx;
92901         int loopTop;
92902
92903         if( pTab->pIndex==0 ) continue;
92904         addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
92905         sqlcipher3VdbeAddOp2(v, OP_Halt, 0, 0);
92906         sqlcipher3VdbeJumpHere(v, addr);
92907         sqlcipher3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
92908         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
92909         loopTop = sqlcipher3VdbeAddOp2(v, OP_Rewind, 1, 0);
92910         sqlcipher3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
92911         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92912           int jmp2;
92913           int r1;
92914           static const VdbeOpList idxErr[] = {
92915             { OP_AddImm,      1, -1,  0},
92916             { OP_String8,     0,  3,  0},    /* 1 */
92917             { OP_Rowid,       1,  4,  0},
92918             { OP_String8,     0,  5,  0},    /* 3 */
92919             { OP_String8,     0,  6,  0},    /* 4 */
92920             { OP_Concat,      4,  3,  3},
92921             { OP_Concat,      5,  3,  3},
92922             { OP_Concat,      6,  3,  3},
92923             { OP_ResultRow,   3,  1,  0},
92924             { OP_IfPos,       1,  0,  0},    /* 9 */
92925             { OP_Halt,        0,  0,  0},
92926           };
92927           r1 = sqlcipher3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
92928           jmp2 = sqlcipher3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
92929           addr = sqlcipher3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
92930           sqlcipher3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
92931           sqlcipher3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
92932           sqlcipher3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
92933           sqlcipher3VdbeJumpHere(v, addr+9);
92934           sqlcipher3VdbeJumpHere(v, jmp2);
92935         }
92936         sqlcipher3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
92937         sqlcipher3VdbeJumpHere(v, loopTop);
92938         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92939           static const VdbeOpList cntIdx[] = {
92940              { OP_Integer,      0,  3,  0},
92941              { OP_Rewind,       0,  0,  0},  /* 1 */
92942              { OP_AddImm,       3,  1,  0},
92943              { OP_Next,         0,  0,  0},  /* 3 */
92944              { OP_Eq,           2,  0,  3},  /* 4 */
92945              { OP_AddImm,       1, -1,  0},
92946              { OP_String8,      0,  2,  0},  /* 6 */
92947              { OP_String8,      0,  3,  0},  /* 7 */
92948              { OP_Concat,       3,  2,  2},
92949              { OP_ResultRow,    2,  1,  0},
92950           };
92951           addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, 1);
92952           sqlcipher3VdbeAddOp2(v, OP_Halt, 0, 0);
92953           sqlcipher3VdbeJumpHere(v, addr);
92954           addr = sqlcipher3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
92955           sqlcipher3VdbeChangeP1(v, addr+1, j+2);
92956           sqlcipher3VdbeChangeP2(v, addr+1, addr+4);
92957           sqlcipher3VdbeChangeP1(v, addr+3, j+2);
92958           sqlcipher3VdbeChangeP2(v, addr+3, addr+2);
92959           sqlcipher3VdbeJumpHere(v, addr+4);
92960           sqlcipher3VdbeChangeP4(v, addr+6, 
92961                      "wrong # of entries in index ", P4_STATIC);
92962           sqlcipher3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
92963         }
92964       } 
92965     }
92966     addr = sqlcipher3VdbeAddOpList(v, ArraySize(endCode), endCode);
92967     sqlcipher3VdbeChangeP2(v, addr, -mxErr);
92968     sqlcipher3VdbeJumpHere(v, addr+1);
92969     sqlcipher3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
92970   }else
92971 #endif /* SQLCIPHER_OMIT_INTEGRITY_CHECK */
92972
92973 #ifndef SQLCIPHER_OMIT_UTF16
92974   /*
92975   **   PRAGMA encoding
92976   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
92977   **
92978   ** In its first form, this pragma returns the encoding of the main
92979   ** database. If the database is not initialized, it is initialized now.
92980   **
92981   ** The second form of this pragma is a no-op if the main database file
92982   ** has not already been initialized. In this case it sets the default
92983   ** encoding that will be used for the main database file if a new file
92984   ** is created. If an existing main database file is opened, then the
92985   ** default text encoding for the existing database is used.
92986   ** 
92987   ** In all cases new databases created using the ATTACH command are
92988   ** created to use the same default text encoding as the main database. If
92989   ** the main database has not been initialized and/or created when ATTACH
92990   ** is executed, this is done before the ATTACH operation.
92991   **
92992   ** In the second form this pragma sets the text encoding to be used in
92993   ** new database files created using this database handle. It is only
92994   ** useful if invoked immediately after the main database i
92995   */
92996   if( sqlcipher3StrICmp(zLeft, "encoding")==0 ){
92997     static const struct EncName {
92998       char *zName;
92999       u8 enc;
93000     } encnames[] = {
93001       { "UTF8",     SQLCIPHER_UTF8        },
93002       { "UTF-8",    SQLCIPHER_UTF8        },  /* Must be element [1] */
93003       { "UTF-16le", SQLCIPHER_UTF16LE     },  /* Must be element [2] */
93004       { "UTF-16be", SQLCIPHER_UTF16BE     },  /* Must be element [3] */
93005       { "UTF16le",  SQLCIPHER_UTF16LE     },
93006       { "UTF16be",  SQLCIPHER_UTF16BE     },
93007       { "UTF-16",   0                  }, /* SQLCIPHER_UTF16NATIVE */
93008       { "UTF16",    0                  }, /* SQLCIPHER_UTF16NATIVE */
93009       { 0, 0 }
93010     };
93011     const struct EncName *pEnc;
93012     if( !zRight ){    /* "PRAGMA encoding" */
93013       if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
93014       sqlcipher3VdbeSetNumCols(v, 1);
93015       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLCIPHER_STATIC);
93016       sqlcipher3VdbeAddOp2(v, OP_String8, 0, 1);
93017       assert( encnames[SQLCIPHER_UTF8].enc==SQLCIPHER_UTF8 );
93018       assert( encnames[SQLCIPHER_UTF16LE].enc==SQLCIPHER_UTF16LE );
93019       assert( encnames[SQLCIPHER_UTF16BE].enc==SQLCIPHER_UTF16BE );
93020       sqlcipher3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
93021       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93022     }else{                        /* "PRAGMA encoding = XXX" */
93023       /* Only change the value of sqlcipher.enc if the database handle is not
93024       ** initialized. If the main database exists, the new sqlcipher.enc value
93025       ** will be overwritten when the schema is next loaded. If it does not
93026       ** already exists, it will be created to use the new encoding value.
93027       */
93028       if( 
93029         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
93030         DbHasProperty(db, 0, DB_Empty) 
93031       ){
93032         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93033           if( 0==sqlcipher3StrICmp(zRight, pEnc->zName) ){
93034             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLCIPHER_UTF16NATIVE;
93035             break;
93036           }
93037         }
93038         if( !pEnc->zName ){
93039           sqlcipher3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93040         }
93041       }
93042     }
93043   }else
93044 #endif /* SQLCIPHER_OMIT_UTF16 */
93045
93046 #ifndef SQLCIPHER_OMIT_SCHEMA_VERSION_PRAGMAS
93047   /*
93048   **   PRAGMA [database.]schema_version
93049   **   PRAGMA [database.]schema_version = <integer>
93050   **
93051   **   PRAGMA [database.]user_version
93052   **   PRAGMA [database.]user_version = <integer>
93053   **
93054   ** The pragma's schema_version and user_version are used to set or get
93055   ** the value of the schema-version and user-version, respectively. Both
93056   ** the schema-version and the user-version are 32-bit signed integers
93057   ** stored in the database header.
93058   **
93059   ** The schema-cookie is usually only manipulated internally by SQLite. It
93060   ** is incremented by SQLite whenever the database schema is modified (by
93061   ** creating or dropping a table or index). The schema version is used by
93062   ** SQLite each time a query is executed to ensure that the internal cache
93063   ** of the schema used when compiling the SQL query matches the schema of
93064   ** the database against which the compiled query is actually executed.
93065   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93066   ** the schema-version is potentially dangerous and may lead to program
93067   ** crashes or database corruption. Use with caution!
93068   **
93069   ** The user-version is not used internally by SQLite. It may be used by
93070   ** applications for any purpose.
93071   */
93072   if( sqlcipher3StrICmp(zLeft, "schema_version")==0 
93073    || sqlcipher3StrICmp(zLeft, "user_version")==0 
93074    || sqlcipher3StrICmp(zLeft, "freelist_count")==0 
93075   ){
93076     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93077     sqlcipher3VdbeUsesBtree(v, iDb);
93078     switch( zLeft[0] ){
93079       case 'f': case 'F':
93080         iCookie = BTREE_FREE_PAGE_COUNT;
93081         break;
93082       case 's': case 'S':
93083         iCookie = BTREE_SCHEMA_VERSION;
93084         break;
93085       default:
93086         iCookie = BTREE_USER_VERSION;
93087         break;
93088     }
93089
93090     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93091       /* Write the specified cookie value */
93092       static const VdbeOpList setCookie[] = {
93093         { OP_Transaction,    0,  1,  0},    /* 0 */
93094         { OP_Integer,        0,  1,  0},    /* 1 */
93095         { OP_SetCookie,      0,  0,  1},    /* 2 */
93096       };
93097       int addr = sqlcipher3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93098       sqlcipher3VdbeChangeP1(v, addr, iDb);
93099       sqlcipher3VdbeChangeP1(v, addr+1, sqlcipher3Atoi(zRight));
93100       sqlcipher3VdbeChangeP1(v, addr+2, iDb);
93101       sqlcipher3VdbeChangeP2(v, addr+2, iCookie);
93102     }else{
93103       /* Read the specified cookie value */
93104       static const VdbeOpList readCookie[] = {
93105         { OP_Transaction,     0,  0,  0},    /* 0 */
93106         { OP_ReadCookie,      0,  1,  0},    /* 1 */
93107         { OP_ResultRow,       1,  1,  0}
93108       };
93109       int addr = sqlcipher3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93110       sqlcipher3VdbeChangeP1(v, addr, iDb);
93111       sqlcipher3VdbeChangeP1(v, addr+1, iDb);
93112       sqlcipher3VdbeChangeP3(v, addr+1, iCookie);
93113       sqlcipher3VdbeSetNumCols(v, 1);
93114       sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLCIPHER_TRANSIENT);
93115     }
93116   }else
93117 #endif /* SQLCIPHER_OMIT_SCHEMA_VERSION_PRAGMAS */
93118
93119 #ifndef SQLCIPHER_OMIT_COMPILEOPTION_DIAGS
93120   /*
93121   **   PRAGMA compile_options
93122   **
93123   ** Return the names of all compile-time options used in this build,
93124   ** one option per row.
93125   */
93126   if( sqlcipher3StrICmp(zLeft, "compile_options")==0 ){
93127     int i = 0;
93128     const char *zOpt;
93129     sqlcipher3VdbeSetNumCols(v, 1);
93130     pParse->nMem = 1;
93131     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLCIPHER_STATIC);
93132     while( (zOpt = sqlcipher3_compileoption_get(i++))!=0 ){
93133       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93134       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93135     }
93136   }else
93137 #endif /* SQLCIPHER_OMIT_COMPILEOPTION_DIAGS */
93138
93139 #ifndef SQLCIPHER_OMIT_WAL
93140   /*
93141   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93142   **
93143   ** Checkpoint the database.
93144   */
93145   if( sqlcipher3StrICmp(zLeft, "wal_checkpoint")==0 ){
93146     int iBt = (pId2->z?iDb:SQLCIPHER_MAX_ATTACHED);
93147     int eMode = SQLCIPHER_CHECKPOINT_PASSIVE;
93148     if( zRight ){
93149       if( sqlcipher3StrICmp(zRight, "full")==0 ){
93150         eMode = SQLCIPHER_CHECKPOINT_FULL;
93151       }else if( sqlcipher3StrICmp(zRight, "restart")==0 ){
93152         eMode = SQLCIPHER_CHECKPOINT_RESTART;
93153       }
93154     }
93155     if( sqlcipher3ReadSchema(pParse) ) goto pragma_out;
93156     sqlcipher3VdbeSetNumCols(v, 3);
93157     pParse->nMem = 3;
93158     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLCIPHER_STATIC);
93159     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLCIPHER_STATIC);
93160     sqlcipher3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLCIPHER_STATIC);
93161
93162     sqlcipher3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93163     sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93164   }else
93165
93166   /*
93167   **   PRAGMA wal_autocheckpoint
93168   **   PRAGMA wal_autocheckpoint = N
93169   **
93170   ** Configure a database connection to automatically checkpoint a database
93171   ** after accumulating N frames in the log. Or query for the current value
93172   ** of N.
93173   */
93174   if( sqlcipher3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93175     if( zRight ){
93176       sqlcipher3_wal_autocheckpoint(db, sqlcipher3Atoi(zRight));
93177     }
93178     returnSingleInt(pParse, "wal_autocheckpoint", 
93179        db->xWalCallback==sqlcipher3WalDefaultHook ? 
93180            SQLCIPHER_PTR_TO_INT(db->pWalArg) : 0);
93181   }else
93182 #endif
93183
93184 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_TEST)
93185   /*
93186   ** Report the current state of file logs for all databases
93187   */
93188   if( sqlcipher3StrICmp(zLeft, "lock_status")==0 ){
93189     static const char *const azLockName[] = {
93190       "unlocked", "shared", "reserved", "pending", "exclusive"
93191     };
93192     int i;
93193     sqlcipher3VdbeSetNumCols(v, 2);
93194     pParse->nMem = 2;
93195     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLCIPHER_STATIC);
93196     sqlcipher3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLCIPHER_STATIC);
93197     for(i=0; i<db->nDb; i++){
93198       Btree *pBt;
93199       Pager *pPager;
93200       const char *zState = "unknown";
93201       int j;
93202       if( db->aDb[i].zName==0 ) continue;
93203       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93204       pBt = db->aDb[i].pBt;
93205       if( pBt==0 || (pPager = sqlcipher3BtreePager(pBt))==0 ){
93206         zState = "closed";
93207       }else if( sqlcipher3_file_control(db, i ? db->aDb[i].zName : 0, 
93208                                      SQLCIPHER_FCNTL_LOCKSTATE, &j)==SQLCIPHER_OK ){
93209          zState = azLockName[j];
93210       }
93211       sqlcipher3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93212       sqlcipher3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93213     }
93214
93215   }else
93216 #endif
93217
93218 #ifdef SQLCIPHER_HAS_CODEC
93219   if( sqlcipher3StrICmp(zLeft, "key")==0 && zRight ){
93220     sqlcipher3_key(db, zRight, sqlcipher3Strlen30(zRight));
93221   }else
93222   if( sqlcipher3StrICmp(zLeft, "rekey")==0 && zRight ){
93223     sqlcipher3_rekey(db, zRight, sqlcipher3Strlen30(zRight));
93224   }else
93225   if( zRight && (sqlcipher3StrICmp(zLeft, "hexkey")==0 ||
93226                  sqlcipher3StrICmp(zLeft, "hexrekey")==0) ){
93227     int i, h1, h2;
93228     char zKey[40];
93229     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93230       h1 += 9*(1&(h1>>6));
93231       h2 += 9*(1&(h2>>6));
93232       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93233     }
93234     if( (zLeft[3] & 0xf)==0xb ){
93235       sqlcipher3_key(db, zKey, i/2);
93236     }else{
93237       sqlcipher3_rekey(db, zKey, i/2);
93238     }
93239   }else
93240 /** BEGIN CRYPTO **/
93241   if( sqlcipher3StrICmp(zLeft, "cipher")==0 && zRight ){
93242     extern int codec_set_cipher_name(sqlcipher3*, int, const char *, int);
93243     codec_set_cipher_name(db, iDb, zRight, 2); // change cipher for both
93244   }else
93245   if( sqlcipher3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){
93246     extern int codec_set_cipher_name(sqlcipher3*, int, const char *, int); 
93247     codec_set_cipher_name(db, iDb, zRight, 1); // change write cipher only
93248   }else
93249   if( sqlcipher3StrICmp(zLeft, "kdf_iter")==0 && zRight ){
93250     extern int codec_set_kdf_iter(sqlcipher3*, int, int, int);
93251     codec_set_kdf_iter(db, iDb, atoi(zRight), 2); // change of RW PBKDF2 iteration
93252   }else
93253   if( sqlcipher3StrICmp(zLeft, "fast_kdf_iter")==0 && zRight ){
93254     extern int codec_set_fast_kdf_iter(sqlcipher3*, int, int, int);
93255     codec_set_fast_kdf_iter(db, iDb, atoi(zRight), 2); // change of RW PBKDF2 iteration
93256   }else
93257   if( sqlcipher3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
93258     extern int codec_set_kdf_iter(sqlcipher3*, int, int, int); 
93259     codec_set_kdf_iter(db, iDb, atoi(zRight), 1); // change # if W iterations
93260   }else
93261   if( sqlcipher3StrICmp(zLeft,"cipher_page_size")==0 ){
93262     extern int codec_set_page_size(sqlcipher3*, int, int); 
93263     codec_set_page_size(db, iDb, atoi(zRight)); // change page size
93264   }else
93265   if( sqlcipher3StrICmp(zLeft,"cipher_use_hmac")==0 ){
93266     extern int codec_set_use_hmac(sqlcipher3*, int, int);
93267     if(sqlcipher3GetBoolean(zRight)) {
93268       codec_set_use_hmac(db, iDb, 1);
93269     } else {
93270       codec_set_use_hmac(db, iDb, 0);
93271     }
93272   }else
93273 /** END CRYPTO **/
93274 #endif
93275 #if defined(SQLCIPHER_HAS_CODEC) || defined(SQLCIPHER_ENABLE_CEROD)
93276   if( sqlcipher3StrICmp(zLeft, "activate_extensions")==0 ){
93277 #ifdef SQLCIPHER_HAS_CODEC
93278     if( sqlcipher3StrNICmp(zRight, "see-", 4)==0 ){
93279       sqlcipher3_activate_see(&zRight[4]);
93280     }
93281 #endif
93282 #ifdef SQLCIPHER_ENABLE_CEROD
93283     if( sqlcipher3StrNICmp(zRight, "cerod-", 6)==0 ){
93284       sqlcipher3_activate_cerod(&zRight[6]);
93285     }
93286 #endif
93287   }else
93288 #endif
93289
93290  
93291   {/* Empty ELSE clause */}
93292
93293   /*
93294   ** Reset the safety level, in case the fullfsync flag or synchronous
93295   ** setting changed.
93296   */
93297 #ifndef SQLCIPHER_OMIT_PAGER_PRAGMAS
93298   if( db->autoCommit ){
93299     sqlcipher3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93300                (db->flags&SQLCIPHER_FullFSync)!=0,
93301                (db->flags&SQLCIPHER_CkptFullFSync)!=0);
93302   }
93303 #endif
93304 pragma_out:
93305   sqlcipher3DbFree(db, zLeft);
93306   sqlcipher3DbFree(db, zRight);
93307 }
93308
93309 #endif /* SQLCIPHER_OMIT_PRAGMA */
93310
93311 /************** End of pragma.c **********************************************/
93312 /************** Begin file prepare.c *****************************************/
93313 /*
93314 ** 2005 May 25
93315 **
93316 ** The author disclaims copyright to this source code.  In place of
93317 ** a legal notice, here is a blessing:
93318 **
93319 **    May you do good and not evil.
93320 **    May you find forgiveness for yourself and forgive others.
93321 **    May you share freely, never taking more than you give.
93322 **
93323 *************************************************************************
93324 ** This file contains the implementation of the sqlcipher3_prepare()
93325 ** interface, and routines that contribute to loading the database schema
93326 ** from disk.
93327 */
93328
93329 /*
93330 ** Fill the InitData structure with an error message that indicates
93331 ** that the database is corrupt.
93332 */
93333 static void corruptSchema(
93334   InitData *pData,     /* Initialization context */
93335   const char *zObj,    /* Object being parsed at the point of error */
93336   const char *zExtra   /* Error information */
93337 ){
93338   sqlcipher3 *db = pData->db;
93339   if( !db->mallocFailed && (db->flags & SQLCIPHER_RecoveryMode)==0 ){
93340     if( zObj==0 ) zObj = "?";
93341     sqlcipher3SetString(pData->pzErrMsg, db,
93342       "malformed database schema (%s)", zObj);
93343     if( zExtra ){
93344       *pData->pzErrMsg = sqlcipher3MAppendf(db, *pData->pzErrMsg, 
93345                                  "%s - %s", *pData->pzErrMsg, zExtra);
93346     }
93347   }
93348   pData->rc = db->mallocFailed ? SQLCIPHER_NOMEM : SQLCIPHER_CORRUPT_BKPT;
93349 }
93350
93351 /*
93352 ** This is the callback routine for the code that initializes the
93353 ** database.  See sqlcipher3Init() below for additional information.
93354 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93355 **
93356 ** Each callback contains the following information:
93357 **
93358 **     argv[0] = name of thing being created
93359 **     argv[1] = root page number for table or index. 0 for trigger or view.
93360 **     argv[2] = SQL text for the CREATE statement.
93361 **
93362 */
93363 SQLCIPHER_PRIVATE int sqlcipher3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93364   InitData *pData = (InitData*)pInit;
93365   sqlcipher3 *db = pData->db;
93366   int iDb = pData->iDb;
93367
93368   assert( argc==3 );
93369   UNUSED_PARAMETER2(NotUsed, argc);
93370   assert( sqlcipher3_mutex_held(db->mutex) );
93371   DbClearProperty(db, iDb, DB_Empty);
93372   if( db->mallocFailed ){
93373     corruptSchema(pData, argv[0], 0);
93374     return 1;
93375   }
93376
93377   assert( iDb>=0 && iDb<db->nDb );
93378   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93379   if( argv[1]==0 ){
93380     corruptSchema(pData, argv[0], 0);
93381   }else if( argv[2] && argv[2][0] ){
93382     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93383     ** But because db->init.busy is set to 1, no VDBE code is generated
93384     ** or executed.  All the parser does is build the internal data
93385     ** structures that describe the table, index, or view.
93386     */
93387     int rc;
93388     sqlcipher3_stmt *pStmt;
93389     TESTONLY(int rcp);            /* Return code from sqlcipher3_prepare() */
93390
93391     assert( db->init.busy );
93392     db->init.iDb = iDb;
93393     db->init.newTnum = sqlcipher3Atoi(argv[1]);
93394     db->init.orphanTrigger = 0;
93395     TESTONLY(rcp = ) sqlcipher3_prepare(db, argv[2], -1, &pStmt, 0);
93396     rc = db->errCode;
93397     assert( (rc&0xFF)==(rcp&0xFF) );
93398     db->init.iDb = 0;
93399     if( SQLCIPHER_OK!=rc ){
93400       if( db->init.orphanTrigger ){
93401         assert( iDb==1 );
93402       }else{
93403         pData->rc = rc;
93404         if( rc==SQLCIPHER_NOMEM ){
93405           db->mallocFailed = 1;
93406         }else if( rc!=SQLCIPHER_INTERRUPT && (rc&0xFF)!=SQLCIPHER_LOCKED ){
93407           corruptSchema(pData, argv[0], sqlcipher3_errmsg(db));
93408         }
93409       }
93410     }
93411     sqlcipher3_finalize(pStmt);
93412   }else if( argv[0]==0 ){
93413     corruptSchema(pData, 0, 0);
93414   }else{
93415     /* If the SQL column is blank it means this is an index that
93416     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93417     ** constraint for a CREATE TABLE.  The index should have already
93418     ** been created when we processed the CREATE TABLE.  All we have
93419     ** to do here is record the root page number for that index.
93420     */
93421     Index *pIndex;
93422     pIndex = sqlcipher3FindIndex(db, argv[0], db->aDb[iDb].zName);
93423     if( pIndex==0 ){
93424       /* This can occur if there exists an index on a TEMP table which
93425       ** has the same name as another index on a permanent index.  Since
93426       ** the permanent table is hidden by the TEMP table, we can also
93427       ** safely ignore the index on the permanent table.
93428       */
93429       /* Do Nothing */;
93430     }else if( sqlcipher3GetInt32(argv[1], &pIndex->tnum)==0 ){
93431       corruptSchema(pData, argv[0], "invalid rootpage");
93432     }
93433   }
93434   return 0;
93435 }
93436
93437 /*
93438 ** Attempt to read the database schema and initialize internal
93439 ** data structures for a single database file.  The index of the
93440 ** database file is given by iDb.  iDb==0 is used for the main
93441 ** database.  iDb==1 should never be used.  iDb>=2 is used for
93442 ** auxiliary databases.  Return one of the SQLCIPHER_ error codes to
93443 ** indicate success or failure.
93444 */
93445 static int sqlcipher3InitOne(sqlcipher3 *db, int iDb, char **pzErrMsg){
93446   int rc;
93447   int i;
93448   int size;
93449   Table *pTab;
93450   Db *pDb;
93451   char const *azArg[4];
93452   int meta[5];
93453   InitData initData;
93454   char const *zMasterSchema;
93455   char const *zMasterName;
93456   int openedTransaction = 0;
93457
93458   /*
93459   ** The master database table has a structure like this
93460   */
93461   static const char master_schema[] = 
93462      "CREATE TABLE sqlcipher_master(\n"
93463      "  type text,\n"
93464      "  name text,\n"
93465      "  tbl_name text,\n"
93466      "  rootpage integer,\n"
93467      "  sql text\n"
93468      ")"
93469   ;
93470 #ifndef SQLCIPHER_OMIT_TEMPDB
93471   static const char temp_master_schema[] = 
93472      "CREATE TEMP TABLE sqlcipher_temp_master(\n"
93473      "  type text,\n"
93474      "  name text,\n"
93475      "  tbl_name text,\n"
93476      "  rootpage integer,\n"
93477      "  sql text\n"
93478      ")"
93479   ;
93480 #else
93481   #define temp_master_schema 0
93482 #endif
93483
93484   assert( iDb>=0 && iDb<db->nDb );
93485   assert( db->aDb[iDb].pSchema );
93486   assert( sqlcipher3_mutex_held(db->mutex) );
93487   assert( iDb==1 || sqlcipher3BtreeHoldsMutex(db->aDb[iDb].pBt) );
93488
93489   /* zMasterSchema and zInitScript are set to point at the master schema
93490   ** and initialisation script appropriate for the database being
93491   ** initialised. zMasterName is the name of the master table.
93492   */
93493   if( !OMIT_TEMPDB && iDb==1 ){
93494     zMasterSchema = temp_master_schema;
93495   }else{
93496     zMasterSchema = master_schema;
93497   }
93498   zMasterName = SCHEMA_TABLE(iDb);
93499
93500   /* Construct the schema tables.  */
93501   azArg[0] = zMasterName;
93502   azArg[1] = "1";
93503   azArg[2] = zMasterSchema;
93504   azArg[3] = 0;
93505   initData.db = db;
93506   initData.iDb = iDb;
93507   initData.rc = SQLCIPHER_OK;
93508   initData.pzErrMsg = pzErrMsg;
93509   sqlcipher3InitCallback(&initData, 3, (char **)azArg, 0);
93510   if( initData.rc ){
93511     rc = initData.rc;
93512     goto error_out;
93513   }
93514   pTab = sqlcipher3FindTable(db, zMasterName, db->aDb[iDb].zName);
93515   if( ALWAYS(pTab) ){
93516     pTab->tabFlags |= TF_Readonly;
93517   }
93518
93519   /* Create a cursor to hold the database open
93520   */
93521   pDb = &db->aDb[iDb];
93522   if( pDb->pBt==0 ){
93523     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
93524       DbSetProperty(db, 1, DB_SchemaLoaded);
93525     }
93526     return SQLCIPHER_OK;
93527   }
93528
93529   /* If there is not already a read-only (or read-write) transaction opened
93530   ** on the b-tree database, open one now. If a transaction is opened, it 
93531   ** will be closed before this function returns.  */
93532   sqlcipher3BtreeEnter(pDb->pBt);
93533   if( !sqlcipher3BtreeIsInReadTrans(pDb->pBt) ){
93534     rc = sqlcipher3BtreeBeginTrans(pDb->pBt, 0);
93535     if( rc!=SQLCIPHER_OK ){
93536       sqlcipher3SetString(pzErrMsg, db, "%s", sqlcipher3ErrStr(rc));
93537       goto initone_error_out;
93538     }
93539     openedTransaction = 1;
93540   }
93541
93542   /* Get the database meta information.
93543   **
93544   ** Meta values are as follows:
93545   **    meta[0]   Schema cookie.  Changes with each schema change.
93546   **    meta[1]   File format of schema layer.
93547   **    meta[2]   Size of the page cache.
93548   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
93549   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
93550   **    meta[5]   User version
93551   **    meta[6]   Incremental vacuum mode
93552   **    meta[7]   unused
93553   **    meta[8]   unused
93554   **    meta[9]   unused
93555   **
93556   ** Note: The #defined SQLCIPHER_UTF* symbols in sqlcipherInt.h correspond to
93557   ** the possible values of meta[4].
93558   */
93559   for(i=0; i<ArraySize(meta); i++){
93560     sqlcipher3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
93561   }
93562   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
93563
93564   /* If opening a non-empty database, check the text encoding. For the
93565   ** main database, set sqlcipher3.enc to the encoding of the main database.
93566   ** For an attached db, it is an error if the encoding is not the same
93567   ** as sqlcipher3.enc.
93568   */
93569   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
93570     if( iDb==0 ){
93571       u8 encoding;
93572       /* If opening the main database, set ENC(db). */
93573       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
93574       if( encoding==0 ) encoding = SQLCIPHER_UTF8;
93575       ENC(db) = encoding;
93576       db->pDfltColl = sqlcipher3FindCollSeq(db, SQLCIPHER_UTF8, "BINARY", 0);
93577     }else{
93578       /* If opening an attached database, the encoding much match ENC(db) */
93579       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
93580         sqlcipher3SetString(pzErrMsg, db, "attached databases must use the same"
93581             " text encoding as main database");
93582         rc = SQLCIPHER_ERROR;
93583         goto initone_error_out;
93584       }
93585     }
93586   }else{
93587     DbSetProperty(db, iDb, DB_Empty);
93588   }
93589   pDb->pSchema->enc = ENC(db);
93590
93591   if( pDb->pSchema->cache_size==0 ){
93592     size = sqlcipher3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
93593     if( size==0 ){ size = SQLCIPHER_DEFAULT_CACHE_SIZE; }
93594     pDb->pSchema->cache_size = size;
93595     sqlcipher3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93596   }
93597
93598   /*
93599   ** file_format==1    Version 3.0.0.
93600   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
93601   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
93602   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
93603   */
93604   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
93605   if( pDb->pSchema->file_format==0 ){
93606     pDb->pSchema->file_format = 1;
93607   }
93608   if( pDb->pSchema->file_format>SQLCIPHER_MAX_FILE_FORMAT ){
93609     sqlcipher3SetString(pzErrMsg, db, "unsupported file format");
93610     rc = SQLCIPHER_ERROR;
93611     goto initone_error_out;
93612   }
93613
93614   /* Ticket #2804:  When we open a database in the newer file format,
93615   ** clear the legacy_file_format pragma flag so that a VACUUM will
93616   ** not downgrade the database and thus invalidate any descending
93617   ** indices that the user might have created.
93618   */
93619   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
93620     db->flags &= ~SQLCIPHER_LegacyFileFmt;
93621   }
93622
93623   /* Read the schema information out of the schema tables
93624   */
93625   assert( db->init.busy );
93626   {
93627     char *zSql;
93628     zSql = sqlcipher3MPrintf(db, 
93629         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
93630         db->aDb[iDb].zName, zMasterName);
93631 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
93632     {
93633       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
93634       xAuth = db->xAuth;
93635       db->xAuth = 0;
93636 #endif
93637       rc = sqlcipher3_exec(db, zSql, sqlcipher3InitCallback, &initData, 0);
93638 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
93639       db->xAuth = xAuth;
93640     }
93641 #endif
93642     if( rc==SQLCIPHER_OK ) rc = initData.rc;
93643     sqlcipher3DbFree(db, zSql);
93644 #ifndef SQLCIPHER_OMIT_ANALYZE
93645     if( rc==SQLCIPHER_OK ){
93646       sqlcipher3AnalysisLoad(db, iDb);
93647     }
93648 #endif
93649   }
93650   if( db->mallocFailed ){
93651     rc = SQLCIPHER_NOMEM;
93652     sqlcipher3ResetInternalSchema(db, -1);
93653   }
93654   if( rc==SQLCIPHER_OK || (db->flags&SQLCIPHER_RecoveryMode)){
93655     /* Black magic: If the SQLCIPHER_RecoveryMode flag is set, then consider
93656     ** the schema loaded, even if errors occurred. In this situation the 
93657     ** current sqlcipher3_prepare() operation will fail, but the following one
93658     ** will attempt to compile the supplied statement against whatever subset
93659     ** of the schema was loaded before the error occurred. The primary
93660     ** purpose of this is to allow access to the sqlcipher_master table
93661     ** even when its contents have been corrupted.
93662     */
93663     DbSetProperty(db, iDb, DB_SchemaLoaded);
93664     rc = SQLCIPHER_OK;
93665   }
93666
93667   /* Jump here for an error that occurs after successfully allocating
93668   ** curMain and calling sqlcipher3BtreeEnter(). For an error that occurs
93669   ** before that point, jump to error_out.
93670   */
93671 initone_error_out:
93672   if( openedTransaction ){
93673     sqlcipher3BtreeCommit(pDb->pBt);
93674   }
93675   sqlcipher3BtreeLeave(pDb->pBt);
93676
93677 error_out:
93678   if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ){
93679     db->mallocFailed = 1;
93680   }
93681   return rc;
93682 }
93683
93684 /*
93685 ** Initialize all database files - the main database file, the file
93686 ** used to store temporary tables, and any additional database files
93687 ** created using ATTACH statements.  Return a success code.  If an
93688 ** error occurs, write an error message into *pzErrMsg.
93689 **
93690 ** After a database is initialized, the DB_SchemaLoaded bit is set
93691 ** bit is set in the flags field of the Db structure. If the database
93692 ** file was of zero-length, then the DB_Empty flag is also set.
93693 */
93694 SQLCIPHER_PRIVATE int sqlcipher3Init(sqlcipher3 *db, char **pzErrMsg){
93695   int i, rc;
93696   int commit_internal = !(db->flags&SQLCIPHER_InternChanges);
93697   
93698   assert( sqlcipher3_mutex_held(db->mutex) );
93699   rc = SQLCIPHER_OK;
93700   db->init.busy = 1;
93701   for(i=0; rc==SQLCIPHER_OK && i<db->nDb; i++){
93702     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
93703     rc = sqlcipher3InitOne(db, i, pzErrMsg);
93704     if( rc ){
93705       sqlcipher3ResetInternalSchema(db, i);
93706     }
93707   }
93708
93709   /* Once all the other databases have been initialised, load the schema
93710   ** for the TEMP database. This is loaded last, as the TEMP database
93711   ** schema may contain references to objects in other databases.
93712   */
93713 #ifndef SQLCIPHER_OMIT_TEMPDB
93714   if( rc==SQLCIPHER_OK && ALWAYS(db->nDb>1)
93715                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
93716     rc = sqlcipher3InitOne(db, 1, pzErrMsg);
93717     if( rc ){
93718       sqlcipher3ResetInternalSchema(db, 1);
93719     }
93720   }
93721 #endif
93722
93723   db->init.busy = 0;
93724   if( rc==SQLCIPHER_OK && commit_internal ){
93725     sqlcipher3CommitInternalChanges(db);
93726   }
93727
93728   return rc; 
93729 }
93730
93731 /*
93732 ** This routine is a no-op if the database schema is already initialised.
93733 ** Otherwise, the schema is loaded. An error code is returned.
93734 */
93735 SQLCIPHER_PRIVATE int sqlcipher3ReadSchema(Parse *pParse){
93736   int rc = SQLCIPHER_OK;
93737   sqlcipher3 *db = pParse->db;
93738   assert( sqlcipher3_mutex_held(db->mutex) );
93739   if( !db->init.busy ){
93740     rc = sqlcipher3Init(db, &pParse->zErrMsg);
93741   }
93742   if( rc!=SQLCIPHER_OK ){
93743     pParse->rc = rc;
93744     pParse->nErr++;
93745   }
93746   return rc;
93747 }
93748
93749
93750 /*
93751 ** Check schema cookies in all databases.  If any cookie is out
93752 ** of date set pParse->rc to SQLCIPHER_SCHEMA.  If all schema cookies
93753 ** make no changes to pParse->rc.
93754 */
93755 static void schemaIsValid(Parse *pParse){
93756   sqlcipher3 *db = pParse->db;
93757   int iDb;
93758   int rc;
93759   int cookie;
93760
93761   assert( pParse->checkSchema );
93762   assert( sqlcipher3_mutex_held(db->mutex) );
93763   for(iDb=0; iDb<db->nDb; iDb++){
93764     int openedTransaction = 0;         /* True if a transaction is opened */
93765     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
93766     if( pBt==0 ) continue;
93767
93768     /* If there is not already a read-only (or read-write) transaction opened
93769     ** on the b-tree database, open one now. If a transaction is opened, it 
93770     ** will be closed immediately after reading the meta-value. */
93771     if( !sqlcipher3BtreeIsInReadTrans(pBt) ){
93772       rc = sqlcipher3BtreeBeginTrans(pBt, 0);
93773       if( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_IOERR_NOMEM ){
93774         db->mallocFailed = 1;
93775       }
93776       if( rc!=SQLCIPHER_OK ) return;
93777       openedTransaction = 1;
93778     }
93779
93780     /* Read the schema cookie from the database. If it does not match the 
93781     ** value stored as part of the in-memory schema representation,
93782     ** set Parse.rc to SQLCIPHER_SCHEMA. */
93783     sqlcipher3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
93784     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
93785     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
93786       sqlcipher3ResetInternalSchema(db, iDb);
93787       pParse->rc = SQLCIPHER_SCHEMA;
93788     }
93789
93790     /* Close the transaction, if one was opened. */
93791     if( openedTransaction ){
93792       sqlcipher3BtreeCommit(pBt);
93793     }
93794   }
93795 }
93796
93797 /*
93798 ** Convert a schema pointer into the iDb index that indicates
93799 ** which database file in db->aDb[] the schema refers to.
93800 **
93801 ** If the same database is attached more than once, the first
93802 ** attached database is returned.
93803 */
93804 SQLCIPHER_PRIVATE int sqlcipher3SchemaToIndex(sqlcipher3 *db, Schema *pSchema){
93805   int i = -1000000;
93806
93807   /* If pSchema is NULL, then return -1000000. This happens when code in 
93808   ** expr.c is trying to resolve a reference to a transient table (i.e. one
93809   ** created by a sub-select). In this case the return value of this 
93810   ** function should never be used.
93811   **
93812   ** We return -1000000 instead of the more usual -1 simply because using
93813   ** -1000000 as the incorrect index into db->aDb[] is much 
93814   ** more likely to cause a segfault than -1 (of course there are assert()
93815   ** statements too, but it never hurts to play the odds).
93816   */
93817   assert( sqlcipher3_mutex_held(db->mutex) );
93818   if( pSchema ){
93819     for(i=0; ALWAYS(i<db->nDb); i++){
93820       if( db->aDb[i].pSchema==pSchema ){
93821         break;
93822       }
93823     }
93824     assert( i>=0 && i<db->nDb );
93825   }
93826   return i;
93827 }
93828
93829 /*
93830 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
93831 */
93832 static int sqlcipher3Prepare(
93833   sqlcipher3 *db,              /* Database handle. */
93834   const char *zSql,         /* UTF-8 encoded SQL statement. */
93835   int nBytes,               /* Length of zSql in bytes. */
93836   int saveSqlFlag,          /* True to copy SQL text into the sqlcipher3_stmt */
93837   Vdbe *pReprepare,         /* VM being reprepared */
93838   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93839   const char **pzTail       /* OUT: End of parsed string */
93840 ){
93841   Parse *pParse;            /* Parsing context */
93842   char *zErrMsg = 0;        /* Error message */
93843   int rc = SQLCIPHER_OK;       /* Result code */
93844   int i;                    /* Loop counter */
93845
93846   /* Allocate the parsing context */
93847   pParse = sqlcipher3StackAllocZero(db, sizeof(*pParse));
93848   if( pParse==0 ){
93849     rc = SQLCIPHER_NOMEM;
93850     goto end_prepare;
93851   }
93852   pParse->pReprepare = pReprepare;
93853   assert( ppStmt && *ppStmt==0 );
93854   assert( !db->mallocFailed );
93855   assert( sqlcipher3_mutex_held(db->mutex) );
93856
93857   /* Check to verify that it is possible to get a read lock on all
93858   ** database schemas.  The inability to get a read lock indicates that
93859   ** some other database connection is holding a write-lock, which in
93860   ** turn means that the other connection has made uncommitted changes
93861   ** to the schema.
93862   **
93863   ** Were we to proceed and prepare the statement against the uncommitted
93864   ** schema changes and if those schema changes are subsequently rolled
93865   ** back and different changes are made in their place, then when this
93866   ** prepared statement goes to run the schema cookie would fail to detect
93867   ** the schema change.  Disaster would follow.
93868   **
93869   ** This thread is currently holding mutexes on all Btrees (because
93870   ** of the sqlcipher3BtreeEnterAll() in sqlcipher3LockAndPrepare()) so it
93871   ** is not possible for another thread to start a new schema change
93872   ** while this routine is running.  Hence, we do not need to hold 
93873   ** locks on the schema, we just need to make sure nobody else is 
93874   ** holding them.
93875   **
93876   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
93877   ** but it does *not* override schema lock detection, so this all still
93878   ** works even if READ_UNCOMMITTED is set.
93879   */
93880   for(i=0; i<db->nDb; i++) {
93881     Btree *pBt = db->aDb[i].pBt;
93882     if( pBt ){
93883       assert( sqlcipher3BtreeHoldsMutex(pBt) );
93884       rc = sqlcipher3BtreeSchemaLocked(pBt);
93885       if( rc ){
93886         const char *zDb = db->aDb[i].zName;
93887         sqlcipher3Error(db, rc, "database schema is locked: %s", zDb);
93888         testcase( db->flags & SQLCIPHER_ReadUncommitted );
93889         goto end_prepare;
93890       }
93891     }
93892   }
93893
93894   sqlcipher3VtabUnlockList(db);
93895
93896   pParse->db = db;
93897   pParse->nQueryLoop = (double)1;
93898   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
93899     char *zSqlCopy;
93900     int mxLen = db->aLimit[SQLCIPHER_LIMIT_SQL_LENGTH];
93901     testcase( nBytes==mxLen );
93902     testcase( nBytes==mxLen+1 );
93903     if( nBytes>mxLen ){
93904       sqlcipher3Error(db, SQLCIPHER_TOOBIG, "statement too long");
93905       rc = sqlcipher3ApiExit(db, SQLCIPHER_TOOBIG);
93906       goto end_prepare;
93907     }
93908     zSqlCopy = sqlcipher3DbStrNDup(db, zSql, nBytes);
93909     if( zSqlCopy ){
93910       sqlcipher3RunParser(pParse, zSqlCopy, &zErrMsg);
93911       sqlcipher3DbFree(db, zSqlCopy);
93912       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
93913     }else{
93914       pParse->zTail = &zSql[nBytes];
93915     }
93916   }else{
93917     sqlcipher3RunParser(pParse, zSql, &zErrMsg);
93918   }
93919   assert( 1==(int)pParse->nQueryLoop );
93920
93921   if( db->mallocFailed ){
93922     pParse->rc = SQLCIPHER_NOMEM;
93923   }
93924   if( pParse->rc==SQLCIPHER_DONE ) pParse->rc = SQLCIPHER_OK;
93925   if( pParse->checkSchema ){
93926     schemaIsValid(pParse);
93927   }
93928   if( db->mallocFailed ){
93929     pParse->rc = SQLCIPHER_NOMEM;
93930   }
93931   if( pzTail ){
93932     *pzTail = pParse->zTail;
93933   }
93934   rc = pParse->rc;
93935
93936 #ifndef SQLCIPHER_OMIT_EXPLAIN
93937   if( rc==SQLCIPHER_OK && pParse->pVdbe && pParse->explain ){
93938     static const char * const azColName[] = {
93939        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
93940        "selectid", "order", "from", "detail"
93941     };
93942     int iFirst, mx;
93943     if( pParse->explain==2 ){
93944       sqlcipher3VdbeSetNumCols(pParse->pVdbe, 4);
93945       iFirst = 8;
93946       mx = 12;
93947     }else{
93948       sqlcipher3VdbeSetNumCols(pParse->pVdbe, 8);
93949       iFirst = 0;
93950       mx = 8;
93951     }
93952     for(i=iFirst; i<mx; i++){
93953       sqlcipher3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
93954                             azColName[i], SQLCIPHER_STATIC);
93955     }
93956   }
93957 #endif
93958
93959   assert( db->init.busy==0 || saveSqlFlag==0 );
93960   if( db->init.busy==0 ){
93961     Vdbe *pVdbe = pParse->pVdbe;
93962     sqlcipher3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
93963   }
93964   if( pParse->pVdbe && (rc!=SQLCIPHER_OK || db->mallocFailed) ){
93965     sqlcipher3VdbeFinalize(pParse->pVdbe);
93966     assert(!(*ppStmt));
93967   }else{
93968     *ppStmt = (sqlcipher3_stmt*)pParse->pVdbe;
93969   }
93970
93971   if( zErrMsg ){
93972     sqlcipher3Error(db, rc, "%s", zErrMsg);
93973     sqlcipher3DbFree(db, zErrMsg);
93974   }else{
93975     sqlcipher3Error(db, rc, 0);
93976   }
93977
93978   /* Delete any TriggerPrg structures allocated while parsing this statement. */
93979   while( pParse->pTriggerPrg ){
93980     TriggerPrg *pT = pParse->pTriggerPrg;
93981     pParse->pTriggerPrg = pT->pNext;
93982     sqlcipher3DbFree(db, pT);
93983   }
93984
93985 end_prepare:
93986
93987   sqlcipher3StackFree(db, pParse);
93988   rc = sqlcipher3ApiExit(db, rc);
93989   assert( (rc&db->errMask)==rc );
93990   return rc;
93991 }
93992 static int sqlcipher3LockAndPrepare(
93993   sqlcipher3 *db,              /* Database handle. */
93994   const char *zSql,         /* UTF-8 encoded SQL statement. */
93995   int nBytes,               /* Length of zSql in bytes. */
93996   int saveSqlFlag,          /* True to copy SQL text into the sqlcipher3_stmt */
93997   Vdbe *pOld,               /* VM being reprepared */
93998   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93999   const char **pzTail       /* OUT: End of parsed string */
94000 ){
94001   int rc;
94002   assert( ppStmt!=0 );
94003   *ppStmt = 0;
94004   if( !sqlcipher3SafetyCheckOk(db) ){
94005     return SQLCIPHER_MISUSE_BKPT;
94006   }
94007   sqlcipher3_mutex_enter(db->mutex);
94008   sqlcipher3BtreeEnterAll(db);
94009   rc = sqlcipher3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94010   if( rc==SQLCIPHER_SCHEMA ){
94011     sqlcipher3_finalize(*ppStmt);
94012     rc = sqlcipher3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94013   }
94014   sqlcipher3BtreeLeaveAll(db);
94015   sqlcipher3_mutex_leave(db->mutex);
94016   return rc;
94017 }
94018
94019 /*
94020 ** Rerun the compilation of a statement after a schema change.
94021 **
94022 ** If the statement is successfully recompiled, return SQLCIPHER_OK. Otherwise,
94023 ** if the statement cannot be recompiled because another connection has
94024 ** locked the sqlcipher3_master table, return SQLCIPHER_LOCKED. If any other error
94025 ** occurs, return SQLCIPHER_SCHEMA.
94026 */
94027 SQLCIPHER_PRIVATE int sqlcipher3Reprepare(Vdbe *p){
94028   int rc;
94029   sqlcipher3_stmt *pNew;
94030   const char *zSql;
94031   sqlcipher3 *db;
94032
94033   assert( sqlcipher3_mutex_held(sqlcipher3VdbeDb(p)->mutex) );
94034   zSql = sqlcipher3_sql((sqlcipher3_stmt *)p);
94035   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94036   db = sqlcipher3VdbeDb(p);
94037   assert( sqlcipher3_mutex_held(db->mutex) );
94038   rc = sqlcipher3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94039   if( rc ){
94040     if( rc==SQLCIPHER_NOMEM ){
94041       db->mallocFailed = 1;
94042     }
94043     assert( pNew==0 );
94044     return rc;
94045   }else{
94046     assert( pNew!=0 );
94047   }
94048   sqlcipher3VdbeSwap((Vdbe*)pNew, p);
94049   sqlcipher3TransferBindings(pNew, (sqlcipher3_stmt*)p);
94050   sqlcipher3VdbeResetStepResult((Vdbe*)pNew);
94051   sqlcipher3VdbeFinalize((Vdbe*)pNew);
94052   return SQLCIPHER_OK;
94053 }
94054
94055
94056 /*
94057 ** Two versions of the official API.  Legacy and new use.  In the legacy
94058 ** version, the original SQL text is not saved in the prepared statement
94059 ** and so if a schema change occurs, SQLCIPHER_SCHEMA is returned by
94060 ** sqlcipher3_step().  In the new version, the original SQL text is retained
94061 ** and the statement is automatically recompiled if an schema change
94062 ** occurs.
94063 */
94064 SQLCIPHER_API int sqlcipher3_prepare(
94065   sqlcipher3 *db,              /* Database handle. */
94066   const char *zSql,         /* UTF-8 encoded SQL statement. */
94067   int nBytes,               /* Length of zSql in bytes. */
94068   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94069   const char **pzTail       /* OUT: End of parsed string */
94070 ){
94071   int rc;
94072   rc = sqlcipher3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94073   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94074   return rc;
94075 }
94076 SQLCIPHER_API int sqlcipher3_prepare_v2(
94077   sqlcipher3 *db,              /* Database handle. */
94078   const char *zSql,         /* UTF-8 encoded SQL statement. */
94079   int nBytes,               /* Length of zSql in bytes. */
94080   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94081   const char **pzTail       /* OUT: End of parsed string */
94082 ){
94083   int rc;
94084   rc = sqlcipher3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94085   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94086   return rc;
94087 }
94088
94089
94090 #ifndef SQLCIPHER_OMIT_UTF16
94091 /*
94092 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94093 */
94094 static int sqlcipher3Prepare16(
94095   sqlcipher3 *db,              /* Database handle. */ 
94096   const void *zSql,         /* UTF-16 encoded SQL statement. */
94097   int nBytes,               /* Length of zSql in bytes. */
94098   int saveSqlFlag,          /* True to save SQL text into the sqlcipher3_stmt */
94099   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94100   const void **pzTail       /* OUT: End of parsed string */
94101 ){
94102   /* This function currently works by first transforming the UTF-16
94103   ** encoded string to UTF-8, then invoking sqlcipher3_prepare(). The
94104   ** tricky bit is figuring out the pointer to return in *pzTail.
94105   */
94106   char *zSql8;
94107   const char *zTail8 = 0;
94108   int rc = SQLCIPHER_OK;
94109
94110   assert( ppStmt );
94111   *ppStmt = 0;
94112   if( !sqlcipher3SafetyCheckOk(db) ){
94113     return SQLCIPHER_MISUSE_BKPT;
94114   }
94115   sqlcipher3_mutex_enter(db->mutex);
94116   zSql8 = sqlcipher3Utf16to8(db, zSql, nBytes, SQLCIPHER_UTF16NATIVE);
94117   if( zSql8 ){
94118     rc = sqlcipher3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94119   }
94120
94121   if( zTail8 && pzTail ){
94122     /* If sqlcipher3_prepare returns a tail pointer, we calculate the
94123     ** equivalent pointer into the UTF-16 string by counting the unicode
94124     ** characters between zSql8 and zTail8, and then returning a pointer
94125     ** the same number of characters into the UTF-16 string.
94126     */
94127     int chars_parsed = sqlcipher3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94128     *pzTail = (u8 *)zSql + sqlcipher3Utf16ByteLen(zSql, chars_parsed);
94129   }
94130   sqlcipher3DbFree(db, zSql8); 
94131   rc = sqlcipher3ApiExit(db, rc);
94132   sqlcipher3_mutex_leave(db->mutex);
94133   return rc;
94134 }
94135
94136 /*
94137 ** Two versions of the official API.  Legacy and new use.  In the legacy
94138 ** version, the original SQL text is not saved in the prepared statement
94139 ** and so if a schema change occurs, SQLCIPHER_SCHEMA is returned by
94140 ** sqlcipher3_step().  In the new version, the original SQL text is retained
94141 ** and the statement is automatically recompiled if an schema change
94142 ** occurs.
94143 */
94144 SQLCIPHER_API int sqlcipher3_prepare16(
94145   sqlcipher3 *db,              /* Database handle. */ 
94146   const void *zSql,         /* UTF-16 encoded SQL statement. */
94147   int nBytes,               /* Length of zSql in bytes. */
94148   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94149   const void **pzTail       /* OUT: End of parsed string */
94150 ){
94151   int rc;
94152   rc = sqlcipher3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94153   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94154   return rc;
94155 }
94156 SQLCIPHER_API int sqlcipher3_prepare16_v2(
94157   sqlcipher3 *db,              /* Database handle. */ 
94158   const void *zSql,         /* UTF-16 encoded SQL statement. */
94159   int nBytes,               /* Length of zSql in bytes. */
94160   sqlcipher3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94161   const void **pzTail       /* OUT: End of parsed string */
94162 ){
94163   int rc;
94164   rc = sqlcipher3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94165   assert( rc==SQLCIPHER_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94166   return rc;
94167 }
94168
94169 #endif /* SQLCIPHER_OMIT_UTF16 */
94170
94171 /************** End of prepare.c *********************************************/
94172 /************** Begin file select.c ******************************************/
94173 /*
94174 ** 2001 September 15
94175 **
94176 ** The author disclaims copyright to this source code.  In place of
94177 ** a legal notice, here is a blessing:
94178 **
94179 **    May you do good and not evil.
94180 **    May you find forgiveness for yourself and forgive others.
94181 **    May you share freely, never taking more than you give.
94182 **
94183 *************************************************************************
94184 ** This file contains C code routines that are called by the parser
94185 ** to handle SELECT statements in SQLite.
94186 */
94187
94188
94189 /*
94190 ** Delete all the content of a Select structure but do not deallocate
94191 ** the select structure itself.
94192 */
94193 static void clearSelect(sqlcipher3 *db, Select *p){
94194   sqlcipher3ExprListDelete(db, p->pEList);
94195   sqlcipher3SrcListDelete(db, p->pSrc);
94196   sqlcipher3ExprDelete(db, p->pWhere);
94197   sqlcipher3ExprListDelete(db, p->pGroupBy);
94198   sqlcipher3ExprDelete(db, p->pHaving);
94199   sqlcipher3ExprListDelete(db, p->pOrderBy);
94200   sqlcipher3SelectDelete(db, p->pPrior);
94201   sqlcipher3ExprDelete(db, p->pLimit);
94202   sqlcipher3ExprDelete(db, p->pOffset);
94203 }
94204
94205 /*
94206 ** Initialize a SelectDest structure.
94207 */
94208 SQLCIPHER_PRIVATE void sqlcipher3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94209   pDest->eDest = (u8)eDest;
94210   pDest->iParm = iParm;
94211   pDest->affinity = 0;
94212   pDest->iMem = 0;
94213   pDest->nMem = 0;
94214 }
94215
94216
94217 /*
94218 ** Allocate a new Select structure and return a pointer to that
94219 ** structure.
94220 */
94221 SQLCIPHER_PRIVATE Select *sqlcipher3SelectNew(
94222   Parse *pParse,        /* Parsing context */
94223   ExprList *pEList,     /* which columns to include in the result */
94224   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94225   Expr *pWhere,         /* the WHERE clause */
94226   ExprList *pGroupBy,   /* the GROUP BY clause */
94227   Expr *pHaving,        /* the HAVING clause */
94228   ExprList *pOrderBy,   /* the ORDER BY clause */
94229   int isDistinct,       /* true if the DISTINCT keyword is present */
94230   Expr *pLimit,         /* LIMIT value.  NULL means not used */
94231   Expr *pOffset         /* OFFSET value.  NULL means no offset */
94232 ){
94233   Select *pNew;
94234   Select standin;
94235   sqlcipher3 *db = pParse->db;
94236   pNew = sqlcipher3DbMallocZero(db, sizeof(*pNew) );
94237   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94238   if( pNew==0 ){
94239     assert( db->mallocFailed );
94240     pNew = &standin;
94241     memset(pNew, 0, sizeof(*pNew));
94242   }
94243   if( pEList==0 ){
94244     pEList = sqlcipher3ExprListAppend(pParse, 0, sqlcipher3Expr(db,TK_ALL,0));
94245   }
94246   pNew->pEList = pEList;
94247   pNew->pSrc = pSrc;
94248   pNew->pWhere = pWhere;
94249   pNew->pGroupBy = pGroupBy;
94250   pNew->pHaving = pHaving;
94251   pNew->pOrderBy = pOrderBy;
94252   pNew->selFlags = isDistinct ? SF_Distinct : 0;
94253   pNew->op = TK_SELECT;
94254   pNew->pLimit = pLimit;
94255   pNew->pOffset = pOffset;
94256   assert( pOffset==0 || pLimit!=0 );
94257   pNew->addrOpenEphm[0] = -1;
94258   pNew->addrOpenEphm[1] = -1;
94259   pNew->addrOpenEphm[2] = -1;
94260   if( db->mallocFailed ) {
94261     clearSelect(db, pNew);
94262     if( pNew!=&standin ) sqlcipher3DbFree(db, pNew);
94263     pNew = 0;
94264   }else{
94265     assert( pNew->pSrc!=0 || pParse->nErr>0 );
94266   }
94267   assert( pNew!=&standin );
94268   return pNew;
94269 }
94270
94271 /*
94272 ** Delete the given Select structure and all of its substructures.
94273 */
94274 SQLCIPHER_PRIVATE void sqlcipher3SelectDelete(sqlcipher3 *db, Select *p){
94275   if( p ){
94276     clearSelect(db, p);
94277     sqlcipher3DbFree(db, p);
94278   }
94279 }
94280
94281 /*
94282 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94283 ** type of join.  Return an integer constant that expresses that type
94284 ** in terms of the following bit values:
94285 **
94286 **     JT_INNER
94287 **     JT_CROSS
94288 **     JT_OUTER
94289 **     JT_NATURAL
94290 **     JT_LEFT
94291 **     JT_RIGHT
94292 **
94293 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94294 **
94295 ** If an illegal or unsupported join type is seen, then still return
94296 ** a join type, but put an error in the pParse structure.
94297 */
94298 SQLCIPHER_PRIVATE int sqlcipher3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94299   int jointype = 0;
94300   Token *apAll[3];
94301   Token *p;
94302                              /*   0123456789 123456789 123456789 123 */
94303   static const char zKeyText[] = "naturaleftouterightfullinnercross";
94304   static const struct {
94305     u8 i;        /* Beginning of keyword text in zKeyText[] */
94306     u8 nChar;    /* Length of the keyword in characters */
94307     u8 code;     /* Join type mask */
94308   } aKeyword[] = {
94309     /* natural */ { 0,  7, JT_NATURAL                },
94310     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94311     /* outer   */ { 10, 5, JT_OUTER                  },
94312     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94313     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94314     /* inner   */ { 23, 5, JT_INNER                  },
94315     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94316   };
94317   int i, j;
94318   apAll[0] = pA;
94319   apAll[1] = pB;
94320   apAll[2] = pC;
94321   for(i=0; i<3 && apAll[i]; i++){
94322     p = apAll[i];
94323     for(j=0; j<ArraySize(aKeyword); j++){
94324       if( p->n==aKeyword[j].nChar 
94325           && sqlcipher3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94326         jointype |= aKeyword[j].code;
94327         break;
94328       }
94329     }
94330     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94331     if( j>=ArraySize(aKeyword) ){
94332       jointype |= JT_ERROR;
94333       break;
94334     }
94335   }
94336   if(
94337      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94338      (jointype & JT_ERROR)!=0
94339   ){
94340     const char *zSp = " ";
94341     assert( pB!=0 );
94342     if( pC==0 ){ zSp++; }
94343     sqlcipher3ErrorMsg(pParse, "unknown or unsupported join type: "
94344        "%T %T%s%T", pA, pB, zSp, pC);
94345     jointype = JT_INNER;
94346   }else if( (jointype & JT_OUTER)!=0 
94347          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94348     sqlcipher3ErrorMsg(pParse, 
94349       "RIGHT and FULL OUTER JOINs are not currently supported");
94350     jointype = JT_INNER;
94351   }
94352   return jointype;
94353 }
94354
94355 /*
94356 ** Return the index of a column in a table.  Return -1 if the column
94357 ** is not contained in the table.
94358 */
94359 static int columnIndex(Table *pTab, const char *zCol){
94360   int i;
94361   for(i=0; i<pTab->nCol; i++){
94362     if( sqlcipher3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94363   }
94364   return -1;
94365 }
94366
94367 /*
94368 ** Search the first N tables in pSrc, from left to right, looking for a
94369 ** table that has a column named zCol.  
94370 **
94371 ** When found, set *piTab and *piCol to the table index and column index
94372 ** of the matching column and return TRUE.
94373 **
94374 ** If not found, return FALSE.
94375 */
94376 static int tableAndColumnIndex(
94377   SrcList *pSrc,       /* Array of tables to search */
94378   int N,               /* Number of tables in pSrc->a[] to search */
94379   const char *zCol,    /* Name of the column we are looking for */
94380   int *piTab,          /* Write index of pSrc->a[] here */
94381   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94382 ){
94383   int i;               /* For looping over tables in pSrc */
94384   int iCol;            /* Index of column matching zCol */
94385
94386   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94387   for(i=0; i<N; i++){
94388     iCol = columnIndex(pSrc->a[i].pTab, zCol);
94389     if( iCol>=0 ){
94390       if( piTab ){
94391         *piTab = i;
94392         *piCol = iCol;
94393       }
94394       return 1;
94395     }
94396   }
94397   return 0;
94398 }
94399
94400 /*
94401 ** This function is used to add terms implied by JOIN syntax to the
94402 ** WHERE clause expression of a SELECT statement. The new term, which
94403 ** is ANDed with the existing WHERE clause, is of the form:
94404 **
94405 **    (tab1.col1 = tab2.col2)
94406 **
94407 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
94408 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94409 ** column iColRight of tab2.
94410 */
94411 static void addWhereTerm(
94412   Parse *pParse,                  /* Parsing context */
94413   SrcList *pSrc,                  /* List of tables in FROM clause */
94414   int iLeft,                      /* Index of first table to join in pSrc */
94415   int iColLeft,                   /* Index of column in first table */
94416   int iRight,                     /* Index of second table in pSrc */
94417   int iColRight,                  /* Index of column in second table */
94418   int isOuterJoin,                /* True if this is an OUTER join */
94419   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94420 ){
94421   sqlcipher3 *db = pParse->db;
94422   Expr *pE1;
94423   Expr *pE2;
94424   Expr *pEq;
94425
94426   assert( iLeft<iRight );
94427   assert( pSrc->nSrc>iRight );
94428   assert( pSrc->a[iLeft].pTab );
94429   assert( pSrc->a[iRight].pTab );
94430
94431   pE1 = sqlcipher3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94432   pE2 = sqlcipher3CreateColumnExpr(db, pSrc, iRight, iColRight);
94433
94434   pEq = sqlcipher3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94435   if( pEq && isOuterJoin ){
94436     ExprSetProperty(pEq, EP_FromJoin);
94437     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94438     ExprSetIrreducible(pEq);
94439     pEq->iRightJoinTable = (i16)pE2->iTable;
94440   }
94441   *ppWhere = sqlcipher3ExprAnd(db, *ppWhere, pEq);
94442 }
94443
94444 /*
94445 ** Set the EP_FromJoin property on all terms of the given expression.
94446 ** And set the Expr.iRightJoinTable to iTable for every term in the
94447 ** expression.
94448 **
94449 ** The EP_FromJoin property is used on terms of an expression to tell
94450 ** the LEFT OUTER JOIN processing logic that this term is part of the
94451 ** join restriction specified in the ON or USING clause and not a part
94452 ** of the more general WHERE clause.  These terms are moved over to the
94453 ** WHERE clause during join processing but we need to remember that they
94454 ** originated in the ON or USING clause.
94455 **
94456 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
94457 ** expression depends on table iRightJoinTable even if that table is not
94458 ** explicitly mentioned in the expression.  That information is needed
94459 ** for cases like this:
94460 **
94461 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
94462 **
94463 ** The where clause needs to defer the handling of the t1.x=5
94464 ** term until after the t2 loop of the join.  In that way, a
94465 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
94466 ** defer the handling of t1.x=5, it will be processed immediately
94467 ** after the t1 loop and rows with t1.x!=5 will never appear in
94468 ** the output, which is incorrect.
94469 */
94470 static void setJoinExpr(Expr *p, int iTable){
94471   while( p ){
94472     ExprSetProperty(p, EP_FromJoin);
94473     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
94474     ExprSetIrreducible(p);
94475     p->iRightJoinTable = (i16)iTable;
94476     setJoinExpr(p->pLeft, iTable);
94477     p = p->pRight;
94478   } 
94479 }
94480
94481 /*
94482 ** This routine processes the join information for a SELECT statement.
94483 ** ON and USING clauses are converted into extra terms of the WHERE clause.
94484 ** NATURAL joins also create extra WHERE clause terms.
94485 **
94486 ** The terms of a FROM clause are contained in the Select.pSrc structure.
94487 ** The left most table is the first entry in Select.pSrc.  The right-most
94488 ** table is the last entry.  The join operator is held in the entry to
94489 ** the left.  Thus entry 0 contains the join operator for the join between
94490 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
94491 ** also attached to the left entry.
94492 **
94493 ** This routine returns the number of errors encountered.
94494 */
94495 static int sqlcipherProcessJoin(Parse *pParse, Select *p){
94496   SrcList *pSrc;                  /* All tables in the FROM clause */
94497   int i, j;                       /* Loop counters */
94498   struct SrcList_item *pLeft;     /* Left table being joined */
94499   struct SrcList_item *pRight;    /* Right table being joined */
94500
94501   pSrc = p->pSrc;
94502   pLeft = &pSrc->a[0];
94503   pRight = &pLeft[1];
94504   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
94505     Table *pLeftTab = pLeft->pTab;
94506     Table *pRightTab = pRight->pTab;
94507     int isOuter;
94508
94509     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
94510     isOuter = (pRight->jointype & JT_OUTER)!=0;
94511
94512     /* When the NATURAL keyword is present, add WHERE clause terms for
94513     ** every column that the two tables have in common.
94514     */
94515     if( pRight->jointype & JT_NATURAL ){
94516       if( pRight->pOn || pRight->pUsing ){
94517         sqlcipher3ErrorMsg(pParse, "a NATURAL join may not have "
94518            "an ON or USING clause", 0);
94519         return 1;
94520       }
94521       for(j=0; j<pRightTab->nCol; j++){
94522         char *zName;   /* Name of column in the right table */
94523         int iLeft;     /* Matching left table */
94524         int iLeftCol;  /* Matching column in the left table */
94525
94526         zName = pRightTab->aCol[j].zName;
94527         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
94528           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
94529                        isOuter, &p->pWhere);
94530         }
94531       }
94532     }
94533
94534     /* Disallow both ON and USING clauses in the same join
94535     */
94536     if( pRight->pOn && pRight->pUsing ){
94537       sqlcipher3ErrorMsg(pParse, "cannot have both ON and USING "
94538         "clauses in the same join");
94539       return 1;
94540     }
94541
94542     /* Add the ON clause to the end of the WHERE clause, connected by
94543     ** an AND operator.
94544     */
94545     if( pRight->pOn ){
94546       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
94547       p->pWhere = sqlcipher3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
94548       pRight->pOn = 0;
94549     }
94550
94551     /* Create extra terms on the WHERE clause for each column named
94552     ** in the USING clause.  Example: If the two tables to be joined are 
94553     ** A and B and the USING clause names X, Y, and Z, then add this
94554     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
94555     ** Report an error if any column mentioned in the USING clause is
94556     ** not contained in both tables to be joined.
94557     */
94558     if( pRight->pUsing ){
94559       IdList *pList = pRight->pUsing;
94560       for(j=0; j<pList->nId; j++){
94561         char *zName;     /* Name of the term in the USING clause */
94562         int iLeft;       /* Table on the left with matching column name */
94563         int iLeftCol;    /* Column number of matching column on the left */
94564         int iRightCol;   /* Column number of matching column on the right */
94565
94566         zName = pList->a[j].zName;
94567         iRightCol = columnIndex(pRightTab, zName);
94568         if( iRightCol<0
94569          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
94570         ){
94571           sqlcipher3ErrorMsg(pParse, "cannot join using column %s - column "
94572             "not present in both tables", zName);
94573           return 1;
94574         }
94575         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
94576                      isOuter, &p->pWhere);
94577       }
94578     }
94579   }
94580   return 0;
94581 }
94582
94583 /*
94584 ** Insert code into "v" that will push the record on the top of the
94585 ** stack into the sorter.
94586 */
94587 static void pushOntoSorter(
94588   Parse *pParse,         /* Parser context */
94589   ExprList *pOrderBy,    /* The ORDER BY clause */
94590   Select *pSelect,       /* The whole SELECT statement */
94591   int regData            /* Register holding data to be sorted */
94592 ){
94593   Vdbe *v = pParse->pVdbe;
94594   int nExpr = pOrderBy->nExpr;
94595   int regBase = sqlcipher3GetTempRange(pParse, nExpr+2);
94596   int regRecord = sqlcipher3GetTempReg(pParse);
94597   int op;
94598   sqlcipher3ExprCacheClear(pParse);
94599   sqlcipher3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
94600   sqlcipher3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
94601   sqlcipher3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
94602   sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
94603   if( pSelect->selFlags & SF_UseSorter ){
94604     op = OP_SorterInsert;
94605   }else{
94606     op = OP_IdxInsert;
94607   }
94608   sqlcipher3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
94609   sqlcipher3ReleaseTempReg(pParse, regRecord);
94610   sqlcipher3ReleaseTempRange(pParse, regBase, nExpr+2);
94611   if( pSelect->iLimit ){
94612     int addr1, addr2;
94613     int iLimit;
94614     if( pSelect->iOffset ){
94615       iLimit = pSelect->iOffset+1;
94616     }else{
94617       iLimit = pSelect->iLimit;
94618     }
94619     addr1 = sqlcipher3VdbeAddOp1(v, OP_IfZero, iLimit);
94620     sqlcipher3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
94621     addr2 = sqlcipher3VdbeAddOp0(v, OP_Goto);
94622     sqlcipher3VdbeJumpHere(v, addr1);
94623     sqlcipher3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
94624     sqlcipher3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
94625     sqlcipher3VdbeJumpHere(v, addr2);
94626   }
94627 }
94628
94629 /*
94630 ** Add code to implement the OFFSET
94631 */
94632 static void codeOffset(
94633   Vdbe *v,          /* Generate code into this VM */
94634   Select *p,        /* The SELECT statement being coded */
94635   int iContinue     /* Jump here to skip the current record */
94636 ){
94637   if( p->iOffset && iContinue!=0 ){
94638     int addr;
94639     sqlcipher3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
94640     addr = sqlcipher3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
94641     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iContinue);
94642     VdbeComment((v, "skip OFFSET records"));
94643     sqlcipher3VdbeJumpHere(v, addr);
94644   }
94645 }
94646
94647 /*
94648 ** Add code that will check to make sure the N registers starting at iMem
94649 ** form a distinct entry.  iTab is a sorting index that holds previously
94650 ** seen combinations of the N values.  A new entry is made in iTab
94651 ** if the current N values are new.
94652 **
94653 ** A jump to addrRepeat is made and the N+1 values are popped from the
94654 ** stack if the top N elements are not distinct.
94655 */
94656 static void codeDistinct(
94657   Parse *pParse,     /* Parsing and code generating context */
94658   int iTab,          /* A sorting index used to test for distinctness */
94659   int addrRepeat,    /* Jump to here if not distinct */
94660   int N,             /* Number of elements */
94661   int iMem           /* First element */
94662 ){
94663   Vdbe *v;
94664   int r1;
94665
94666   v = pParse->pVdbe;
94667   r1 = sqlcipher3GetTempReg(pParse);
94668   sqlcipher3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
94669   sqlcipher3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
94670   sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
94671   sqlcipher3ReleaseTempReg(pParse, r1);
94672 }
94673
94674 #ifndef SQLCIPHER_OMIT_SUBQUERY
94675 /*
94676 ** Generate an error message when a SELECT is used within a subexpression
94677 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
94678 ** column.  We do this in a subroutine because the error used to occur
94679 ** in multiple places.  (The error only occurs in one place now, but we
94680 ** retain the subroutine to minimize code disruption.)
94681 */
94682 static int checkForMultiColumnSelectError(
94683   Parse *pParse,       /* Parse context. */
94684   SelectDest *pDest,   /* Destination of SELECT results */
94685   int nExpr            /* Number of result columns returned by SELECT */
94686 ){
94687   int eDest = pDest->eDest;
94688   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
94689     sqlcipher3ErrorMsg(pParse, "only a single result allowed for "
94690        "a SELECT that is part of an expression");
94691     return 1;
94692   }else{
94693     return 0;
94694   }
94695 }
94696 #endif
94697
94698 /*
94699 ** This routine generates the code for the inside of the inner loop
94700 ** of a SELECT.
94701 **
94702 ** If srcTab and nColumn are both zero, then the pEList expressions
94703 ** are evaluated in order to get the data for this row.  If nColumn>0
94704 ** then data is pulled from srcTab and pEList is used only to get the
94705 ** datatypes for each column.
94706 */
94707 static void selectInnerLoop(
94708   Parse *pParse,          /* The parser context */
94709   Select *p,              /* The complete select statement being coded */
94710   ExprList *pEList,       /* List of values being extracted */
94711   int srcTab,             /* Pull data from this table */
94712   int nColumn,            /* Number of columns in the source table */
94713   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
94714   int distinct,           /* If >=0, make sure results are distinct */
94715   SelectDest *pDest,      /* How to dispose of the results */
94716   int iContinue,          /* Jump here to continue with next row */
94717   int iBreak              /* Jump here to break out of the inner loop */
94718 ){
94719   Vdbe *v = pParse->pVdbe;
94720   int i;
94721   int hasDistinct;        /* True if the DISTINCT keyword is present */
94722   int regResult;              /* Start of memory holding result set */
94723   int eDest = pDest->eDest;   /* How to dispose of results */
94724   int iParm = pDest->iParm;   /* First argument to disposal method */
94725   int nResultCol;             /* Number of result columns */
94726
94727   assert( v );
94728   if( NEVER(v==0) ) return;
94729   assert( pEList!=0 );
94730   hasDistinct = distinct>=0;
94731   if( pOrderBy==0 && !hasDistinct ){
94732     codeOffset(v, p, iContinue);
94733   }
94734
94735   /* Pull the requested columns.
94736   */
94737   if( nColumn>0 ){
94738     nResultCol = nColumn;
94739   }else{
94740     nResultCol = pEList->nExpr;
94741   }
94742   if( pDest->iMem==0 ){
94743     pDest->iMem = pParse->nMem+1;
94744     pDest->nMem = nResultCol;
94745     pParse->nMem += nResultCol;
94746   }else{ 
94747     assert( pDest->nMem==nResultCol );
94748   }
94749   regResult = pDest->iMem;
94750   if( nColumn>0 ){
94751     for(i=0; i<nColumn; i++){
94752       sqlcipher3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
94753     }
94754   }else if( eDest!=SRT_Exists ){
94755     /* If the destination is an EXISTS(...) expression, the actual
94756     ** values returned by the SELECT are not required.
94757     */
94758     sqlcipher3ExprCacheClear(pParse);
94759     sqlcipher3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
94760   }
94761   nColumn = nResultCol;
94762
94763   /* If the DISTINCT keyword was present on the SELECT statement
94764   ** and this row has been seen before, then do not make this row
94765   ** part of the result.
94766   */
94767   if( hasDistinct ){
94768     assert( pEList!=0 );
94769     assert( pEList->nExpr==nColumn );
94770     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
94771     if( pOrderBy==0 ){
94772       codeOffset(v, p, iContinue);
94773     }
94774   }
94775
94776   switch( eDest ){
94777     /* In this mode, write each query result to the key of the temporary
94778     ** table iParm.
94779     */
94780 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
94781     case SRT_Union: {
94782       int r1;
94783       r1 = sqlcipher3GetTempReg(pParse);
94784       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94785       sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94786       sqlcipher3ReleaseTempReg(pParse, r1);
94787       break;
94788     }
94789
94790     /* Construct a record from the query result, but instead of
94791     ** saving that record, use it as a key to delete elements from
94792     ** the temporary table iParm.
94793     */
94794     case SRT_Except: {
94795       sqlcipher3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
94796       break;
94797     }
94798 #endif
94799
94800     /* Store the result as data using a unique key.
94801     */
94802     case SRT_Table:
94803     case SRT_EphemTab: {
94804       int r1 = sqlcipher3GetTempReg(pParse);
94805       testcase( eDest==SRT_Table );
94806       testcase( eDest==SRT_EphemTab );
94807       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94808       if( pOrderBy ){
94809         pushOntoSorter(pParse, pOrderBy, p, r1);
94810       }else{
94811         int r2 = sqlcipher3GetTempReg(pParse);
94812         sqlcipher3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
94813         sqlcipher3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
94814         sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
94815         sqlcipher3ReleaseTempReg(pParse, r2);
94816       }
94817       sqlcipher3ReleaseTempReg(pParse, r1);
94818       break;
94819     }
94820
94821 #ifndef SQLCIPHER_OMIT_SUBQUERY
94822     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
94823     ** then there should be a single item on the stack.  Write this
94824     ** item into the set table with bogus data.
94825     */
94826     case SRT_Set: {
94827       assert( nColumn==1 );
94828       p->affinity = sqlcipher3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
94829       if( pOrderBy ){
94830         /* At first glance you would think we could optimize out the
94831         ** ORDER BY in this case since the order of entries in the set
94832         ** does not matter.  But there might be a LIMIT clause, in which
94833         ** case the order does matter */
94834         pushOntoSorter(pParse, pOrderBy, p, regResult);
94835       }else{
94836         int r1 = sqlcipher3GetTempReg(pParse);
94837         sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
94838         sqlcipher3ExprCacheAffinityChange(pParse, regResult, 1);
94839         sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94840         sqlcipher3ReleaseTempReg(pParse, r1);
94841       }
94842       break;
94843     }
94844
94845     /* If any row exist in the result set, record that fact and abort.
94846     */
94847     case SRT_Exists: {
94848       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, iParm);
94849       /* The LIMIT clause will terminate the loop for us */
94850       break;
94851     }
94852
94853     /* If this is a scalar select that is part of an expression, then
94854     ** store the results in the appropriate memory cell and break out
94855     ** of the scan loop.
94856     */
94857     case SRT_Mem: {
94858       assert( nColumn==1 );
94859       if( pOrderBy ){
94860         pushOntoSorter(pParse, pOrderBy, p, regResult);
94861       }else{
94862         sqlcipher3ExprCodeMove(pParse, regResult, iParm, 1);
94863         /* The LIMIT clause will jump out of the loop for us */
94864       }
94865       break;
94866     }
94867 #endif /* #ifndef SQLCIPHER_OMIT_SUBQUERY */
94868
94869     /* Send the data to the callback function or to a subroutine.  In the
94870     ** case of a subroutine, the subroutine itself is responsible for
94871     ** popping the data from the stack.
94872     */
94873     case SRT_Coroutine:
94874     case SRT_Output: {
94875       testcase( eDest==SRT_Coroutine );
94876       testcase( eDest==SRT_Output );
94877       if( pOrderBy ){
94878         int r1 = sqlcipher3GetTempReg(pParse);
94879         sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94880         pushOntoSorter(pParse, pOrderBy, p, r1);
94881         sqlcipher3ReleaseTempReg(pParse, r1);
94882       }else if( eDest==SRT_Coroutine ){
94883         sqlcipher3VdbeAddOp1(v, OP_Yield, pDest->iParm);
94884       }else{
94885         sqlcipher3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
94886         sqlcipher3ExprCacheAffinityChange(pParse, regResult, nColumn);
94887       }
94888       break;
94889     }
94890
94891 #if !defined(SQLCIPHER_OMIT_TRIGGER)
94892     /* Discard the results.  This is used for SELECT statements inside
94893     ** the body of a TRIGGER.  The purpose of such selects is to call
94894     ** user-defined functions that have side effects.  We do not care
94895     ** about the actual results of the select.
94896     */
94897     default: {
94898       assert( eDest==SRT_Discard );
94899       break;
94900     }
94901 #endif
94902   }
94903
94904   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
94905   ** there is a sorter, in which case the sorter has already limited
94906   ** the output for us.
94907   */
94908   if( pOrderBy==0 && p->iLimit ){
94909     sqlcipher3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
94910   }
94911 }
94912
94913 /*
94914 ** Given an expression list, generate a KeyInfo structure that records
94915 ** the collating sequence for each expression in that expression list.
94916 **
94917 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
94918 ** KeyInfo structure is appropriate for initializing a virtual index to
94919 ** implement that clause.  If the ExprList is the result set of a SELECT
94920 ** then the KeyInfo structure is appropriate for initializing a virtual
94921 ** index to implement a DISTINCT test.
94922 **
94923 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
94924 ** function is responsible for seeing that this structure is eventually
94925 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
94926 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
94927 */
94928 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
94929   sqlcipher3 *db = pParse->db;
94930   int nExpr;
94931   KeyInfo *pInfo;
94932   struct ExprList_item *pItem;
94933   int i;
94934
94935   nExpr = pList->nExpr;
94936   pInfo = sqlcipher3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
94937   if( pInfo ){
94938     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
94939     pInfo->nField = (u16)nExpr;
94940     pInfo->enc = ENC(db);
94941     pInfo->db = db;
94942     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
94943       CollSeq *pColl;
94944       pColl = sqlcipher3ExprCollSeq(pParse, pItem->pExpr);
94945       if( !pColl ){
94946         pColl = db->pDfltColl;
94947       }
94948       pInfo->aColl[i] = pColl;
94949       pInfo->aSortOrder[i] = pItem->sortOrder;
94950     }
94951   }
94952   return pInfo;
94953 }
94954
94955 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
94956 /*
94957 ** Name of the connection operator, used for error messages.
94958 */
94959 static const char *selectOpName(int id){
94960   char *z;
94961   switch( id ){
94962     case TK_ALL:       z = "UNION ALL";   break;
94963     case TK_INTERSECT: z = "INTERSECT";   break;
94964     case TK_EXCEPT:    z = "EXCEPT";      break;
94965     default:           z = "UNION";       break;
94966   }
94967   return z;
94968 }
94969 #endif /* SQLCIPHER_OMIT_COMPOUND_SELECT */
94970
94971 #ifndef SQLCIPHER_OMIT_EXPLAIN
94972 /*
94973 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
94974 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
94975 ** where the caption is of the form:
94976 **
94977 **   "USE TEMP B-TREE FOR xxx"
94978 **
94979 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
94980 ** is determined by the zUsage argument.
94981 */
94982 static void explainTempTable(Parse *pParse, const char *zUsage){
94983   if( pParse->explain==2 ){
94984     Vdbe *v = pParse->pVdbe;
94985     char *zMsg = sqlcipher3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
94986     sqlcipher3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
94987   }
94988 }
94989
94990 /*
94991 ** Assign expression b to lvalue a. A second, no-op, version of this macro
94992 ** is provided when SQLCIPHER_OMIT_EXPLAIN is defined. This allows the code
94993 ** in sqlcipher3Select() to assign values to structure member variables that
94994 ** only exist if SQLCIPHER_OMIT_EXPLAIN is not defined without polluting the
94995 ** code with #ifndef directives.
94996 */
94997 # define explainSetInteger(a, b) a = b
94998
94999 #else
95000 /* No-op versions of the explainXXX() functions and macros. */
95001 # define explainTempTable(y,z)
95002 # define explainSetInteger(y,z)
95003 #endif
95004
95005 #if !defined(SQLCIPHER_OMIT_EXPLAIN) && !defined(SQLCIPHER_OMIT_COMPOUND_SELECT)
95006 /*
95007 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95008 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95009 ** where the caption is of one of the two forms:
95010 **
95011 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
95012 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
95013 **
95014 ** where iSub1 and iSub2 are the integers passed as the corresponding
95015 ** function parameters, and op is the text representation of the parameter
95016 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
95017 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
95018 ** false, or the second form if it is true.
95019 */
95020 static void explainComposite(
95021   Parse *pParse,                  /* Parse context */
95022   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
95023   int iSub1,                      /* Subquery id 1 */
95024   int iSub2,                      /* Subquery id 2 */
95025   int bUseTmp                     /* True if a temp table was used */
95026 ){
95027   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
95028   if( pParse->explain==2 ){
95029     Vdbe *v = pParse->pVdbe;
95030     char *zMsg = sqlcipher3MPrintf(
95031         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95032         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95033     );
95034     sqlcipher3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95035   }
95036 }
95037 #else
95038 /* No-op versions of the explainXXX() functions and macros. */
95039 # define explainComposite(v,w,x,y,z)
95040 #endif
95041
95042 /*
95043 ** If the inner loop was generated using a non-null pOrderBy argument,
95044 ** then the results were placed in a sorter.  After the loop is terminated
95045 ** we need to run the sorter and output the results.  The following
95046 ** routine generates the code needed to do that.
95047 */
95048 static void generateSortTail(
95049   Parse *pParse,    /* Parsing context */
95050   Select *p,        /* The SELECT statement */
95051   Vdbe *v,          /* Generate code into this VDBE */
95052   int nColumn,      /* Number of columns of data */
95053   SelectDest *pDest /* Write the sorted results here */
95054 ){
95055   int addrBreak = sqlcipher3VdbeMakeLabel(v);     /* Jump here to exit loop */
95056   int addrContinue = sqlcipher3VdbeMakeLabel(v);  /* Jump here for next cycle */
95057   int addr;
95058   int iTab;
95059   int pseudoTab = 0;
95060   ExprList *pOrderBy = p->pOrderBy;
95061
95062   int eDest = pDest->eDest;
95063   int iParm = pDest->iParm;
95064
95065   int regRow;
95066   int regRowid;
95067
95068   iTab = pOrderBy->iECursor;
95069   regRow = sqlcipher3GetTempReg(pParse);
95070   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95071     pseudoTab = pParse->nTab++;
95072     sqlcipher3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95073     regRowid = 0;
95074   }else{
95075     regRowid = sqlcipher3GetTempReg(pParse);
95076   }
95077   if( p->selFlags & SF_UseSorter ){
95078     int regSortOut = ++pParse->nMem;
95079     int ptab2 = pParse->nTab++;
95080     sqlcipher3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95081     addr = 1 + sqlcipher3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95082     codeOffset(v, p, addrContinue);
95083     sqlcipher3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95084     sqlcipher3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95085     sqlcipher3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95086   }else{
95087     addr = 1 + sqlcipher3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95088     codeOffset(v, p, addrContinue);
95089     sqlcipher3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95090   }
95091   switch( eDest ){
95092     case SRT_Table:
95093     case SRT_EphemTab: {
95094       testcase( eDest==SRT_Table );
95095       testcase( eDest==SRT_EphemTab );
95096       sqlcipher3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95097       sqlcipher3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95098       sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
95099       break;
95100     }
95101 #ifndef SQLCIPHER_OMIT_SUBQUERY
95102     case SRT_Set: {
95103       assert( nColumn==1 );
95104       sqlcipher3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
95105       sqlcipher3ExprCacheAffinityChange(pParse, regRow, 1);
95106       sqlcipher3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95107       break;
95108     }
95109     case SRT_Mem: {
95110       assert( nColumn==1 );
95111       sqlcipher3ExprCodeMove(pParse, regRow, iParm, 1);
95112       /* The LIMIT clause will terminate the loop for us */
95113       break;
95114     }
95115 #endif
95116     default: {
95117       int i;
95118       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
95119       testcase( eDest==SRT_Output );
95120       testcase( eDest==SRT_Coroutine );
95121       for(i=0; i<nColumn; i++){
95122         assert( regRow!=pDest->iMem+i );
95123         sqlcipher3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
95124         if( i==0 ){
95125           sqlcipher3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95126         }
95127       }
95128       if( eDest==SRT_Output ){
95129         sqlcipher3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
95130         sqlcipher3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
95131       }else{
95132         sqlcipher3VdbeAddOp1(v, OP_Yield, pDest->iParm);
95133       }
95134       break;
95135     }
95136   }
95137   sqlcipher3ReleaseTempReg(pParse, regRow);
95138   sqlcipher3ReleaseTempReg(pParse, regRowid);
95139
95140   /* The bottom of the loop
95141   */
95142   sqlcipher3VdbeResolveLabel(v, addrContinue);
95143   if( p->selFlags & SF_UseSorter ){
95144     sqlcipher3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95145   }else{
95146     sqlcipher3VdbeAddOp2(v, OP_Next, iTab, addr);
95147   }
95148   sqlcipher3VdbeResolveLabel(v, addrBreak);
95149   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95150     sqlcipher3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95151   }
95152 }
95153
95154 /*
95155 ** Return a pointer to a string containing the 'declaration type' of the
95156 ** expression pExpr. The string may be treated as static by the caller.
95157 **
95158 ** The declaration type is the exact datatype definition extracted from the
95159 ** original CREATE TABLE statement if the expression is a column. The
95160 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
95161 ** is considered a column can be complex in the presence of subqueries. The
95162 ** result-set expression in all of the following SELECT statements is 
95163 ** considered a column by this function.
95164 **
95165 **   SELECT col FROM tbl;
95166 **   SELECT (SELECT col FROM tbl;
95167 **   SELECT (SELECT col FROM tbl);
95168 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
95169 ** 
95170 ** The declaration type for any expression other than a column is NULL.
95171 */
95172 static const char *columnType(
95173   NameContext *pNC, 
95174   Expr *pExpr,
95175   const char **pzOriginDb,
95176   const char **pzOriginTab,
95177   const char **pzOriginCol
95178 ){
95179   char const *zType = 0;
95180   char const *zOriginDb = 0;
95181   char const *zOriginTab = 0;
95182   char const *zOriginCol = 0;
95183   int j;
95184   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95185
95186   switch( pExpr->op ){
95187     case TK_AGG_COLUMN:
95188     case TK_COLUMN: {
95189       /* The expression is a column. Locate the table the column is being
95190       ** extracted from in NameContext.pSrcList. This table may be real
95191       ** database table or a subquery.
95192       */
95193       Table *pTab = 0;            /* Table structure column is extracted from */
95194       Select *pS = 0;             /* Select the column is extracted from */
95195       int iCol = pExpr->iColumn;  /* Index of column in pTab */
95196       testcase( pExpr->op==TK_AGG_COLUMN );
95197       testcase( pExpr->op==TK_COLUMN );
95198       while( pNC && !pTab ){
95199         SrcList *pTabList = pNC->pSrcList;
95200         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95201         if( j<pTabList->nSrc ){
95202           pTab = pTabList->a[j].pTab;
95203           pS = pTabList->a[j].pSelect;
95204         }else{
95205           pNC = pNC->pNext;
95206         }
95207       }
95208
95209       if( pTab==0 ){
95210         /* At one time, code such as "SELECT new.x" within a trigger would
95211         ** cause this condition to run.  Since then, we have restructured how
95212         ** trigger code is generated and so this condition is no longer 
95213         ** possible. However, it can still be true for statements like
95214         ** the following:
95215         **
95216         **   CREATE TABLE t1(col INTEGER);
95217         **   SELECT (SELECT t1.col) FROM FROM t1;
95218         **
95219         ** when columnType() is called on the expression "t1.col" in the 
95220         ** sub-select. In this case, set the column type to NULL, even
95221         ** though it should really be "INTEGER".
95222         **
95223         ** This is not a problem, as the column type of "t1.col" is never
95224         ** used. When columnType() is called on the expression 
95225         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95226         ** branch below.  */
95227         break;
95228       }
95229
95230       assert( pTab && pExpr->pTab==pTab );
95231       if( pS ){
95232         /* The "table" is actually a sub-select or a view in the FROM clause
95233         ** of the SELECT statement. Return the declaration type and origin
95234         ** data for the result-set column of the sub-select.
95235         */
95236         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95237           /* If iCol is less than zero, then the expression requests the
95238           ** rowid of the sub-select or view. This expression is legal (see 
95239           ** test case misc2.2.2) - it always evaluates to NULL.
95240           */
95241           NameContext sNC;
95242           Expr *p = pS->pEList->a[iCol].pExpr;
95243           sNC.pSrcList = pS->pSrc;
95244           sNC.pNext = pNC;
95245           sNC.pParse = pNC->pParse;
95246           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95247         }
95248       }else if( ALWAYS(pTab->pSchema) ){
95249         /* A real table */
95250         assert( !pS );
95251         if( iCol<0 ) iCol = pTab->iPKey;
95252         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95253         if( iCol<0 ){
95254           zType = "INTEGER";
95255           zOriginCol = "rowid";
95256         }else{
95257           zType = pTab->aCol[iCol].zType;
95258           zOriginCol = pTab->aCol[iCol].zName;
95259         }
95260         zOriginTab = pTab->zName;
95261         if( pNC->pParse ){
95262           int iDb = sqlcipher3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95263           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95264         }
95265       }
95266       break;
95267     }
95268 #ifndef SQLCIPHER_OMIT_SUBQUERY
95269     case TK_SELECT: {
95270       /* The expression is a sub-select. Return the declaration type and
95271       ** origin info for the single column in the result set of the SELECT
95272       ** statement.
95273       */
95274       NameContext sNC;
95275       Select *pS = pExpr->x.pSelect;
95276       Expr *p = pS->pEList->a[0].pExpr;
95277       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95278       sNC.pSrcList = pS->pSrc;
95279       sNC.pNext = pNC;
95280       sNC.pParse = pNC->pParse;
95281       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95282       break;
95283     }
95284 #endif
95285   }
95286   
95287   if( pzOriginDb ){
95288     assert( pzOriginTab && pzOriginCol );
95289     *pzOriginDb = zOriginDb;
95290     *pzOriginTab = zOriginTab;
95291     *pzOriginCol = zOriginCol;
95292   }
95293   return zType;
95294 }
95295
95296 /*
95297 ** Generate code that will tell the VDBE the declaration types of columns
95298 ** in the result set.
95299 */
95300 static void generateColumnTypes(
95301   Parse *pParse,      /* Parser context */
95302   SrcList *pTabList,  /* List of tables */
95303   ExprList *pEList    /* Expressions defining the result set */
95304 ){
95305 #ifndef SQLCIPHER_OMIT_DECLTYPE
95306   Vdbe *v = pParse->pVdbe;
95307   int i;
95308   NameContext sNC;
95309   sNC.pSrcList = pTabList;
95310   sNC.pParse = pParse;
95311   for(i=0; i<pEList->nExpr; i++){
95312     Expr *p = pEList->a[i].pExpr;
95313     const char *zType;
95314 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
95315     const char *zOrigDb = 0;
95316     const char *zOrigTab = 0;
95317     const char *zOrigCol = 0;
95318     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95319
95320     /* The vdbe must make its own copy of the column-type and other 
95321     ** column specific strings, in case the schema is reset before this
95322     ** virtual machine is deleted.
95323     */
95324     sqlcipher3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLCIPHER_TRANSIENT);
95325     sqlcipher3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLCIPHER_TRANSIENT);
95326     sqlcipher3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLCIPHER_TRANSIENT);
95327 #else
95328     zType = columnType(&sNC, p, 0, 0, 0);
95329 #endif
95330     sqlcipher3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLCIPHER_TRANSIENT);
95331   }
95332 #endif /* SQLCIPHER_OMIT_DECLTYPE */
95333 }
95334
95335 /*
95336 ** Generate code that will tell the VDBE the names of columns
95337 ** in the result set.  This information is used to provide the
95338 ** azCol[] values in the callback.
95339 */
95340 static void generateColumnNames(
95341   Parse *pParse,      /* Parser context */
95342   SrcList *pTabList,  /* List of tables */
95343   ExprList *pEList    /* Expressions defining the result set */
95344 ){
95345   Vdbe *v = pParse->pVdbe;
95346   int i, j;
95347   sqlcipher3 *db = pParse->db;
95348   int fullNames, shortNames;
95349
95350 #ifndef SQLCIPHER_OMIT_EXPLAIN
95351   /* If this is an EXPLAIN, skip this step */
95352   if( pParse->explain ){
95353     return;
95354   }
95355 #endif
95356
95357   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95358   pParse->colNamesSet = 1;
95359   fullNames = (db->flags & SQLCIPHER_FullColNames)!=0;
95360   shortNames = (db->flags & SQLCIPHER_ShortColNames)!=0;
95361   sqlcipher3VdbeSetNumCols(v, pEList->nExpr);
95362   for(i=0; i<pEList->nExpr; i++){
95363     Expr *p;
95364     p = pEList->a[i].pExpr;
95365     if( NEVER(p==0) ) continue;
95366     if( pEList->a[i].zName ){
95367       char *zName = pEList->a[i].zName;
95368       sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLCIPHER_TRANSIENT);
95369     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95370       Table *pTab;
95371       char *zCol;
95372       int iCol = p->iColumn;
95373       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95374         if( pTabList->a[j].iCursor==p->iTable ) break;
95375       }
95376       assert( j<pTabList->nSrc );
95377       pTab = pTabList->a[j].pTab;
95378       if( iCol<0 ) iCol = pTab->iPKey;
95379       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95380       if( iCol<0 ){
95381         zCol = "rowid";
95382       }else{
95383         zCol = pTab->aCol[iCol].zName;
95384       }
95385       if( !shortNames && !fullNames ){
95386         sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, 
95387             sqlcipher3DbStrDup(db, pEList->a[i].zSpan), SQLCIPHER_DYNAMIC);
95388       }else if( fullNames ){
95389         char *zName = 0;
95390         zName = sqlcipher3MPrintf(db, "%s.%s", pTab->zName, zCol);
95391         sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLCIPHER_DYNAMIC);
95392       }else{
95393         sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLCIPHER_TRANSIENT);
95394       }
95395     }else{
95396       sqlcipher3VdbeSetColName(v, i, COLNAME_NAME, 
95397           sqlcipher3DbStrDup(db, pEList->a[i].zSpan), SQLCIPHER_DYNAMIC);
95398     }
95399   }
95400   generateColumnTypes(pParse, pTabList, pEList);
95401 }
95402
95403 /*
95404 ** Given a an expression list (which is really the list of expressions
95405 ** that form the result set of a SELECT statement) compute appropriate
95406 ** column names for a table that would hold the expression list.
95407 **
95408 ** All column names will be unique.
95409 **
95410 ** Only the column names are computed.  Column.zType, Column.zColl,
95411 ** and other fields of Column are zeroed.
95412 **
95413 ** Return SQLCIPHER_OK on success.  If a memory allocation error occurs,
95414 ** store NULL in *paCol and 0 in *pnCol and return SQLCIPHER_NOMEM.
95415 */
95416 static int selectColumnsFromExprList(
95417   Parse *pParse,          /* Parsing context */
95418   ExprList *pEList,       /* Expr list from which to derive column names */
95419   int *pnCol,             /* Write the number of columns here */
95420   Column **paCol          /* Write the new column list here */
95421 ){
95422   sqlcipher3 *db = pParse->db;   /* Database connection */
95423   int i, j;                   /* Loop counters */
95424   int cnt;                    /* Index added to make the name unique */
95425   Column *aCol, *pCol;        /* For looping over result columns */
95426   int nCol;                   /* Number of columns in the result set */
95427   Expr *p;                    /* Expression for a single result column */
95428   char *zName;                /* Column name */
95429   int nName;                  /* Size of name in zName[] */
95430
95431   *pnCol = nCol = pEList->nExpr;
95432   aCol = *paCol = sqlcipher3DbMallocZero(db, sizeof(aCol[0])*nCol);
95433   if( aCol==0 ) return SQLCIPHER_NOMEM;
95434   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95435     /* Get an appropriate name for the column
95436     */
95437     p = pEList->a[i].pExpr;
95438     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
95439                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
95440     if( (zName = pEList->a[i].zName)!=0 ){
95441       /* If the column contains an "AS <name>" phrase, use <name> as the name */
95442       zName = sqlcipher3DbStrDup(db, zName);
95443     }else{
95444       Expr *pColExpr = p;  /* The expression that is the result column name */
95445       Table *pTab;         /* Table associated with this expression */
95446       while( pColExpr->op==TK_DOT ){
95447         pColExpr = pColExpr->pRight;
95448         assert( pColExpr!=0 );
95449       }
95450       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
95451         /* For columns use the column name name */
95452         int iCol = pColExpr->iColumn;
95453         pTab = pColExpr->pTab;
95454         if( iCol<0 ) iCol = pTab->iPKey;
95455         zName = sqlcipher3MPrintf(db, "%s",
95456                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
95457       }else if( pColExpr->op==TK_ID ){
95458         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
95459         zName = sqlcipher3MPrintf(db, "%s", pColExpr->u.zToken);
95460       }else{
95461         /* Use the original text of the column expression as its name */
95462         zName = sqlcipher3MPrintf(db, "%s", pEList->a[i].zSpan);
95463       }
95464     }
95465     if( db->mallocFailed ){
95466       sqlcipher3DbFree(db, zName);
95467       break;
95468     }
95469
95470     /* Make sure the column name is unique.  If the name is not unique,
95471     ** append a integer to the name so that it becomes unique.
95472     */
95473     nName = sqlcipher3Strlen30(zName);
95474     for(j=cnt=0; j<i; j++){
95475       if( sqlcipher3StrICmp(aCol[j].zName, zName)==0 ){
95476         char *zNewName;
95477         zName[nName] = 0;
95478         zNewName = sqlcipher3MPrintf(db, "%s:%d", zName, ++cnt);
95479         sqlcipher3DbFree(db, zName);
95480         zName = zNewName;
95481         j = -1;
95482         if( zName==0 ) break;
95483       }
95484     }
95485     pCol->zName = zName;
95486   }
95487   if( db->mallocFailed ){
95488     for(j=0; j<i; j++){
95489       sqlcipher3DbFree(db, aCol[j].zName);
95490     }
95491     sqlcipher3DbFree(db, aCol);
95492     *paCol = 0;
95493     *pnCol = 0;
95494     return SQLCIPHER_NOMEM;
95495   }
95496   return SQLCIPHER_OK;
95497 }
95498
95499 /*
95500 ** Add type and collation information to a column list based on
95501 ** a SELECT statement.
95502 ** 
95503 ** The column list presumably came from selectColumnNamesFromExprList().
95504 ** The column list has only names, not types or collations.  This
95505 ** routine goes through and adds the types and collations.
95506 **
95507 ** This routine requires that all identifiers in the SELECT
95508 ** statement be resolved.
95509 */
95510 static void selectAddColumnTypeAndCollation(
95511   Parse *pParse,        /* Parsing contexts */
95512   int nCol,             /* Number of columns */
95513   Column *aCol,         /* List of columns */
95514   Select *pSelect       /* SELECT used to determine types and collations */
95515 ){
95516   sqlcipher3 *db = pParse->db;
95517   NameContext sNC;
95518   Column *pCol;
95519   CollSeq *pColl;
95520   int i;
95521   Expr *p;
95522   struct ExprList_item *a;
95523
95524   assert( pSelect!=0 );
95525   assert( (pSelect->selFlags & SF_Resolved)!=0 );
95526   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
95527   if( db->mallocFailed ) return;
95528   memset(&sNC, 0, sizeof(sNC));
95529   sNC.pSrcList = pSelect->pSrc;
95530   a = pSelect->pEList->a;
95531   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95532     p = a[i].pExpr;
95533     pCol->zType = sqlcipher3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
95534     pCol->affinity = sqlcipher3ExprAffinity(p);
95535     if( pCol->affinity==0 ) pCol->affinity = SQLCIPHER_AFF_NONE;
95536     pColl = sqlcipher3ExprCollSeq(pParse, p);
95537     if( pColl ){
95538       pCol->zColl = sqlcipher3DbStrDup(db, pColl->zName);
95539     }
95540   }
95541 }
95542
95543 /*
95544 ** Given a SELECT statement, generate a Table structure that describes
95545 ** the result set of that SELECT.
95546 */
95547 SQLCIPHER_PRIVATE Table *sqlcipher3ResultSetOfSelect(Parse *pParse, Select *pSelect){
95548   Table *pTab;
95549   sqlcipher3 *db = pParse->db;
95550   int savedFlags;
95551
95552   savedFlags = db->flags;
95553   db->flags &= ~SQLCIPHER_FullColNames;
95554   db->flags |= SQLCIPHER_ShortColNames;
95555   sqlcipher3SelectPrep(pParse, pSelect, 0);
95556   if( pParse->nErr ) return 0;
95557   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
95558   db->flags = savedFlags;
95559   pTab = sqlcipher3DbMallocZero(db, sizeof(Table) );
95560   if( pTab==0 ){
95561     return 0;
95562   }
95563   /* The sqlcipher3ResultSetOfSelect() is only used n contexts where lookaside
95564   ** is disabled */
95565   assert( db->lookaside.bEnabled==0 );
95566   pTab->nRef = 1;
95567   pTab->zName = 0;
95568   pTab->nRowEst = 1000000;
95569   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
95570   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
95571   pTab->iPKey = -1;
95572   if( db->mallocFailed ){
95573     sqlcipher3DeleteTable(db, pTab);
95574     return 0;
95575   }
95576   return pTab;
95577 }
95578
95579 /*
95580 ** Get a VDBE for the given parser context.  Create a new one if necessary.
95581 ** If an error occurs, return NULL and leave a message in pParse.
95582 */
95583 SQLCIPHER_PRIVATE Vdbe *sqlcipher3GetVdbe(Parse *pParse){
95584   Vdbe *v = pParse->pVdbe;
95585   if( v==0 ){
95586     v = pParse->pVdbe = sqlcipher3VdbeCreate(pParse->db);
95587 #ifndef SQLCIPHER_OMIT_TRACE
95588     if( v ){
95589       sqlcipher3VdbeAddOp0(v, OP_Trace);
95590     }
95591 #endif
95592   }
95593   return v;
95594 }
95595
95596
95597 /*
95598 ** Compute the iLimit and iOffset fields of the SELECT based on the
95599 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
95600 ** that appear in the original SQL statement after the LIMIT and OFFSET
95601 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
95602 ** are the integer memory register numbers for counters used to compute 
95603 ** the limit and offset.  If there is no limit and/or offset, then 
95604 ** iLimit and iOffset are negative.
95605 **
95606 ** This routine changes the values of iLimit and iOffset only if
95607 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
95608 ** iOffset should have been preset to appropriate default values
95609 ** (usually but not always -1) prior to calling this routine.
95610 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
95611 ** redefined.  The UNION ALL operator uses this property to force
95612 ** the reuse of the same limit and offset registers across multiple
95613 ** SELECT statements.
95614 */
95615 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
95616   Vdbe *v = 0;
95617   int iLimit = 0;
95618   int iOffset;
95619   int addr1, n;
95620   if( p->iLimit ) return;
95621
95622   /* 
95623   ** "LIMIT -1" always shows all rows.  There is some
95624   ** contraversy about what the correct behavior should be.
95625   ** The current implementation interprets "LIMIT 0" to mean
95626   ** no rows.
95627   */
95628   sqlcipher3ExprCacheClear(pParse);
95629   assert( p->pOffset==0 || p->pLimit!=0 );
95630   if( p->pLimit ){
95631     p->iLimit = iLimit = ++pParse->nMem;
95632     v = sqlcipher3GetVdbe(pParse);
95633     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
95634     if( sqlcipher3ExprIsInteger(p->pLimit, &n) ){
95635       sqlcipher3VdbeAddOp2(v, OP_Integer, n, iLimit);
95636       VdbeComment((v, "LIMIT counter"));
95637       if( n==0 ){
95638         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, iBreak);
95639       }else{
95640         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
95641       }
95642     }else{
95643       sqlcipher3ExprCode(pParse, p->pLimit, iLimit);
95644       sqlcipher3VdbeAddOp1(v, OP_MustBeInt, iLimit);
95645       VdbeComment((v, "LIMIT counter"));
95646       sqlcipher3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
95647     }
95648     if( p->pOffset ){
95649       p->iOffset = iOffset = ++pParse->nMem;
95650       pParse->nMem++;   /* Allocate an extra register for limit+offset */
95651       sqlcipher3ExprCode(pParse, p->pOffset, iOffset);
95652       sqlcipher3VdbeAddOp1(v, OP_MustBeInt, iOffset);
95653       VdbeComment((v, "OFFSET counter"));
95654       addr1 = sqlcipher3VdbeAddOp1(v, OP_IfPos, iOffset);
95655       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iOffset);
95656       sqlcipher3VdbeJumpHere(v, addr1);
95657       sqlcipher3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
95658       VdbeComment((v, "LIMIT+OFFSET"));
95659       addr1 = sqlcipher3VdbeAddOp1(v, OP_IfPos, iLimit);
95660       sqlcipher3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
95661       sqlcipher3VdbeJumpHere(v, addr1);
95662     }
95663   }
95664 }
95665
95666 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
95667 /*
95668 ** Return the appropriate collating sequence for the iCol-th column of
95669 ** the result set for the compound-select statement "p".  Return NULL if
95670 ** the column has no default collating sequence.
95671 **
95672 ** The collating sequence for the compound select is taken from the
95673 ** left-most term of the select that has a collating sequence.
95674 */
95675 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
95676   CollSeq *pRet;
95677   if( p->pPrior ){
95678     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
95679   }else{
95680     pRet = 0;
95681   }
95682   assert( iCol>=0 );
95683   if( pRet==0 && iCol<p->pEList->nExpr ){
95684     pRet = sqlcipher3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
95685   }
95686   return pRet;
95687 }
95688 #endif /* SQLCIPHER_OMIT_COMPOUND_SELECT */
95689
95690 /* Forward reference */
95691 static int multiSelectOrderBy(
95692   Parse *pParse,        /* Parsing context */
95693   Select *p,            /* The right-most of SELECTs to be coded */
95694   SelectDest *pDest     /* What to do with query results */
95695 );
95696
95697
95698 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
95699 /*
95700 ** This routine is called to process a compound query form from
95701 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
95702 ** INTERSECT
95703 **
95704 ** "p" points to the right-most of the two queries.  the query on the
95705 ** left is p->pPrior.  The left query could also be a compound query
95706 ** in which case this routine will be called recursively. 
95707 **
95708 ** The results of the total query are to be written into a destination
95709 ** of type eDest with parameter iParm.
95710 **
95711 ** Example 1:  Consider a three-way compound SQL statement.
95712 **
95713 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
95714 **
95715 ** This statement is parsed up as follows:
95716 **
95717 **     SELECT c FROM t3
95718 **      |
95719 **      `----->  SELECT b FROM t2
95720 **                |
95721 **                `------>  SELECT a FROM t1
95722 **
95723 ** The arrows in the diagram above represent the Select.pPrior pointer.
95724 ** So if this routine is called with p equal to the t3 query, then
95725 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
95726 **
95727 ** Notice that because of the way SQLite parses compound SELECTs, the
95728 ** individual selects always group from left to right.
95729 */
95730 static int multiSelect(
95731   Parse *pParse,        /* Parsing context */
95732   Select *p,            /* The right-most of SELECTs to be coded */
95733   SelectDest *pDest     /* What to do with query results */
95734 ){
95735   int rc = SQLCIPHER_OK;   /* Success code from a subroutine */
95736   Select *pPrior;       /* Another SELECT immediately to our left */
95737   Vdbe *v;              /* Generate code to this VDBE */
95738   SelectDest dest;      /* Alternative data destination */
95739   Select *pDelete = 0;  /* Chain of simple selects to delete */
95740   sqlcipher3 *db;          /* Database connection */
95741 #ifndef SQLCIPHER_OMIT_EXPLAIN
95742   int iSub1;            /* EQP id of left-hand query */
95743   int iSub2;            /* EQP id of right-hand query */
95744 #endif
95745
95746   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
95747   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
95748   */
95749   assert( p && p->pPrior );  /* Calling function guarantees this much */
95750   db = pParse->db;
95751   pPrior = p->pPrior;
95752   assert( pPrior->pRightmost!=pPrior );
95753   assert( pPrior->pRightmost==p->pRightmost );
95754   dest = *pDest;
95755   if( pPrior->pOrderBy ){
95756     sqlcipher3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
95757       selectOpName(p->op));
95758     rc = 1;
95759     goto multi_select_end;
95760   }
95761   if( pPrior->pLimit ){
95762     sqlcipher3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
95763       selectOpName(p->op));
95764     rc = 1;
95765     goto multi_select_end;
95766   }
95767
95768   v = sqlcipher3GetVdbe(pParse);
95769   assert( v!=0 );  /* The VDBE already created by calling function */
95770
95771   /* Create the destination temporary table if necessary
95772   */
95773   if( dest.eDest==SRT_EphemTab ){
95774     assert( p->pEList );
95775     sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
95776     sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
95777     dest.eDest = SRT_Table;
95778   }
95779
95780   /* Make sure all SELECTs in the statement have the same number of elements
95781   ** in their result sets.
95782   */
95783   assert( p->pEList && pPrior->pEList );
95784   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
95785     sqlcipher3ErrorMsg(pParse, "SELECTs to the left and right of %s"
95786       " do not have the same number of result columns", selectOpName(p->op));
95787     rc = 1;
95788     goto multi_select_end;
95789   }
95790
95791   /* Compound SELECTs that have an ORDER BY clause are handled separately.
95792   */
95793   if( p->pOrderBy ){
95794     return multiSelectOrderBy(pParse, p, pDest);
95795   }
95796
95797   /* Generate code for the left and right SELECT statements.
95798   */
95799   switch( p->op ){
95800     case TK_ALL: {
95801       int addr = 0;
95802       int nLimit;
95803       assert( !pPrior->pLimit );
95804       pPrior->pLimit = p->pLimit;
95805       pPrior->pOffset = p->pOffset;
95806       explainSetInteger(iSub1, pParse->iNextSelectId);
95807       rc = sqlcipher3Select(pParse, pPrior, &dest);
95808       p->pLimit = 0;
95809       p->pOffset = 0;
95810       if( rc ){
95811         goto multi_select_end;
95812       }
95813       p->pPrior = 0;
95814       p->iLimit = pPrior->iLimit;
95815       p->iOffset = pPrior->iOffset;
95816       if( p->iLimit ){
95817         addr = sqlcipher3VdbeAddOp1(v, OP_IfZero, p->iLimit);
95818         VdbeComment((v, "Jump ahead if LIMIT reached"));
95819       }
95820       explainSetInteger(iSub2, pParse->iNextSelectId);
95821       rc = sqlcipher3Select(pParse, p, &dest);
95822       testcase( rc!=SQLCIPHER_OK );
95823       pDelete = p->pPrior;
95824       p->pPrior = pPrior;
95825       p->nSelectRow += pPrior->nSelectRow;
95826       if( pPrior->pLimit
95827        && sqlcipher3ExprIsInteger(pPrior->pLimit, &nLimit)
95828        && p->nSelectRow > (double)nLimit 
95829       ){
95830         p->nSelectRow = (double)nLimit;
95831       }
95832       if( addr ){
95833         sqlcipher3VdbeJumpHere(v, addr);
95834       }
95835       break;
95836     }
95837     case TK_EXCEPT:
95838     case TK_UNION: {
95839       int unionTab;    /* Cursor number of the temporary table holding result */
95840       u8 op = 0;       /* One of the SRT_ operations to apply to self */
95841       int priorOp;     /* The SRT_ operation to apply to prior selects */
95842       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
95843       int addr;
95844       SelectDest uniondest;
95845
95846       testcase( p->op==TK_EXCEPT );
95847       testcase( p->op==TK_UNION );
95848       priorOp = SRT_Union;
95849       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
95850         /* We can reuse a temporary table generated by a SELECT to our
95851         ** right.
95852         */
95853         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
95854                                      ** of a 3-way or more compound */
95855         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
95856         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
95857         unionTab = dest.iParm;
95858       }else{
95859         /* We will need to create our own temporary table to hold the
95860         ** intermediate results.
95861         */
95862         unionTab = pParse->nTab++;
95863         assert( p->pOrderBy==0 );
95864         addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
95865         assert( p->addrOpenEphm[0] == -1 );
95866         p->addrOpenEphm[0] = addr;
95867         p->pRightmost->selFlags |= SF_UsesEphemeral;
95868         assert( p->pEList );
95869       }
95870
95871       /* Code the SELECT statements to our left
95872       */
95873       assert( !pPrior->pOrderBy );
95874       sqlcipher3SelectDestInit(&uniondest, priorOp, unionTab);
95875       explainSetInteger(iSub1, pParse->iNextSelectId);
95876       rc = sqlcipher3Select(pParse, pPrior, &uniondest);
95877       if( rc ){
95878         goto multi_select_end;
95879       }
95880
95881       /* Code the current SELECT statement
95882       */
95883       if( p->op==TK_EXCEPT ){
95884         op = SRT_Except;
95885       }else{
95886         assert( p->op==TK_UNION );
95887         op = SRT_Union;
95888       }
95889       p->pPrior = 0;
95890       pLimit = p->pLimit;
95891       p->pLimit = 0;
95892       pOffset = p->pOffset;
95893       p->pOffset = 0;
95894       uniondest.eDest = op;
95895       explainSetInteger(iSub2, pParse->iNextSelectId);
95896       rc = sqlcipher3Select(pParse, p, &uniondest);
95897       testcase( rc!=SQLCIPHER_OK );
95898       /* Query flattening in sqlcipher3Select() might refill p->pOrderBy.
95899       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
95900       sqlcipher3ExprListDelete(db, p->pOrderBy);
95901       pDelete = p->pPrior;
95902       p->pPrior = pPrior;
95903       p->pOrderBy = 0;
95904       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
95905       sqlcipher3ExprDelete(db, p->pLimit);
95906       p->pLimit = pLimit;
95907       p->pOffset = pOffset;
95908       p->iLimit = 0;
95909       p->iOffset = 0;
95910
95911       /* Convert the data in the temporary table into whatever form
95912       ** it is that we currently need.
95913       */
95914       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
95915       if( dest.eDest!=priorOp ){
95916         int iCont, iBreak, iStart;
95917         assert( p->pEList );
95918         if( dest.eDest==SRT_Output ){
95919           Select *pFirst = p;
95920           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95921           generateColumnNames(pParse, 0, pFirst->pEList);
95922         }
95923         iBreak = sqlcipher3VdbeMakeLabel(v);
95924         iCont = sqlcipher3VdbeMakeLabel(v);
95925         computeLimitRegisters(pParse, p, iBreak);
95926         sqlcipher3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
95927         iStart = sqlcipher3VdbeCurrentAddr(v);
95928         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
95929                         0, -1, &dest, iCont, iBreak);
95930         sqlcipher3VdbeResolveLabel(v, iCont);
95931         sqlcipher3VdbeAddOp2(v, OP_Next, unionTab, iStart);
95932         sqlcipher3VdbeResolveLabel(v, iBreak);
95933         sqlcipher3VdbeAddOp2(v, OP_Close, unionTab, 0);
95934       }
95935       break;
95936     }
95937     default: assert( p->op==TK_INTERSECT ); {
95938       int tab1, tab2;
95939       int iCont, iBreak, iStart;
95940       Expr *pLimit, *pOffset;
95941       int addr;
95942       SelectDest intersectdest;
95943       int r1;
95944
95945       /* INTERSECT is different from the others since it requires
95946       ** two temporary tables.  Hence it has its own case.  Begin
95947       ** by allocating the tables we will need.
95948       */
95949       tab1 = pParse->nTab++;
95950       tab2 = pParse->nTab++;
95951       assert( p->pOrderBy==0 );
95952
95953       addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
95954       assert( p->addrOpenEphm[0] == -1 );
95955       p->addrOpenEphm[0] = addr;
95956       p->pRightmost->selFlags |= SF_UsesEphemeral;
95957       assert( p->pEList );
95958
95959       /* Code the SELECTs to our left into temporary table "tab1".
95960       */
95961       sqlcipher3SelectDestInit(&intersectdest, SRT_Union, tab1);
95962       explainSetInteger(iSub1, pParse->iNextSelectId);
95963       rc = sqlcipher3Select(pParse, pPrior, &intersectdest);
95964       if( rc ){
95965         goto multi_select_end;
95966       }
95967
95968       /* Code the current SELECT into temporary table "tab2"
95969       */
95970       addr = sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
95971       assert( p->addrOpenEphm[1] == -1 );
95972       p->addrOpenEphm[1] = addr;
95973       p->pPrior = 0;
95974       pLimit = p->pLimit;
95975       p->pLimit = 0;
95976       pOffset = p->pOffset;
95977       p->pOffset = 0;
95978       intersectdest.iParm = tab2;
95979       explainSetInteger(iSub2, pParse->iNextSelectId);
95980       rc = sqlcipher3Select(pParse, p, &intersectdest);
95981       testcase( rc!=SQLCIPHER_OK );
95982       pDelete = p->pPrior;
95983       p->pPrior = pPrior;
95984       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
95985       sqlcipher3ExprDelete(db, p->pLimit);
95986       p->pLimit = pLimit;
95987       p->pOffset = pOffset;
95988
95989       /* Generate code to take the intersection of the two temporary
95990       ** tables.
95991       */
95992       assert( p->pEList );
95993       if( dest.eDest==SRT_Output ){
95994         Select *pFirst = p;
95995         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95996         generateColumnNames(pParse, 0, pFirst->pEList);
95997       }
95998       iBreak = sqlcipher3VdbeMakeLabel(v);
95999       iCont = sqlcipher3VdbeMakeLabel(v);
96000       computeLimitRegisters(pParse, p, iBreak);
96001       sqlcipher3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
96002       r1 = sqlcipher3GetTempReg(pParse);
96003       iStart = sqlcipher3VdbeAddOp2(v, OP_RowKey, tab1, r1);
96004       sqlcipher3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
96005       sqlcipher3ReleaseTempReg(pParse, r1);
96006       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
96007                       0, -1, &dest, iCont, iBreak);
96008       sqlcipher3VdbeResolveLabel(v, iCont);
96009       sqlcipher3VdbeAddOp2(v, OP_Next, tab1, iStart);
96010       sqlcipher3VdbeResolveLabel(v, iBreak);
96011       sqlcipher3VdbeAddOp2(v, OP_Close, tab2, 0);
96012       sqlcipher3VdbeAddOp2(v, OP_Close, tab1, 0);
96013       break;
96014     }
96015   }
96016
96017   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
96018
96019   /* Compute collating sequences used by 
96020   ** temporary tables needed to implement the compound select.
96021   ** Attach the KeyInfo structure to all temporary tables.
96022   **
96023   ** This section is run by the right-most SELECT statement only.
96024   ** SELECT statements to the left always skip this part.  The right-most
96025   ** SELECT might also skip this part if it has no ORDER BY clause and
96026   ** no temp tables are required.
96027   */
96028   if( p->selFlags & SF_UsesEphemeral ){
96029     int i;                        /* Loop counter */
96030     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96031     Select *pLoop;                /* For looping through SELECT statements */
96032     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96033     int nCol;                     /* Number of columns in result set */
96034
96035     assert( p->pRightmost==p );
96036     nCol = p->pEList->nExpr;
96037     pKeyInfo = sqlcipher3DbMallocZero(db,
96038                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96039     if( !pKeyInfo ){
96040       rc = SQLCIPHER_NOMEM;
96041       goto multi_select_end;
96042     }
96043
96044     pKeyInfo->enc = ENC(db);
96045     pKeyInfo->nField = (u16)nCol;
96046
96047     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96048       *apColl = multiSelectCollSeq(pParse, p, i);
96049       if( 0==*apColl ){
96050         *apColl = db->pDfltColl;
96051       }
96052     }
96053
96054     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96055       for(i=0; i<2; i++){
96056         int addr = pLoop->addrOpenEphm[i];
96057         if( addr<0 ){
96058           /* If [0] is unused then [1] is also unused.  So we can
96059           ** always safely abort as soon as the first unused slot is found */
96060           assert( pLoop->addrOpenEphm[1]<0 );
96061           break;
96062         }
96063         sqlcipher3VdbeChangeP2(v, addr, nCol);
96064         sqlcipher3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96065         pLoop->addrOpenEphm[i] = -1;
96066       }
96067     }
96068     sqlcipher3DbFree(db, pKeyInfo);
96069   }
96070
96071 multi_select_end:
96072   pDest->iMem = dest.iMem;
96073   pDest->nMem = dest.nMem;
96074   sqlcipher3SelectDelete(db, pDelete);
96075   return rc;
96076 }
96077 #endif /* SQLCIPHER_OMIT_COMPOUND_SELECT */
96078
96079 /*
96080 ** Code an output subroutine for a coroutine implementation of a
96081 ** SELECT statment.
96082 **
96083 ** The data to be output is contained in pIn->iMem.  There are
96084 ** pIn->nMem columns to be output.  pDest is where the output should
96085 ** be sent.
96086 **
96087 ** regReturn is the number of the register holding the subroutine
96088 ** return address.
96089 **
96090 ** If regPrev>0 then it is the first register in a vector that
96091 ** records the previous output.  mem[regPrev] is a flag that is false
96092 ** if there has been no previous output.  If regPrev>0 then code is
96093 ** generated to suppress duplicates.  pKeyInfo is used for comparing
96094 ** keys.
96095 **
96096 ** If the LIMIT found in p->iLimit is reached, jump immediately to
96097 ** iBreak.
96098 */
96099 static int generateOutputSubroutine(
96100   Parse *pParse,          /* Parsing context */
96101   Select *p,              /* The SELECT statement */
96102   SelectDest *pIn,        /* Coroutine supplying data */
96103   SelectDest *pDest,      /* Where to send the data */
96104   int regReturn,          /* The return address register */
96105   int regPrev,            /* Previous result register.  No uniqueness if 0 */
96106   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96107   int p4type,             /* The p4 type for pKeyInfo */
96108   int iBreak              /* Jump here if we hit the LIMIT */
96109 ){
96110   Vdbe *v = pParse->pVdbe;
96111   int iContinue;
96112   int addr;
96113
96114   addr = sqlcipher3VdbeCurrentAddr(v);
96115   iContinue = sqlcipher3VdbeMakeLabel(v);
96116
96117   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
96118   */
96119   if( regPrev ){
96120     int j1, j2;
96121     j1 = sqlcipher3VdbeAddOp1(v, OP_IfNot, regPrev);
96122     j2 = sqlcipher3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
96123                               (char*)pKeyInfo, p4type);
96124     sqlcipher3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96125     sqlcipher3VdbeJumpHere(v, j1);
96126     sqlcipher3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
96127     sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96128   }
96129   if( pParse->db->mallocFailed ) return 0;
96130
96131   /* Suppress the the first OFFSET entries if there is an OFFSET clause
96132   */
96133   codeOffset(v, p, iContinue);
96134
96135   switch( pDest->eDest ){
96136     /* Store the result as data using a unique key.
96137     */
96138     case SRT_Table:
96139     case SRT_EphemTab: {
96140       int r1 = sqlcipher3GetTempReg(pParse);
96141       int r2 = sqlcipher3GetTempReg(pParse);
96142       testcase( pDest->eDest==SRT_Table );
96143       testcase( pDest->eDest==SRT_EphemTab );
96144       sqlcipher3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
96145       sqlcipher3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
96146       sqlcipher3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
96147       sqlcipher3VdbeChangeP5(v, OPFLAG_APPEND);
96148       sqlcipher3ReleaseTempReg(pParse, r2);
96149       sqlcipher3ReleaseTempReg(pParse, r1);
96150       break;
96151     }
96152
96153 #ifndef SQLCIPHER_OMIT_SUBQUERY
96154     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96155     ** then there should be a single item on the stack.  Write this
96156     ** item into the set table with bogus data.
96157     */
96158     case SRT_Set: {
96159       int r1;
96160       assert( pIn->nMem==1 );
96161       p->affinity = 
96162          sqlcipher3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
96163       r1 = sqlcipher3GetTempReg(pParse);
96164       sqlcipher3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
96165       sqlcipher3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
96166       sqlcipher3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
96167       sqlcipher3ReleaseTempReg(pParse, r1);
96168       break;
96169     }
96170
96171 #if 0  /* Never occurs on an ORDER BY query */
96172     /* If any row exist in the result set, record that fact and abort.
96173     */
96174     case SRT_Exists: {
96175       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
96176       /* The LIMIT clause will terminate the loop for us */
96177       break;
96178     }
96179 #endif
96180
96181     /* If this is a scalar select that is part of an expression, then
96182     ** store the results in the appropriate memory cell and break out
96183     ** of the scan loop.
96184     */
96185     case SRT_Mem: {
96186       assert( pIn->nMem==1 );
96187       sqlcipher3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
96188       /* The LIMIT clause will jump out of the loop for us */
96189       break;
96190     }
96191 #endif /* #ifndef SQLCIPHER_OMIT_SUBQUERY */
96192
96193     /* The results are stored in a sequence of registers
96194     ** starting at pDest->iMem.  Then the co-routine yields.
96195     */
96196     case SRT_Coroutine: {
96197       if( pDest->iMem==0 ){
96198         pDest->iMem = sqlcipher3GetTempRange(pParse, pIn->nMem);
96199         pDest->nMem = pIn->nMem;
96200       }
96201       sqlcipher3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
96202       sqlcipher3VdbeAddOp1(v, OP_Yield, pDest->iParm);
96203       break;
96204     }
96205
96206     /* If none of the above, then the result destination must be
96207     ** SRT_Output.  This routine is never called with any other
96208     ** destination other than the ones handled above or SRT_Output.
96209     **
96210     ** For SRT_Output, results are stored in a sequence of registers.  
96211     ** Then the OP_ResultRow opcode is used to cause sqlcipher3_step() to
96212     ** return the next row of result.
96213     */
96214     default: {
96215       assert( pDest->eDest==SRT_Output );
96216       sqlcipher3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
96217       sqlcipher3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
96218       break;
96219     }
96220   }
96221
96222   /* Jump to the end of the loop if the LIMIT is reached.
96223   */
96224   if( p->iLimit ){
96225     sqlcipher3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96226   }
96227
96228   /* Generate the subroutine return
96229   */
96230   sqlcipher3VdbeResolveLabel(v, iContinue);
96231   sqlcipher3VdbeAddOp1(v, OP_Return, regReturn);
96232
96233   return addr;
96234 }
96235
96236 /*
96237 ** Alternative compound select code generator for cases when there
96238 ** is an ORDER BY clause.
96239 **
96240 ** We assume a query of the following form:
96241 **
96242 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96243 **
96244 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96245 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
96246 ** co-routines.  Then run the co-routines in parallel and merge the results
96247 ** into the output.  In addition to the two coroutines (called selectA and
96248 ** selectB) there are 7 subroutines:
96249 **
96250 **    outA:    Move the output of the selectA coroutine into the output
96251 **             of the compound query.
96252 **
96253 **    outB:    Move the output of the selectB coroutine into the output
96254 **             of the compound query.  (Only generated for UNION and
96255 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96256 **             appears only in B.)
96257 **
96258 **    AltB:    Called when there is data from both coroutines and A<B.
96259 **
96260 **    AeqB:    Called when there is data from both coroutines and A==B.
96261 **
96262 **    AgtB:    Called when there is data from both coroutines and A>B.
96263 **
96264 **    EofA:    Called when data is exhausted from selectA.
96265 **
96266 **    EofB:    Called when data is exhausted from selectB.
96267 **
96268 ** The implementation of the latter five subroutines depend on which 
96269 ** <operator> is used:
96270 **
96271 **
96272 **             UNION ALL         UNION            EXCEPT          INTERSECT
96273 **          -------------  -----------------  --------------  -----------------
96274 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96275 **
96276 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96277 **
96278 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96279 **
96280 **   EofA:   outB, nextB      outB, nextB          halt             halt
96281 **
96282 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96283 **
96284 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96285 ** causes an immediate jump to EofA and an EOF on B following nextB causes
96286 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96287 ** following nextX causes a jump to the end of the select processing.
96288 **
96289 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96290 ** within the output subroutine.  The regPrev register set holds the previously
96291 ** output value.  A comparison is made against this value and the output
96292 ** is skipped if the next results would be the same as the previous.
96293 **
96294 ** The implementation plan is to implement the two coroutines and seven
96295 ** subroutines first, then put the control logic at the bottom.  Like this:
96296 **
96297 **          goto Init
96298 **     coA: coroutine for left query (A)
96299 **     coB: coroutine for right query (B)
96300 **    outA: output one row of A
96301 **    outB: output one row of B (UNION and UNION ALL only)
96302 **    EofA: ...
96303 **    EofB: ...
96304 **    AltB: ...
96305 **    AeqB: ...
96306 **    AgtB: ...
96307 **    Init: initialize coroutine registers
96308 **          yield coA
96309 **          if eof(A) goto EofA
96310 **          yield coB
96311 **          if eof(B) goto EofB
96312 **    Cmpr: Compare A, B
96313 **          Jump AltB, AeqB, AgtB
96314 **     End: ...
96315 **
96316 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96317 ** actually called using Gosub and they do not Return.  EofA and EofB loop
96318 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96319 ** and AgtB jump to either L2 or to one of EofA or EofB.
96320 */
96321 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
96322 static int multiSelectOrderBy(
96323   Parse *pParse,        /* Parsing context */
96324   Select *p,            /* The right-most of SELECTs to be coded */
96325   SelectDest *pDest     /* What to do with query results */
96326 ){
96327   int i, j;             /* Loop counters */
96328   Select *pPrior;       /* Another SELECT immediately to our left */
96329   Vdbe *v;              /* Generate code to this VDBE */
96330   SelectDest destA;     /* Destination for coroutine A */
96331   SelectDest destB;     /* Destination for coroutine B */
96332   int regAddrA;         /* Address register for select-A coroutine */
96333   int regEofA;          /* Flag to indicate when select-A is complete */
96334   int regAddrB;         /* Address register for select-B coroutine */
96335   int regEofB;          /* Flag to indicate when select-B is complete */
96336   int addrSelectA;      /* Address of the select-A coroutine */
96337   int addrSelectB;      /* Address of the select-B coroutine */
96338   int regOutA;          /* Address register for the output-A subroutine */
96339   int regOutB;          /* Address register for the output-B subroutine */
96340   int addrOutA;         /* Address of the output-A subroutine */
96341   int addrOutB = 0;     /* Address of the output-B subroutine */
96342   int addrEofA;         /* Address of the select-A-exhausted subroutine */
96343   int addrEofB;         /* Address of the select-B-exhausted subroutine */
96344   int addrAltB;         /* Address of the A<B subroutine */
96345   int addrAeqB;         /* Address of the A==B subroutine */
96346   int addrAgtB;         /* Address of the A>B subroutine */
96347   int regLimitA;        /* Limit register for select-A */
96348   int regLimitB;        /* Limit register for select-A */
96349   int regPrev;          /* A range of registers to hold previous output */
96350   int savedLimit;       /* Saved value of p->iLimit */
96351   int savedOffset;      /* Saved value of p->iOffset */
96352   int labelCmpr;        /* Label for the start of the merge algorithm */
96353   int labelEnd;         /* Label for the end of the overall SELECT stmt */
96354   int j1;               /* Jump instructions that get retargetted */
96355   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96356   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96357   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96358   sqlcipher3 *db;          /* Database connection */
96359   ExprList *pOrderBy;   /* The ORDER BY clause */
96360   int nOrderBy;         /* Number of terms in the ORDER BY clause */
96361   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96362 #ifndef SQLCIPHER_OMIT_EXPLAIN
96363   int iSub1;            /* EQP id of left-hand query */
96364   int iSub2;            /* EQP id of right-hand query */
96365 #endif
96366
96367   assert( p->pOrderBy!=0 );
96368   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96369   db = pParse->db;
96370   v = pParse->pVdbe;
96371   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
96372   labelEnd = sqlcipher3VdbeMakeLabel(v);
96373   labelCmpr = sqlcipher3VdbeMakeLabel(v);
96374
96375
96376   /* Patch up the ORDER BY clause
96377   */
96378   op = p->op;  
96379   pPrior = p->pPrior;
96380   assert( pPrior->pOrderBy==0 );
96381   pOrderBy = p->pOrderBy;
96382   assert( pOrderBy );
96383   nOrderBy = pOrderBy->nExpr;
96384
96385   /* For operators other than UNION ALL we have to make sure that
96386   ** the ORDER BY clause covers every term of the result set.  Add
96387   ** terms to the ORDER BY clause as necessary.
96388   */
96389   if( op!=TK_ALL ){
96390     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
96391       struct ExprList_item *pItem;
96392       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
96393         assert( pItem->iCol>0 );
96394         if( pItem->iCol==i ) break;
96395       }
96396       if( j==nOrderBy ){
96397         Expr *pNew = sqlcipher3Expr(db, TK_INTEGER, 0);
96398         if( pNew==0 ) return SQLCIPHER_NOMEM;
96399         pNew->flags |= EP_IntValue;
96400         pNew->u.iValue = i;
96401         pOrderBy = sqlcipher3ExprListAppend(pParse, pOrderBy, pNew);
96402         pOrderBy->a[nOrderBy++].iCol = (u16)i;
96403       }
96404     }
96405   }
96406
96407   /* Compute the comparison permutation and keyinfo that is used with
96408   ** the permutation used to determine if the next
96409   ** row of results comes from selectA or selectB.  Also add explicit
96410   ** collations to the ORDER BY clause terms so that when the subqueries
96411   ** to the right and the left are evaluated, they use the correct
96412   ** collation.
96413   */
96414   aPermute = sqlcipher3DbMallocRaw(db, sizeof(int)*nOrderBy);
96415   if( aPermute ){
96416     struct ExprList_item *pItem;
96417     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
96418       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
96419       aPermute[i] = pItem->iCol - 1;
96420     }
96421     pKeyMerge =
96422       sqlcipher3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
96423     if( pKeyMerge ){
96424       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
96425       pKeyMerge->nField = (u16)nOrderBy;
96426       pKeyMerge->enc = ENC(db);
96427       for(i=0; i<nOrderBy; i++){
96428         CollSeq *pColl;
96429         Expr *pTerm = pOrderBy->a[i].pExpr;
96430         if( pTerm->flags & EP_ExpCollate ){
96431           pColl = pTerm->pColl;
96432         }else{
96433           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
96434           pTerm->flags |= EP_ExpCollate;
96435           pTerm->pColl = pColl;
96436         }
96437         pKeyMerge->aColl[i] = pColl;
96438         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
96439       }
96440     }
96441   }else{
96442     pKeyMerge = 0;
96443   }
96444
96445   /* Reattach the ORDER BY clause to the query.
96446   */
96447   p->pOrderBy = pOrderBy;
96448   pPrior->pOrderBy = sqlcipher3ExprListDup(pParse->db, pOrderBy, 0);
96449
96450   /* Allocate a range of temporary registers and the KeyInfo needed
96451   ** for the logic that removes duplicate result rows when the
96452   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
96453   */
96454   if( op==TK_ALL ){
96455     regPrev = 0;
96456   }else{
96457     int nExpr = p->pEList->nExpr;
96458     assert( nOrderBy>=nExpr || db->mallocFailed );
96459     regPrev = sqlcipher3GetTempRange(pParse, nExpr+1);
96460     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regPrev);
96461     pKeyDup = sqlcipher3DbMallocZero(db,
96462                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
96463     if( pKeyDup ){
96464       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
96465       pKeyDup->nField = (u16)nExpr;
96466       pKeyDup->enc = ENC(db);
96467       for(i=0; i<nExpr; i++){
96468         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
96469         pKeyDup->aSortOrder[i] = 0;
96470       }
96471     }
96472   }
96473  
96474   /* Separate the left and the right query from one another
96475   */
96476   p->pPrior = 0;
96477   sqlcipher3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
96478   if( pPrior->pPrior==0 ){
96479     sqlcipher3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
96480   }
96481
96482   /* Compute the limit registers */
96483   computeLimitRegisters(pParse, p, labelEnd);
96484   if( p->iLimit && op==TK_ALL ){
96485     regLimitA = ++pParse->nMem;
96486     regLimitB = ++pParse->nMem;
96487     sqlcipher3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
96488                                   regLimitA);
96489     sqlcipher3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
96490   }else{
96491     regLimitA = regLimitB = 0;
96492   }
96493   sqlcipher3ExprDelete(db, p->pLimit);
96494   p->pLimit = 0;
96495   sqlcipher3ExprDelete(db, p->pOffset);
96496   p->pOffset = 0;
96497
96498   regAddrA = ++pParse->nMem;
96499   regEofA = ++pParse->nMem;
96500   regAddrB = ++pParse->nMem;
96501   regEofB = ++pParse->nMem;
96502   regOutA = ++pParse->nMem;
96503   regOutB = ++pParse->nMem;
96504   sqlcipher3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
96505   sqlcipher3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
96506
96507   /* Jump past the various subroutines and coroutines to the main
96508   ** merge loop
96509   */
96510   j1 = sqlcipher3VdbeAddOp0(v, OP_Goto);
96511   addrSelectA = sqlcipher3VdbeCurrentAddr(v);
96512
96513
96514   /* Generate a coroutine to evaluate the SELECT statement to the
96515   ** left of the compound operator - the "A" select.
96516   */
96517   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
96518   pPrior->iLimit = regLimitA;
96519   explainSetInteger(iSub1, pParse->iNextSelectId);
96520   sqlcipher3Select(pParse, pPrior, &destA);
96521   sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regEofA);
96522   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96523   VdbeNoopComment((v, "End coroutine for left SELECT"));
96524
96525   /* Generate a coroutine to evaluate the SELECT statement on 
96526   ** the right - the "B" select
96527   */
96528   addrSelectB = sqlcipher3VdbeCurrentAddr(v);
96529   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
96530   savedLimit = p->iLimit;
96531   savedOffset = p->iOffset;
96532   p->iLimit = regLimitB;
96533   p->iOffset = 0;  
96534   explainSetInteger(iSub2, pParse->iNextSelectId);
96535   sqlcipher3Select(pParse, p, &destB);
96536   p->iLimit = savedLimit;
96537   p->iOffset = savedOffset;
96538   sqlcipher3VdbeAddOp2(v, OP_Integer, 1, regEofB);
96539   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrB);
96540   VdbeNoopComment((v, "End coroutine for right SELECT"));
96541
96542   /* Generate a subroutine that outputs the current row of the A
96543   ** select as the next output row of the compound select.
96544   */
96545   VdbeNoopComment((v, "Output routine for A"));
96546   addrOutA = generateOutputSubroutine(pParse,
96547                  p, &destA, pDest, regOutA,
96548                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
96549   
96550   /* Generate a subroutine that outputs the current row of the B
96551   ** select as the next output row of the compound select.
96552   */
96553   if( op==TK_ALL || op==TK_UNION ){
96554     VdbeNoopComment((v, "Output routine for B"));
96555     addrOutB = generateOutputSubroutine(pParse,
96556                  p, &destB, pDest, regOutB,
96557                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
96558   }
96559
96560   /* Generate a subroutine to run when the results from select A
96561   ** are exhausted and only data in select B remains.
96562   */
96563   VdbeNoopComment((v, "eof-A subroutine"));
96564   if( op==TK_EXCEPT || op==TK_INTERSECT ){
96565     addrEofA = sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
96566   }else{  
96567     addrEofA = sqlcipher3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
96568     sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96569     sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrB);
96570     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
96571     p->nSelectRow += pPrior->nSelectRow;
96572   }
96573
96574   /* Generate a subroutine to run when the results from select B
96575   ** are exhausted and only data in select A remains.
96576   */
96577   if( op==TK_INTERSECT ){
96578     addrEofB = addrEofA;
96579     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96580   }else{  
96581     VdbeNoopComment((v, "eof-B subroutine"));
96582     addrEofB = sqlcipher3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
96583     sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96584     sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96585     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
96586   }
96587
96588   /* Generate code to handle the case of A<B
96589   */
96590   VdbeNoopComment((v, "A-lt-B subroutine"));
96591   addrAltB = sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96592   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96593   sqlcipher3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96594   sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96595
96596   /* Generate code to handle the case of A==B
96597   */
96598   if( op==TK_ALL ){
96599     addrAeqB = addrAltB;
96600   }else if( op==TK_INTERSECT ){
96601     addrAeqB = addrAltB;
96602     addrAltB++;
96603   }else{
96604     VdbeNoopComment((v, "A-eq-B subroutine"));
96605     addrAeqB =
96606     sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrA);
96607     sqlcipher3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96608     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96609   }
96610
96611   /* Generate code to handle the case of A>B
96612   */
96613   VdbeNoopComment((v, "A-gt-B subroutine"));
96614   addrAgtB = sqlcipher3VdbeCurrentAddr(v);
96615   if( op==TK_ALL || op==TK_UNION ){
96616     sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96617   }
96618   sqlcipher3VdbeAddOp1(v, OP_Yield, regAddrB);
96619   sqlcipher3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96620   sqlcipher3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96621
96622   /* This code runs once to initialize everything.
96623   */
96624   sqlcipher3VdbeJumpHere(v, j1);
96625   sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regEofA);
96626   sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regEofB);
96627   sqlcipher3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
96628   sqlcipher3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
96629   sqlcipher3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96630   sqlcipher3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96631
96632   /* Implement the main merge loop
96633   */
96634   sqlcipher3VdbeResolveLabel(v, labelCmpr);
96635   sqlcipher3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
96636   sqlcipher3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
96637                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
96638   sqlcipher3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
96639
96640   /* Release temporary registers
96641   */
96642   if( regPrev ){
96643     sqlcipher3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
96644   }
96645
96646   /* Jump to the this point in order to terminate the query.
96647   */
96648   sqlcipher3VdbeResolveLabel(v, labelEnd);
96649
96650   /* Set the number of output columns
96651   */
96652   if( pDest->eDest==SRT_Output ){
96653     Select *pFirst = pPrior;
96654     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96655     generateColumnNames(pParse, 0, pFirst->pEList);
96656   }
96657
96658   /* Reassembly the compound query so that it will be freed correctly
96659   ** by the calling function */
96660   if( p->pPrior ){
96661     sqlcipher3SelectDelete(db, p->pPrior);
96662   }
96663   p->pPrior = pPrior;
96664
96665   /*** TBD:  Insert subroutine calls to close cursors on incomplete
96666   **** subqueries ****/
96667   explainComposite(pParse, p->op, iSub1, iSub2, 0);
96668   return SQLCIPHER_OK;
96669 }
96670 #endif
96671
96672 #if !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW)
96673 /* Forward Declarations */
96674 static void substExprList(sqlcipher3*, ExprList*, int, ExprList*);
96675 static void substSelect(sqlcipher3*, Select *, int, ExprList *);
96676
96677 /*
96678 ** Scan through the expression pExpr.  Replace every reference to
96679 ** a column in table number iTable with a copy of the iColumn-th
96680 ** entry in pEList.  (But leave references to the ROWID column 
96681 ** unchanged.)
96682 **
96683 ** This routine is part of the flattening procedure.  A subquery
96684 ** whose result set is defined by pEList appears as entry in the
96685 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
96686 ** FORM clause entry is iTable.  This routine make the necessary 
96687 ** changes to pExpr so that it refers directly to the source table
96688 ** of the subquery rather the result set of the subquery.
96689 */
96690 static Expr *substExpr(
96691   sqlcipher3 *db,        /* Report malloc errors to this connection */
96692   Expr *pExpr,        /* Expr in which substitution occurs */
96693   int iTable,         /* Table to be substituted */
96694   ExprList *pEList    /* Substitute expressions */
96695 ){
96696   if( pExpr==0 ) return 0;
96697   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
96698     if( pExpr->iColumn<0 ){
96699       pExpr->op = TK_NULL;
96700     }else{
96701       Expr *pNew;
96702       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
96703       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
96704       pNew = sqlcipher3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
96705       if( pNew && pExpr->pColl ){
96706         pNew->pColl = pExpr->pColl;
96707       }
96708       sqlcipher3ExprDelete(db, pExpr);
96709       pExpr = pNew;
96710     }
96711   }else{
96712     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
96713     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
96714     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96715       substSelect(db, pExpr->x.pSelect, iTable, pEList);
96716     }else{
96717       substExprList(db, pExpr->x.pList, iTable, pEList);
96718     }
96719   }
96720   return pExpr;
96721 }
96722 static void substExprList(
96723   sqlcipher3 *db,         /* Report malloc errors here */
96724   ExprList *pList,     /* List to scan and in which to make substitutes */
96725   int iTable,          /* Table to be substituted */
96726   ExprList *pEList     /* Substitute values */
96727 ){
96728   int i;
96729   if( pList==0 ) return;
96730   for(i=0; i<pList->nExpr; i++){
96731     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
96732   }
96733 }
96734 static void substSelect(
96735   sqlcipher3 *db,         /* Report malloc errors here */
96736   Select *p,           /* SELECT statement in which to make substitutions */
96737   int iTable,          /* Table to be replaced */
96738   ExprList *pEList     /* Substitute values */
96739 ){
96740   SrcList *pSrc;
96741   struct SrcList_item *pItem;
96742   int i;
96743   if( !p ) return;
96744   substExprList(db, p->pEList, iTable, pEList);
96745   substExprList(db, p->pGroupBy, iTable, pEList);
96746   substExprList(db, p->pOrderBy, iTable, pEList);
96747   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
96748   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
96749   substSelect(db, p->pPrior, iTable, pEList);
96750   pSrc = p->pSrc;
96751   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
96752   if( ALWAYS(pSrc) ){
96753     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
96754       substSelect(db, pItem->pSelect, iTable, pEList);
96755     }
96756   }
96757 }
96758 #endif /* !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW) */
96759
96760 #if !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW)
96761 /*
96762 ** This routine attempts to flatten subqueries in order to speed
96763 ** execution.  It returns 1 if it makes changes and 0 if no flattening
96764 ** occurs.
96765 **
96766 ** To understand the concept of flattening, consider the following
96767 ** query:
96768 **
96769 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
96770 **
96771 ** The default way of implementing this query is to execute the
96772 ** subquery first and store the results in a temporary table, then
96773 ** run the outer query on that temporary table.  This requires two
96774 ** passes over the data.  Furthermore, because the temporary table
96775 ** has no indices, the WHERE clause on the outer query cannot be
96776 ** optimized.
96777 **
96778 ** This routine attempts to rewrite queries such as the above into
96779 ** a single flat select, like this:
96780 **
96781 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
96782 **
96783 ** The code generated for this simpification gives the same result
96784 ** but only has to scan the data once.  And because indices might 
96785 ** exist on the table t1, a complete scan of the data might be
96786 ** avoided.
96787 **
96788 ** Flattening is only attempted if all of the following are true:
96789 **
96790 **   (1)  The subquery and the outer query do not both use aggregates.
96791 **
96792 **   (2)  The subquery is not an aggregate or the outer query is not a join.
96793 **
96794 **   (3)  The subquery is not the right operand of a left outer join
96795 **        (Originally ticket #306.  Strengthened by ticket #3300)
96796 **
96797 **   (4)  The subquery is not DISTINCT.
96798 **
96799 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
96800 **        sub-queries that were excluded from this optimization. Restriction 
96801 **        (4) has since been expanded to exclude all DISTINCT subqueries.
96802 **
96803 **   (6)  The subquery does not use aggregates or the outer query is not
96804 **        DISTINCT.
96805 **
96806 **   (7)  The subquery has a FROM clause.
96807 **
96808 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
96809 **
96810 **   (9)  The subquery does not use LIMIT or the outer query does not use
96811 **        aggregates.
96812 **
96813 **  (10)  The subquery does not use aggregates or the outer query does not
96814 **        use LIMIT.
96815 **
96816 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
96817 **
96818 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
96819 **        a separate restriction deriving from ticket #350.
96820 **
96821 **  (13)  The subquery and outer query do not both use LIMIT.
96822 **
96823 **  (14)  The subquery does not use OFFSET.
96824 **
96825 **  (15)  The outer query is not part of a compound select or the
96826 **        subquery does not have a LIMIT clause.
96827 **        (See ticket #2339 and ticket [02a8e81d44]).
96828 **
96829 **  (16)  The outer query is not an aggregate or the subquery does
96830 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
96831 **        until we introduced the group_concat() function.  
96832 **
96833 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
96834 **        compound clause made up entirely of non-aggregate queries, and 
96835 **        the parent query:
96836 **
96837 **          * is not itself part of a compound select,
96838 **          * is not an aggregate or DISTINCT query, and
96839 **          * has no other tables or sub-selects in the FROM clause.
96840 **
96841 **        The parent and sub-query may contain WHERE clauses. Subject to
96842 **        rules (11), (13) and (14), they may also contain ORDER BY,
96843 **        LIMIT and OFFSET clauses.
96844 **
96845 **  (18)  If the sub-query is a compound select, then all terms of the
96846 **        ORDER by clause of the parent must be simple references to 
96847 **        columns of the sub-query.
96848 **
96849 **  (19)  The subquery does not use LIMIT or the outer query does not
96850 **        have a WHERE clause.
96851 **
96852 **  (20)  If the sub-query is a compound select, then it must not use
96853 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
96854 **        somewhat by saying that the terms of the ORDER BY clause must
96855 **        appear as unmodified result columns in the outer query.  But
96856 **        have other optimizations in mind to deal with that case.
96857 **
96858 **  (21)  The subquery does not use LIMIT or the outer query is not
96859 **        DISTINCT.  (See ticket [752e1646fc]).
96860 **
96861 ** In this routine, the "p" parameter is a pointer to the outer query.
96862 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
96863 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
96864 **
96865 ** If flattening is not attempted, this routine is a no-op and returns 0.
96866 ** If flattening is attempted this routine returns 1.
96867 **
96868 ** All of the expression analysis must occur on both the outer query and
96869 ** the subquery before this routine runs.
96870 */
96871 static int flattenSubquery(
96872   Parse *pParse,       /* Parsing context */
96873   Select *p,           /* The parent or outer SELECT statement */
96874   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
96875   int isAgg,           /* True if outer SELECT uses aggregate functions */
96876   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
96877 ){
96878   const char *zSavedAuthContext = pParse->zAuthContext;
96879   Select *pParent;
96880   Select *pSub;       /* The inner query or "subquery" */
96881   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
96882   SrcList *pSrc;      /* The FROM clause of the outer query */
96883   SrcList *pSubSrc;   /* The FROM clause of the subquery */
96884   ExprList *pList;    /* The result set of the outer query */
96885   int iParent;        /* VDBE cursor number of the pSub result set temp table */
96886   int i;              /* Loop counter */
96887   Expr *pWhere;                    /* The WHERE clause */
96888   struct SrcList_item *pSubitem;   /* The subquery */
96889   sqlcipher3 *db = pParse->db;
96890
96891   /* Check to see if flattening is permitted.  Return 0 if not.
96892   */
96893   assert( p!=0 );
96894   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
96895   if( db->flags & SQLCIPHER_QueryFlattener ) return 0;
96896   pSrc = p->pSrc;
96897   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
96898   pSubitem = &pSrc->a[iFrom];
96899   iParent = pSubitem->iCursor;
96900   pSub = pSubitem->pSelect;
96901   assert( pSub!=0 );
96902   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
96903   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
96904   pSubSrc = pSub->pSrc;
96905   assert( pSubSrc );
96906   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
96907   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
96908   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
96909   ** became arbitrary expressions, we were forced to add restrictions (13)
96910   ** and (14). */
96911   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
96912   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
96913   if( p->pRightmost && pSub->pLimit ){
96914     return 0;                                            /* Restriction (15) */
96915   }
96916   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
96917   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
96918   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
96919      return 0;         /* Restrictions (8)(9) */
96920   }
96921   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
96922      return 0;         /* Restriction (6)  */
96923   }
96924   if( p->pOrderBy && pSub->pOrderBy ){
96925      return 0;                                           /* Restriction (11) */
96926   }
96927   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
96928   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
96929   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
96930      return 0;         /* Restriction (21) */
96931   }
96932
96933   /* OBSOLETE COMMENT 1:
96934   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
96935   ** not used as the right operand of an outer join.  Examples of why this
96936   ** is not allowed:
96937   **
96938   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
96939   **
96940   ** If we flatten the above, we would get
96941   **
96942   **         (t1 LEFT OUTER JOIN t2) JOIN t3
96943   **
96944   ** which is not at all the same thing.
96945   **
96946   ** OBSOLETE COMMENT 2:
96947   ** Restriction 12:  If the subquery is the right operand of a left outer
96948   ** join, make sure the subquery has no WHERE clause.
96949   ** An examples of why this is not allowed:
96950   **
96951   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
96952   **
96953   ** If we flatten the above, we would get
96954   **
96955   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
96956   **
96957   ** But the t2.x>0 test will always fail on a NULL row of t2, which
96958   ** effectively converts the OUTER JOIN into an INNER JOIN.
96959   **
96960   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
96961   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
96962   ** is fraught with danger.  Best to avoid the whole thing.  If the
96963   ** subquery is the right term of a LEFT JOIN, then do not flatten.
96964   */
96965   if( (pSubitem->jointype & JT_OUTER)!=0 ){
96966     return 0;
96967   }
96968
96969   /* Restriction 17: If the sub-query is a compound SELECT, then it must
96970   ** use only the UNION ALL operator. And none of the simple select queries
96971   ** that make up the compound SELECT are allowed to be aggregate or distinct
96972   ** queries.
96973   */
96974   if( pSub->pPrior ){
96975     if( pSub->pOrderBy ){
96976       return 0;  /* Restriction 20 */
96977     }
96978     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
96979       return 0;
96980     }
96981     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
96982       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
96983       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
96984       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
96985        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
96986        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
96987       ){
96988         return 0;
96989       }
96990     }
96991
96992     /* Restriction 18. */
96993     if( p->pOrderBy ){
96994       int ii;
96995       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
96996         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
96997       }
96998     }
96999   }
97000
97001   /***** If we reach this point, flattening is permitted. *****/
97002
97003   /* Authorize the subquery */
97004   pParse->zAuthContext = pSubitem->zName;
97005   sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0);
97006   pParse->zAuthContext = zSavedAuthContext;
97007
97008   /* If the sub-query is a compound SELECT statement, then (by restrictions
97009   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
97010   ** be of the form:
97011   **
97012   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
97013   **
97014   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
97015   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
97016   ** OFFSET clauses and joins them to the left-hand-side of the original
97017   ** using UNION ALL operators. In this case N is the number of simple
97018   ** select statements in the compound sub-query.
97019   **
97020   ** Example:
97021   **
97022   **     SELECT a+1 FROM (
97023   **        SELECT x FROM tab
97024   **        UNION ALL
97025   **        SELECT y FROM tab
97026   **        UNION ALL
97027   **        SELECT abs(z*2) FROM tab2
97028   **     ) WHERE a!=5 ORDER BY 1
97029   **
97030   ** Transformed into:
97031   **
97032   **     SELECT x+1 FROM tab WHERE x+1!=5
97033   **     UNION ALL
97034   **     SELECT y+1 FROM tab WHERE y+1!=5
97035   **     UNION ALL
97036   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97037   **     ORDER BY 1
97038   **
97039   ** We call this the "compound-subquery flattening".
97040   */
97041   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97042     Select *pNew;
97043     ExprList *pOrderBy = p->pOrderBy;
97044     Expr *pLimit = p->pLimit;
97045     Select *pPrior = p->pPrior;
97046     p->pOrderBy = 0;
97047     p->pSrc = 0;
97048     p->pPrior = 0;
97049     p->pLimit = 0;
97050     pNew = sqlcipher3SelectDup(db, p, 0);
97051     p->pLimit = pLimit;
97052     p->pOrderBy = pOrderBy;
97053     p->pSrc = pSrc;
97054     p->op = TK_ALL;
97055     p->pRightmost = 0;
97056     if( pNew==0 ){
97057       pNew = pPrior;
97058     }else{
97059       pNew->pPrior = pPrior;
97060       pNew->pRightmost = 0;
97061     }
97062     p->pPrior = pNew;
97063     if( db->mallocFailed ) return 1;
97064   }
97065
97066   /* Begin flattening the iFrom-th entry of the FROM clause 
97067   ** in the outer query.
97068   */
97069   pSub = pSub1 = pSubitem->pSelect;
97070
97071   /* Delete the transient table structure associated with the
97072   ** subquery
97073   */
97074   sqlcipher3DbFree(db, pSubitem->zDatabase);
97075   sqlcipher3DbFree(db, pSubitem->zName);
97076   sqlcipher3DbFree(db, pSubitem->zAlias);
97077   pSubitem->zDatabase = 0;
97078   pSubitem->zName = 0;
97079   pSubitem->zAlias = 0;
97080   pSubitem->pSelect = 0;
97081
97082   /* Defer deleting the Table object associated with the
97083   ** subquery until code generation is
97084   ** complete, since there may still exist Expr.pTab entries that
97085   ** refer to the subquery even after flattening.  Ticket #3346.
97086   **
97087   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97088   */
97089   if( ALWAYS(pSubitem->pTab!=0) ){
97090     Table *pTabToDel = pSubitem->pTab;
97091     if( pTabToDel->nRef==1 ){
97092       Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
97093       pTabToDel->pNextZombie = pToplevel->pZombieTab;
97094       pToplevel->pZombieTab = pTabToDel;
97095     }else{
97096       pTabToDel->nRef--;
97097     }
97098     pSubitem->pTab = 0;
97099   }
97100
97101   /* The following loop runs once for each term in a compound-subquery
97102   ** flattening (as described above).  If we are doing a different kind
97103   ** of flattening - a flattening other than a compound-subquery flattening -
97104   ** then this loop only runs once.
97105   **
97106   ** This loop moves all of the FROM elements of the subquery into the
97107   ** the FROM clause of the outer query.  Before doing this, remember
97108   ** the cursor number for the original outer query FROM element in
97109   ** iParent.  The iParent cursor will never be used.  Subsequent code
97110   ** will scan expressions looking for iParent references and replace
97111   ** those references with expressions that resolve to the subquery FROM
97112   ** elements we are now copying in.
97113   */
97114   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97115     int nSubSrc;
97116     u8 jointype = 0;
97117     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97118     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97119     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97120
97121     if( pSrc ){
97122       assert( pParent==p );  /* First time through the loop */
97123       jointype = pSubitem->jointype;
97124     }else{
97125       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97126       pSrc = pParent->pSrc = sqlcipher3SrcListAppend(db, 0, 0, 0);
97127       if( pSrc==0 ){
97128         assert( db->mallocFailed );
97129         break;
97130       }
97131     }
97132
97133     /* The subquery uses a single slot of the FROM clause of the outer
97134     ** query.  If the subquery has more than one element in its FROM clause,
97135     ** then expand the outer query to make space for it to hold all elements
97136     ** of the subquery.
97137     **
97138     ** Example:
97139     **
97140     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97141     **
97142     ** The outer query has 3 slots in its FROM clause.  One slot of the
97143     ** outer query (the middle slot) is used by the subquery.  The next
97144     ** block of code will expand the out query to 4 slots.  The middle
97145     ** slot is expanded to two slots in order to make space for the
97146     ** two elements in the FROM clause of the subquery.
97147     */
97148     if( nSubSrc>1 ){
97149       pParent->pSrc = pSrc = sqlcipher3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97150       if( db->mallocFailed ){
97151         break;
97152       }
97153     }
97154
97155     /* Transfer the FROM clause terms from the subquery into the
97156     ** outer query.
97157     */
97158     for(i=0; i<nSubSrc; i++){
97159       sqlcipher3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97160       pSrc->a[i+iFrom] = pSubSrc->a[i];
97161       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97162     }
97163     pSrc->a[iFrom].jointype = jointype;
97164   
97165     /* Now begin substituting subquery result set expressions for 
97166     ** references to the iParent in the outer query.
97167     ** 
97168     ** Example:
97169     **
97170     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97171     **   \                     \_____________ subquery __________/          /
97172     **    \_____________________ outer query ______________________________/
97173     **
97174     ** We look at every expression in the outer query and every place we see
97175     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97176     */
97177     pList = pParent->pEList;
97178     for(i=0; i<pList->nExpr; i++){
97179       if( pList->a[i].zName==0 ){
97180         const char *zSpan = pList->a[i].zSpan;
97181         if( ALWAYS(zSpan) ){
97182           pList->a[i].zName = sqlcipher3DbStrDup(db, zSpan);
97183         }
97184       }
97185     }
97186     substExprList(db, pParent->pEList, iParent, pSub->pEList);
97187     if( isAgg ){
97188       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97189       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97190     }
97191     if( pSub->pOrderBy ){
97192       assert( pParent->pOrderBy==0 );
97193       pParent->pOrderBy = pSub->pOrderBy;
97194       pSub->pOrderBy = 0;
97195     }else if( pParent->pOrderBy ){
97196       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97197     }
97198     if( pSub->pWhere ){
97199       pWhere = sqlcipher3ExprDup(db, pSub->pWhere, 0);
97200     }else{
97201       pWhere = 0;
97202     }
97203     if( subqueryIsAgg ){
97204       assert( pParent->pHaving==0 );
97205       pParent->pHaving = pParent->pWhere;
97206       pParent->pWhere = pWhere;
97207       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97208       pParent->pHaving = sqlcipher3ExprAnd(db, pParent->pHaving, 
97209                                   sqlcipher3ExprDup(db, pSub->pHaving, 0));
97210       assert( pParent->pGroupBy==0 );
97211       pParent->pGroupBy = sqlcipher3ExprListDup(db, pSub->pGroupBy, 0);
97212     }else{
97213       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97214       pParent->pWhere = sqlcipher3ExprAnd(db, pParent->pWhere, pWhere);
97215     }
97216   
97217     /* The flattened query is distinct if either the inner or the
97218     ** outer query is distinct. 
97219     */
97220     pParent->selFlags |= pSub->selFlags & SF_Distinct;
97221   
97222     /*
97223     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97224     **
97225     ** One is tempted to try to add a and b to combine the limits.  But this
97226     ** does not work if either limit is negative.
97227     */
97228     if( pSub->pLimit ){
97229       pParent->pLimit = pSub->pLimit;
97230       pSub->pLimit = 0;
97231     }
97232   }
97233
97234   /* Finially, delete what is left of the subquery and return
97235   ** success.
97236   */
97237   sqlcipher3SelectDelete(db, pSub1);
97238
97239   return 1;
97240 }
97241 #endif /* !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW) */
97242
97243 /*
97244 ** Analyze the SELECT statement passed as an argument to see if it
97245 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
97246 ** it is, or 0 otherwise. At present, a query is considered to be
97247 ** a min()/max() query if:
97248 **
97249 **   1. There is a single object in the FROM clause.
97250 **
97251 **   2. There is a single expression in the result set, and it is
97252 **      either min(x) or max(x), where x is a column reference.
97253 */
97254 static u8 minMaxQuery(Select *p){
97255   Expr *pExpr;
97256   ExprList *pEList = p->pEList;
97257
97258   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
97259   pExpr = pEList->a[0].pExpr;
97260   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97261   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
97262   pEList = pExpr->x.pList;
97263   if( pEList==0 || pEList->nExpr!=1 ) return 0;
97264   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
97265   assert( !ExprHasProperty(pExpr, EP_IntValue) );
97266   if( sqlcipher3StrICmp(pExpr->u.zToken,"min")==0 ){
97267     return WHERE_ORDERBY_MIN;
97268   }else if( sqlcipher3StrICmp(pExpr->u.zToken,"max")==0 ){
97269     return WHERE_ORDERBY_MAX;
97270   }
97271   return WHERE_ORDERBY_NORMAL;
97272 }
97273
97274 /*
97275 ** The select statement passed as the first argument is an aggregate query.
97276 ** The second argment is the associated aggregate-info object. This 
97277 ** function tests if the SELECT is of the form:
97278 **
97279 **   SELECT count(*) FROM <tbl>
97280 **
97281 ** where table is a database table, not a sub-select or view. If the query
97282 ** does match this pattern, then a pointer to the Table object representing
97283 ** <tbl> is returned. Otherwise, 0 is returned.
97284 */
97285 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97286   Table *pTab;
97287   Expr *pExpr;
97288
97289   assert( !p->pGroupBy );
97290
97291   if( p->pWhere || p->pEList->nExpr!=1 
97292    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97293   ){
97294     return 0;
97295   }
97296   pTab = p->pSrc->a[0].pTab;
97297   pExpr = p->pEList->a[0].pExpr;
97298   assert( pTab && !pTab->pSelect && pExpr );
97299
97300   if( IsVirtual(pTab) ) return 0;
97301   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97302   if( (pAggInfo->aFunc[0].pFunc->flags&SQLCIPHER_FUNC_COUNT)==0 ) return 0;
97303   if( pExpr->flags&EP_Distinct ) return 0;
97304
97305   return pTab;
97306 }
97307
97308 /*
97309 ** If the source-list item passed as an argument was augmented with an
97310 ** INDEXED BY clause, then try to locate the specified index. If there
97311 ** was such a clause and the named index cannot be found, return 
97312 ** SQLCIPHER_ERROR and leave an error in pParse. Otherwise, populate 
97313 ** pFrom->pIndex and return SQLCIPHER_OK.
97314 */
97315 SQLCIPHER_PRIVATE int sqlcipher3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97316   if( pFrom->pTab && pFrom->zIndex ){
97317     Table *pTab = pFrom->pTab;
97318     char *zIndex = pFrom->zIndex;
97319     Index *pIdx;
97320     for(pIdx=pTab->pIndex; 
97321         pIdx && sqlcipher3StrICmp(pIdx->zName, zIndex); 
97322         pIdx=pIdx->pNext
97323     );
97324     if( !pIdx ){
97325       sqlcipher3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97326       pParse->checkSchema = 1;
97327       return SQLCIPHER_ERROR;
97328     }
97329     pFrom->pIndex = pIdx;
97330   }
97331   return SQLCIPHER_OK;
97332 }
97333
97334 /*
97335 ** This routine is a Walker callback for "expanding" a SELECT statement.
97336 ** "Expanding" means to do the following:
97337 **
97338 **    (1)  Make sure VDBE cursor numbers have been assigned to every
97339 **         element of the FROM clause.
97340 **
97341 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
97342 **         defines FROM clause.  When views appear in the FROM clause,
97343 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
97344 **         that implements the view.  A copy is made of the view's SELECT
97345 **         statement so that we can freely modify or delete that statement
97346 **         without worrying about messing up the presistent representation
97347 **         of the view.
97348 **
97349 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
97350 **         on joins and the ON and USING clause of joins.
97351 **
97352 **    (4)  Scan the list of columns in the result set (pEList) looking
97353 **         for instances of the "*" operator or the TABLE.* operator.
97354 **         If found, expand each "*" to be every column in every table
97355 **         and TABLE.* to be every column in TABLE.
97356 **
97357 */
97358 static int selectExpander(Walker *pWalker, Select *p){
97359   Parse *pParse = pWalker->pParse;
97360   int i, j, k;
97361   SrcList *pTabList;
97362   ExprList *pEList;
97363   struct SrcList_item *pFrom;
97364   sqlcipher3 *db = pParse->db;
97365
97366   if( db->mallocFailed  ){
97367     return WRC_Abort;
97368   }
97369   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
97370     return WRC_Prune;
97371   }
97372   p->selFlags |= SF_Expanded;
97373   pTabList = p->pSrc;
97374   pEList = p->pEList;
97375
97376   /* Make sure cursor numbers have been assigned to all entries in
97377   ** the FROM clause of the SELECT statement.
97378   */
97379   sqlcipher3SrcListAssignCursors(pParse, pTabList);
97380
97381   /* Look up every table named in the FROM clause of the select.  If
97382   ** an entry of the FROM clause is a subquery instead of a table or view,
97383   ** then create a transient table structure to describe the subquery.
97384   */
97385   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97386     Table *pTab;
97387     if( pFrom->pTab!=0 ){
97388       /* This statement has already been prepared.  There is no need
97389       ** to go further. */
97390       assert( i==0 );
97391       return WRC_Prune;
97392     }
97393     if( pFrom->zName==0 ){
97394 #ifndef SQLCIPHER_OMIT_SUBQUERY
97395       Select *pSel = pFrom->pSelect;
97396       /* A sub-query in the FROM clause of a SELECT */
97397       assert( pSel!=0 );
97398       assert( pFrom->pTab==0 );
97399       sqlcipher3WalkSelect(pWalker, pSel);
97400       pFrom->pTab = pTab = sqlcipher3DbMallocZero(db, sizeof(Table));
97401       if( pTab==0 ) return WRC_Abort;
97402       pTab->nRef = 1;
97403       pTab->zName = sqlcipher3MPrintf(db, "sqlcipher_subquery_%p_", (void*)pTab);
97404       while( pSel->pPrior ){ pSel = pSel->pPrior; }
97405       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
97406       pTab->iPKey = -1;
97407       pTab->nRowEst = 1000000;
97408       pTab->tabFlags |= TF_Ephemeral;
97409 #endif
97410     }else{
97411       /* An ordinary table or view name in the FROM clause */
97412       assert( pFrom->pTab==0 );
97413       pFrom->pTab = pTab = 
97414         sqlcipher3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
97415       if( pTab==0 ) return WRC_Abort;
97416       pTab->nRef++;
97417 #if !defined(SQLCIPHER_OMIT_VIEW) || !defined (SQLCIPHER_OMIT_VIRTUALTABLE)
97418       if( pTab->pSelect || IsVirtual(pTab) ){
97419         /* We reach here if the named table is a really a view */
97420         if( sqlcipher3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
97421         assert( pFrom->pSelect==0 );
97422         pFrom->pSelect = sqlcipher3SelectDup(db, pTab->pSelect, 0);
97423         sqlcipher3WalkSelect(pWalker, pFrom->pSelect);
97424       }
97425 #endif
97426     }
97427
97428     /* Locate the index named by the INDEXED BY clause, if any. */
97429     if( sqlcipher3IndexedByLookup(pParse, pFrom) ){
97430       return WRC_Abort;
97431     }
97432   }
97433
97434   /* Process NATURAL keywords, and ON and USING clauses of joins.
97435   */
97436   if( db->mallocFailed || sqlcipherProcessJoin(pParse, p) ){
97437     return WRC_Abort;
97438   }
97439
97440   /* For every "*" that occurs in the column list, insert the names of
97441   ** all columns in all tables.  And for every TABLE.* insert the names
97442   ** of all columns in TABLE.  The parser inserted a special expression
97443   ** with the TK_ALL operator for each "*" that it found in the column list.
97444   ** The following code just has to locate the TK_ALL expressions and expand
97445   ** each one to the list of all columns in all tables.
97446   **
97447   ** The first loop just checks to see if there are any "*" operators
97448   ** that need expanding.
97449   */
97450   for(k=0; k<pEList->nExpr; k++){
97451     Expr *pE = pEList->a[k].pExpr;
97452     if( pE->op==TK_ALL ) break;
97453     assert( pE->op!=TK_DOT || pE->pRight!=0 );
97454     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
97455     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
97456   }
97457   if( k<pEList->nExpr ){
97458     /*
97459     ** If we get here it means the result set contains one or more "*"
97460     ** operators that need to be expanded.  Loop through each expression
97461     ** in the result set and expand them one by one.
97462     */
97463     struct ExprList_item *a = pEList->a;
97464     ExprList *pNew = 0;
97465     int flags = pParse->db->flags;
97466     int longNames = (flags & SQLCIPHER_FullColNames)!=0
97467                       && (flags & SQLCIPHER_ShortColNames)==0;
97468
97469     for(k=0; k<pEList->nExpr; k++){
97470       Expr *pE = a[k].pExpr;
97471       assert( pE->op!=TK_DOT || pE->pRight!=0 );
97472       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
97473         /* This particular expression does not need to be expanded.
97474         */
97475         pNew = sqlcipher3ExprListAppend(pParse, pNew, a[k].pExpr);
97476         if( pNew ){
97477           pNew->a[pNew->nExpr-1].zName = a[k].zName;
97478           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
97479           a[k].zName = 0;
97480           a[k].zSpan = 0;
97481         }
97482         a[k].pExpr = 0;
97483       }else{
97484         /* This expression is a "*" or a "TABLE.*" and needs to be
97485         ** expanded. */
97486         int tableSeen = 0;      /* Set to 1 when TABLE matches */
97487         char *zTName;            /* text of name of TABLE */
97488         if( pE->op==TK_DOT ){
97489           assert( pE->pLeft!=0 );
97490           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
97491           zTName = pE->pLeft->u.zToken;
97492         }else{
97493           zTName = 0;
97494         }
97495         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97496           Table *pTab = pFrom->pTab;
97497           char *zTabName = pFrom->zAlias;
97498           if( zTabName==0 ){
97499             zTabName = pTab->zName;
97500           }
97501           if( db->mallocFailed ) break;
97502           if( zTName && sqlcipher3StrICmp(zTName, zTabName)!=0 ){
97503             continue;
97504           }
97505           tableSeen = 1;
97506           for(j=0; j<pTab->nCol; j++){
97507             Expr *pExpr, *pRight;
97508             char *zName = pTab->aCol[j].zName;
97509             char *zColname;  /* The computed column name */
97510             char *zToFree;   /* Malloced string that needs to be freed */
97511             Token sColname;  /* Computed column name as a token */
97512
97513             /* If a column is marked as 'hidden' (currently only possible
97514             ** for virtual tables), do not include it in the expanded
97515             ** result-set list.
97516             */
97517             if( IsHiddenColumn(&pTab->aCol[j]) ){
97518               assert(IsVirtual(pTab));
97519               continue;
97520             }
97521
97522             if( i>0 && zTName==0 ){
97523               if( (pFrom->jointype & JT_NATURAL)!=0
97524                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
97525               ){
97526                 /* In a NATURAL join, omit the join columns from the 
97527                 ** table to the right of the join */
97528                 continue;
97529               }
97530               if( sqlcipher3IdListIndex(pFrom->pUsing, zName)>=0 ){
97531                 /* In a join with a USING clause, omit columns in the
97532                 ** using clause from the table on the right. */
97533                 continue;
97534               }
97535             }
97536             pRight = sqlcipher3Expr(db, TK_ID, zName);
97537             zColname = zName;
97538             zToFree = 0;
97539             if( longNames || pTabList->nSrc>1 ){
97540               Expr *pLeft;
97541               pLeft = sqlcipher3Expr(db, TK_ID, zTabName);
97542               pExpr = sqlcipher3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
97543               if( longNames ){
97544                 zColname = sqlcipher3MPrintf(db, "%s.%s", zTabName, zName);
97545                 zToFree = zColname;
97546               }
97547             }else{
97548               pExpr = pRight;
97549             }
97550             pNew = sqlcipher3ExprListAppend(pParse, pNew, pExpr);
97551             sColname.z = zColname;
97552             sColname.n = sqlcipher3Strlen30(zColname);
97553             sqlcipher3ExprListSetName(pParse, pNew, &sColname, 0);
97554             sqlcipher3DbFree(db, zToFree);
97555           }
97556         }
97557         if( !tableSeen ){
97558           if( zTName ){
97559             sqlcipher3ErrorMsg(pParse, "no such table: %s", zTName);
97560           }else{
97561             sqlcipher3ErrorMsg(pParse, "no tables specified");
97562           }
97563         }
97564       }
97565     }
97566     sqlcipher3ExprListDelete(db, pEList);
97567     p->pEList = pNew;
97568   }
97569 #if SQLCIPHER_MAX_COLUMN
97570   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLCIPHER_LIMIT_COLUMN] ){
97571     sqlcipher3ErrorMsg(pParse, "too many columns in result set");
97572   }
97573 #endif
97574   return WRC_Continue;
97575 }
97576
97577 /*
97578 ** No-op routine for the parse-tree walker.
97579 **
97580 ** When this routine is the Walker.xExprCallback then expression trees
97581 ** are walked without any actions being taken at each node.  Presumably,
97582 ** when this routine is used for Walker.xExprCallback then 
97583 ** Walker.xSelectCallback is set to do something useful for every 
97584 ** subquery in the parser tree.
97585 */
97586 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
97587   UNUSED_PARAMETER2(NotUsed, NotUsed2);
97588   return WRC_Continue;
97589 }
97590
97591 /*
97592 ** This routine "expands" a SELECT statement and all of its subqueries.
97593 ** For additional information on what it means to "expand" a SELECT
97594 ** statement, see the comment on the selectExpand worker callback above.
97595 **
97596 ** Expanding a SELECT statement is the first step in processing a
97597 ** SELECT statement.  The SELECT statement must be expanded before
97598 ** name resolution is performed.
97599 **
97600 ** If anything goes wrong, an error message is written into pParse.
97601 ** The calling function can detect the problem by looking at pParse->nErr
97602 ** and/or pParse->db->mallocFailed.
97603 */
97604 static void sqlcipher3SelectExpand(Parse *pParse, Select *pSelect){
97605   Walker w;
97606   w.xSelectCallback = selectExpander;
97607   w.xExprCallback = exprWalkNoop;
97608   w.pParse = pParse;
97609   sqlcipher3WalkSelect(&w, pSelect);
97610 }
97611
97612
97613 #ifndef SQLCIPHER_OMIT_SUBQUERY
97614 /*
97615 ** This is a Walker.xSelectCallback callback for the sqlcipher3SelectTypeInfo()
97616 ** interface.
97617 **
97618 ** For each FROM-clause subquery, add Column.zType and Column.zColl
97619 ** information to the Table structure that represents the result set
97620 ** of that subquery.
97621 **
97622 ** The Table structure that represents the result set was constructed
97623 ** by selectExpander() but the type and collation information was omitted
97624 ** at that point because identifiers had not yet been resolved.  This
97625 ** routine is called after identifier resolution.
97626 */
97627 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
97628   Parse *pParse;
97629   int i;
97630   SrcList *pTabList;
97631   struct SrcList_item *pFrom;
97632
97633   assert( p->selFlags & SF_Resolved );
97634   if( (p->selFlags & SF_HasTypeInfo)==0 ){
97635     p->selFlags |= SF_HasTypeInfo;
97636     pParse = pWalker->pParse;
97637     pTabList = p->pSrc;
97638     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97639       Table *pTab = pFrom->pTab;
97640       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
97641         /* A sub-query in the FROM clause of a SELECT */
97642         Select *pSel = pFrom->pSelect;
97643         assert( pSel );
97644         while( pSel->pPrior ) pSel = pSel->pPrior;
97645         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
97646       }
97647     }
97648   }
97649   return WRC_Continue;
97650 }
97651 #endif
97652
97653
97654 /*
97655 ** This routine adds datatype and collating sequence information to
97656 ** the Table structures of all FROM-clause subqueries in a
97657 ** SELECT statement.
97658 **
97659 ** Use this routine after name resolution.
97660 */
97661 static void sqlcipher3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
97662 #ifndef SQLCIPHER_OMIT_SUBQUERY
97663   Walker w;
97664   w.xSelectCallback = selectAddSubqueryTypeInfo;
97665   w.xExprCallback = exprWalkNoop;
97666   w.pParse = pParse;
97667   sqlcipher3WalkSelect(&w, pSelect);
97668 #endif
97669 }
97670
97671
97672 /*
97673 ** This routine sets of a SELECT statement for processing.  The
97674 ** following is accomplished:
97675 **
97676 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
97677 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
97678 **     *  ON and USING clauses are shifted into WHERE statements
97679 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
97680 **     *  Identifiers in expression are matched to tables.
97681 **
97682 ** This routine acts recursively on all subqueries within the SELECT.
97683 */
97684 SQLCIPHER_PRIVATE void sqlcipher3SelectPrep(
97685   Parse *pParse,         /* The parser context */
97686   Select *p,             /* The SELECT statement being coded. */
97687   NameContext *pOuterNC  /* Name context for container */
97688 ){
97689   sqlcipher3 *db;
97690   if( NEVER(p==0) ) return;
97691   db = pParse->db;
97692   if( p->selFlags & SF_HasTypeInfo ) return;
97693   sqlcipher3SelectExpand(pParse, p);
97694   if( pParse->nErr || db->mallocFailed ) return;
97695   sqlcipher3ResolveSelectNames(pParse, p, pOuterNC);
97696   if( pParse->nErr || db->mallocFailed ) return;
97697   sqlcipher3SelectAddTypeInfo(pParse, p);
97698 }
97699
97700 /*
97701 ** Reset the aggregate accumulator.
97702 **
97703 ** The aggregate accumulator is a set of memory cells that hold
97704 ** intermediate results while calculating an aggregate.  This
97705 ** routine simply stores NULLs in all of those memory cells.
97706 */
97707 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
97708   Vdbe *v = pParse->pVdbe;
97709   int i;
97710   struct AggInfo_func *pFunc;
97711   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
97712     return;
97713   }
97714   for(i=0; i<pAggInfo->nColumn; i++){
97715     sqlcipher3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
97716   }
97717   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
97718     sqlcipher3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
97719     if( pFunc->iDistinct>=0 ){
97720       Expr *pE = pFunc->pExpr;
97721       assert( !ExprHasProperty(pE, EP_xIsSelect) );
97722       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
97723         sqlcipher3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
97724            "argument");
97725         pFunc->iDistinct = -1;
97726       }else{
97727         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
97728         sqlcipher3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
97729                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97730       }
97731     }
97732   }
97733 }
97734
97735 /*
97736 ** Invoke the OP_AggFinalize opcode for every aggregate function
97737 ** in the AggInfo structure.
97738 */
97739 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
97740   Vdbe *v = pParse->pVdbe;
97741   int i;
97742   struct AggInfo_func *pF;
97743   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97744     ExprList *pList = pF->pExpr->x.pList;
97745     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97746     sqlcipher3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
97747                       (void*)pF->pFunc, P4_FUNCDEF);
97748   }
97749 }
97750
97751 /*
97752 ** Update the accumulator memory cells for an aggregate based on
97753 ** the current cursor position.
97754 */
97755 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
97756   Vdbe *v = pParse->pVdbe;
97757   int i;
97758   struct AggInfo_func *pF;
97759   struct AggInfo_col *pC;
97760
97761   pAggInfo->directMode = 1;
97762   sqlcipher3ExprCacheClear(pParse);
97763   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97764     int nArg;
97765     int addrNext = 0;
97766     int regAgg;
97767     ExprList *pList = pF->pExpr->x.pList;
97768     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97769     if( pList ){
97770       nArg = pList->nExpr;
97771       regAgg = sqlcipher3GetTempRange(pParse, nArg);
97772       sqlcipher3ExprCodeExprList(pParse, pList, regAgg, 1);
97773     }else{
97774       nArg = 0;
97775       regAgg = 0;
97776     }
97777     if( pF->iDistinct>=0 ){
97778       addrNext = sqlcipher3VdbeMakeLabel(v);
97779       assert( nArg==1 );
97780       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
97781     }
97782     if( pF->pFunc->flags & SQLCIPHER_FUNC_NEEDCOLL ){
97783       CollSeq *pColl = 0;
97784       struct ExprList_item *pItem;
97785       int j;
97786       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
97787       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
97788         pColl = sqlcipher3ExprCollSeq(pParse, pItem->pExpr);
97789       }
97790       if( !pColl ){
97791         pColl = pParse->db->pDfltColl;
97792       }
97793       sqlcipher3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
97794     }
97795     sqlcipher3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
97796                       (void*)pF->pFunc, P4_FUNCDEF);
97797     sqlcipher3VdbeChangeP5(v, (u8)nArg);
97798     sqlcipher3ExprCacheAffinityChange(pParse, regAgg, nArg);
97799     sqlcipher3ReleaseTempRange(pParse, regAgg, nArg);
97800     if( addrNext ){
97801       sqlcipher3VdbeResolveLabel(v, addrNext);
97802       sqlcipher3ExprCacheClear(pParse);
97803     }
97804   }
97805
97806   /* Before populating the accumulator registers, clear the column cache.
97807   ** Otherwise, if any of the required column values are already present 
97808   ** in registers, sqlcipher3ExprCode() may use OP_SCopy to copy the value
97809   ** to pC->iMem. But by the time the value is used, the original register
97810   ** may have been used, invalidating the underlying buffer holding the
97811   ** text or blob value. See ticket [883034dcb5].
97812   **
97813   ** Another solution would be to change the OP_SCopy used to copy cached
97814   ** values to an OP_Copy.
97815   */
97816   sqlcipher3ExprCacheClear(pParse);
97817   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
97818     sqlcipher3ExprCode(pParse, pC->pExpr, pC->iMem);
97819   }
97820   pAggInfo->directMode = 0;
97821   sqlcipher3ExprCacheClear(pParse);
97822 }
97823
97824 /*
97825 ** Add a single OP_Explain instruction to the VDBE to explain a simple
97826 ** count(*) query ("SELECT count(*) FROM pTab").
97827 */
97828 #ifndef SQLCIPHER_OMIT_EXPLAIN
97829 static void explainSimpleCount(
97830   Parse *pParse,                  /* Parse context */
97831   Table *pTab,                    /* Table being queried */
97832   Index *pIdx                     /* Index used to optimize scan, or NULL */
97833 ){
97834   if( pParse->explain==2 ){
97835     char *zEqp = sqlcipher3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
97836         pTab->zName, 
97837         pIdx ? "USING COVERING INDEX " : "",
97838         pIdx ? pIdx->zName : "",
97839         pTab->nRowEst
97840     );
97841     sqlcipher3VdbeAddOp4(
97842         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
97843     );
97844   }
97845 }
97846 #else
97847 # define explainSimpleCount(a,b,c)
97848 #endif
97849
97850 /*
97851 ** Generate code for the SELECT statement given in the p argument.  
97852 **
97853 ** The results are distributed in various ways depending on the
97854 ** contents of the SelectDest structure pointed to by argument pDest
97855 ** as follows:
97856 **
97857 **     pDest->eDest    Result
97858 **     ------------    -------------------------------------------
97859 **     SRT_Output      Generate a row of output (using the OP_ResultRow
97860 **                     opcode) for each row in the result set.
97861 **
97862 **     SRT_Mem         Only valid if the result is a single column.
97863 **                     Store the first column of the first result row
97864 **                     in register pDest->iParm then abandon the rest
97865 **                     of the query.  This destination implies "LIMIT 1".
97866 **
97867 **     SRT_Set         The result must be a single column.  Store each
97868 **                     row of result as the key in table pDest->iParm. 
97869 **                     Apply the affinity pDest->affinity before storing
97870 **                     results.  Used to implement "IN (SELECT ...)".
97871 **
97872 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
97873 **
97874 **     SRT_Except      Remove results from the temporary table pDest->iParm.
97875 **
97876 **     SRT_Table       Store results in temporary table pDest->iParm.
97877 **                     This is like SRT_EphemTab except that the table
97878 **                     is assumed to already be open.
97879 **
97880 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
97881 **                     the result there. The cursor is left open after
97882 **                     returning.  This is like SRT_Table except that
97883 **                     this destination uses OP_OpenEphemeral to create
97884 **                     the table first.
97885 **
97886 **     SRT_Coroutine   Generate a co-routine that returns a new row of
97887 **                     results each time it is invoked.  The entry point
97888 **                     of the co-routine is stored in register pDest->iParm.
97889 **
97890 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
97891 **                     set is not empty.
97892 **
97893 **     SRT_Discard     Throw the results away.  This is used by SELECT
97894 **                     statements within triggers whose only purpose is
97895 **                     the side-effects of functions.
97896 **
97897 ** This routine returns the number of errors.  If any errors are
97898 ** encountered, then an appropriate error message is left in
97899 ** pParse->zErrMsg.
97900 **
97901 ** This routine does NOT free the Select structure passed in.  The
97902 ** calling function needs to do that.
97903 */
97904 SQLCIPHER_PRIVATE int sqlcipher3Select(
97905   Parse *pParse,         /* The parser context */
97906   Select *p,             /* The SELECT statement being coded. */
97907   SelectDest *pDest      /* What to do with the query results */
97908 ){
97909   int i, j;              /* Loop counters */
97910   WhereInfo *pWInfo;     /* Return from sqlcipher3WhereBegin() */
97911   Vdbe *v;               /* The virtual machine under construction */
97912   int isAgg;             /* True for select lists like "count(*)" */
97913   ExprList *pEList;      /* List of columns to extract. */
97914   SrcList *pTabList;     /* List of tables to select from */
97915   Expr *pWhere;          /* The WHERE clause.  May be NULL */
97916   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
97917   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
97918   Expr *pHaving;         /* The HAVING clause.  May be NULL */
97919   int isDistinct;        /* True if the DISTINCT keyword is present */
97920   int distinct;          /* Table to use for the distinct set */
97921   int rc = 1;            /* Value to return from this function */
97922   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
97923   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
97924   AggInfo sAggInfo;      /* Information used by aggregate queries */
97925   int iEnd;              /* Address of the end of the query */
97926   sqlcipher3 *db;           /* The database connection */
97927
97928 #ifndef SQLCIPHER_OMIT_EXPLAIN
97929   int iRestoreSelectId = pParse->iSelectId;
97930   pParse->iSelectId = pParse->iNextSelectId++;
97931 #endif
97932
97933   db = pParse->db;
97934   if( p==0 || db->mallocFailed || pParse->nErr ){
97935     return 1;
97936   }
97937   if( sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0) ) return 1;
97938   memset(&sAggInfo, 0, sizeof(sAggInfo));
97939
97940   if( IgnorableOrderby(pDest) ){
97941     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
97942            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
97943     /* If ORDER BY makes no difference in the output then neither does
97944     ** DISTINCT so it can be removed too. */
97945     sqlcipher3ExprListDelete(db, p->pOrderBy);
97946     p->pOrderBy = 0;
97947     p->selFlags &= ~SF_Distinct;
97948   }
97949   sqlcipher3SelectPrep(pParse, p, 0);
97950   pOrderBy = p->pOrderBy;
97951   pTabList = p->pSrc;
97952   pEList = p->pEList;
97953   if( pParse->nErr || db->mallocFailed ){
97954     goto select_end;
97955   }
97956   isAgg = (p->selFlags & SF_Aggregate)!=0;
97957   assert( pEList!=0 );
97958
97959   /* Begin generating code.
97960   */
97961   v = sqlcipher3GetVdbe(pParse);
97962   if( v==0 ) goto select_end;
97963
97964   /* If writing to memory or generating a set
97965   ** only a single column may be output.
97966   */
97967 #ifndef SQLCIPHER_OMIT_SUBQUERY
97968   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
97969     goto select_end;
97970   }
97971 #endif
97972
97973   /* Generate code for all sub-queries in the FROM clause
97974   */
97975 #if !defined(SQLCIPHER_OMIT_SUBQUERY) || !defined(SQLCIPHER_OMIT_VIEW)
97976   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
97977     struct SrcList_item *pItem = &pTabList->a[i];
97978     SelectDest dest;
97979     Select *pSub = pItem->pSelect;
97980     int isAggSub;
97981
97982     if( pSub==0 ) continue;
97983     if( pItem->addrFillSub ){
97984       sqlcipher3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
97985       continue;
97986     }
97987
97988     /* Increment Parse.nHeight by the height of the largest expression
97989     ** tree refered to by this, the parent select. The child select
97990     ** may contain expression trees of at most
97991     ** (SQLCIPHER_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
97992     ** more conservative than necessary, but much easier than enforcing
97993     ** an exact limit.
97994     */
97995     pParse->nHeight += sqlcipher3SelectExprHeight(p);
97996
97997     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
97998     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
97999       /* This subquery can be absorbed into its parent. */
98000       if( isAggSub ){
98001         isAgg = 1;
98002         p->selFlags |= SF_Aggregate;
98003       }
98004       i = -1;
98005     }else{
98006       /* Generate a subroutine that will fill an ephemeral table with
98007       ** the content of this subquery.  pItem->addrFillSub will point
98008       ** to the address of the generated subroutine.  pItem->regReturn
98009       ** is a register allocated to hold the subroutine return address
98010       */
98011       int topAddr;
98012       int onceAddr = 0;
98013       int retAddr;
98014       assert( pItem->addrFillSub==0 );
98015       pItem->regReturn = ++pParse->nMem;
98016       topAddr = sqlcipher3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
98017       pItem->addrFillSub = topAddr+1;
98018       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
98019       if( pItem->isCorrelated==0 && pParse->pTriggerTab==0 ){
98020         /* If the subquery is no correlated and if we are not inside of
98021         ** a trigger, then we only need to compute the value of the subquery
98022         ** once. */
98023         int regOnce = ++pParse->nMem;
98024         onceAddr = sqlcipher3VdbeAddOp1(v, OP_Once, regOnce);
98025       }
98026       sqlcipher3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
98027       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98028       sqlcipher3Select(pParse, pSub, &dest);
98029       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98030       if( onceAddr ) sqlcipher3VdbeJumpHere(v, onceAddr);
98031       retAddr = sqlcipher3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98032       VdbeComment((v, "end %s", pItem->pTab->zName));
98033       sqlcipher3VdbeChangeP1(v, topAddr, retAddr);
98034
98035     }
98036     if( /*pParse->nErr ||*/ db->mallocFailed ){
98037       goto select_end;
98038     }
98039     pParse->nHeight -= sqlcipher3SelectExprHeight(p);
98040     pTabList = p->pSrc;
98041     if( !IgnorableOrderby(pDest) ){
98042       pOrderBy = p->pOrderBy;
98043     }
98044   }
98045   pEList = p->pEList;
98046 #endif
98047   pWhere = p->pWhere;
98048   pGroupBy = p->pGroupBy;
98049   pHaving = p->pHaving;
98050   isDistinct = (p->selFlags & SF_Distinct)!=0;
98051
98052 #ifndef SQLCIPHER_OMIT_COMPOUND_SELECT
98053   /* If there is are a sequence of queries, do the earlier ones first.
98054   */
98055   if( p->pPrior ){
98056     if( p->pRightmost==0 ){
98057       Select *pLoop, *pRight = 0;
98058       int cnt = 0;
98059       int mxSelect;
98060       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98061         pLoop->pRightmost = p;
98062         pLoop->pNext = pRight;
98063         pRight = pLoop;
98064       }
98065       mxSelect = db->aLimit[SQLCIPHER_LIMIT_COMPOUND_SELECT];
98066       if( mxSelect && cnt>mxSelect ){
98067         sqlcipher3ErrorMsg(pParse, "too many terms in compound SELECT");
98068         goto select_end;
98069       }
98070     }
98071     rc = multiSelect(pParse, p, pDest);
98072     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98073     return rc;
98074   }
98075 #endif
98076
98077   /* If there is both a GROUP BY and an ORDER BY clause and they are
98078   ** identical, then disable the ORDER BY clause since the GROUP BY
98079   ** will cause elements to come out in the correct order.  This is
98080   ** an optimization - the correct answer should result regardless.
98081   ** Use the SQLCIPHER_GroupByOrder flag with SQLCIPHER_TESTCTRL_OPTIMIZER
98082   ** to disable this optimization for testing purposes.
98083   */
98084   if( sqlcipher3ExprListCompare(p->pGroupBy, pOrderBy)==0
98085          && (db->flags & SQLCIPHER_GroupByOrder)==0 ){
98086     pOrderBy = 0;
98087   }
98088
98089   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
98090   ** if the select-list is the same as the ORDER BY list, then this query
98091   ** can be rewritten as a GROUP BY. In other words, this:
98092   **
98093   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98094   **
98095   ** is transformed to:
98096   **
98097   **     SELECT xyz FROM ... GROUP BY xyz
98098   **
98099   ** The second form is preferred as a single index (or temp-table) may be 
98100   ** used for both the ORDER BY and DISTINCT processing. As originally 
98101   ** written the query must use a temp-table for at least one of the ORDER 
98102   ** BY and DISTINCT, and an index or separate temp-table for the other.
98103   */
98104   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
98105    && sqlcipher3ExprListCompare(pOrderBy, p->pEList)==0
98106   ){
98107     p->selFlags &= ~SF_Distinct;
98108     p->pGroupBy = sqlcipher3ExprListDup(db, p->pEList, 0);
98109     pGroupBy = p->pGroupBy;
98110     pOrderBy = 0;
98111   }
98112
98113   /* If there is an ORDER BY clause, then this sorting
98114   ** index might end up being unused if the data can be 
98115   ** extracted in pre-sorted order.  If that is the case, then the
98116   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98117   ** we figure out that the sorting index is not needed.  The addrSortIndex
98118   ** variable is used to facilitate that change.
98119   */
98120   if( pOrderBy ){
98121     KeyInfo *pKeyInfo;
98122     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98123     pOrderBy->iECursor = pParse->nTab++;
98124     p->addrOpenEphm[2] = addrSortIndex =
98125       sqlcipher3VdbeAddOp4(v, OP_OpenEphemeral,
98126                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98127                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98128   }else{
98129     addrSortIndex = -1;
98130   }
98131
98132   /* If the output is destined for a temporary table, open that table.
98133   */
98134   if( pDest->eDest==SRT_EphemTab ){
98135     sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
98136   }
98137
98138   /* Set the limiter.
98139   */
98140   iEnd = sqlcipher3VdbeMakeLabel(v);
98141   p->nSelectRow = (double)LARGEST_INT64;
98142   computeLimitRegisters(pParse, p, iEnd);
98143   if( p->iLimit==0 && addrSortIndex>=0 ){
98144     sqlcipher3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98145     p->selFlags |= SF_UseSorter;
98146   }
98147
98148   /* Open a virtual index to use for the distinct set.
98149   */
98150   if( p->selFlags & SF_Distinct ){
98151     KeyInfo *pKeyInfo;
98152     distinct = pParse->nTab++;
98153     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
98154     addrDistinctIndex = sqlcipher3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
98155         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98156     sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
98157   }else{
98158     distinct = addrDistinctIndex = -1;
98159   }
98160
98161   /* Aggregate and non-aggregate queries are handled differently */
98162   if( !isAgg && pGroupBy==0 ){
98163     ExprList *pDist = (isDistinct ? p->pEList : 0);
98164
98165     /* Begin the database scan. */
98166     pWInfo = sqlcipher3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
98167     if( pWInfo==0 ) goto select_end;
98168     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98169
98170     /* If sorting index that was created by a prior OP_OpenEphemeral 
98171     ** instruction ended up not being needed, then change the OP_OpenEphemeral
98172     ** into an OP_Noop.
98173     */
98174     if( addrSortIndex>=0 && pOrderBy==0 ){
98175       sqlcipher3VdbeChangeToNoop(v, addrSortIndex);
98176       p->addrOpenEphm[2] = -1;
98177     }
98178
98179     if( pWInfo->eDistinct ){
98180       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
98181      
98182       assert( addrDistinctIndex>=0 );
98183       pOp = sqlcipher3VdbeGetOp(v, addrDistinctIndex);
98184
98185       assert( isDistinct );
98186       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 
98187            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE 
98188       );
98189       distinct = -1;
98190       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
98191         int iJump;
98192         int iExpr;
98193         int iFlag = ++pParse->nMem;
98194         int iBase = pParse->nMem+1;
98195         int iBase2 = iBase + pEList->nExpr;
98196         pParse->nMem += (pEList->nExpr*2);
98197
98198         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
98199         ** OP_Integer initializes the "first row" flag.  */
98200         pOp->opcode = OP_Integer;
98201         pOp->p1 = 1;
98202         pOp->p2 = iFlag;
98203
98204         sqlcipher3ExprCodeExprList(pParse, pEList, iBase, 1);
98205         iJump = sqlcipher3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
98206         sqlcipher3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
98207         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
98208           CollSeq *pColl = sqlcipher3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
98209           sqlcipher3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
98210           sqlcipher3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
98211           sqlcipher3VdbeChangeP5(v, SQLCIPHER_NULLEQ);
98212         }
98213         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
98214
98215         sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iFlag);
98216         assert( sqlcipher3VdbeCurrentAddr(v)==iJump );
98217         sqlcipher3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
98218       }else{
98219         pOp->opcode = OP_Noop;
98220       }
98221     }
98222
98223     /* Use the standard inner loop. */
98224     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
98225                     pWInfo->iContinue, pWInfo->iBreak);
98226
98227     /* End the database scan loop.
98228     */
98229     sqlcipher3WhereEnd(pWInfo);
98230   }else{
98231     /* This is the processing for aggregate queries */
98232     NameContext sNC;    /* Name context for processing aggregate information */
98233     int iAMem;          /* First Mem address for storing current GROUP BY */
98234     int iBMem;          /* First Mem address for previous GROUP BY */
98235     int iUseFlag;       /* Mem address holding flag indicating that at least
98236                         ** one row of the input to the aggregator has been
98237                         ** processed */
98238     int iAbortFlag;     /* Mem address which causes query abort if positive */
98239     int groupBySort;    /* Rows come from source in GROUP BY order */
98240     int addrEnd;        /* End of processing for this SELECT */
98241     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98242     int sortOut = 0;    /* Output register from the sorter */
98243
98244     /* Remove any and all aliases between the result set and the
98245     ** GROUP BY clause.
98246     */
98247     if( pGroupBy ){
98248       int k;                        /* Loop counter */
98249       struct ExprList_item *pItem;  /* For looping over expression in a list */
98250
98251       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98252         pItem->iAlias = 0;
98253       }
98254       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98255         pItem->iAlias = 0;
98256       }
98257       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98258     }else{
98259       p->nSelectRow = (double)1;
98260     }
98261
98262  
98263     /* Create a label to jump to when we want to abort the query */
98264     addrEnd = sqlcipher3VdbeMakeLabel(v);
98265
98266     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98267     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98268     ** SELECT statement.
98269     */
98270     memset(&sNC, 0, sizeof(sNC));
98271     sNC.pParse = pParse;
98272     sNC.pSrcList = pTabList;
98273     sNC.pAggInfo = &sAggInfo;
98274     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98275     sAggInfo.pGroupBy = pGroupBy;
98276     sqlcipher3ExprAnalyzeAggList(&sNC, pEList);
98277     sqlcipher3ExprAnalyzeAggList(&sNC, pOrderBy);
98278     if( pHaving ){
98279       sqlcipher3ExprAnalyzeAggregates(&sNC, pHaving);
98280     }
98281     sAggInfo.nAccumulator = sAggInfo.nColumn;
98282     for(i=0; i<sAggInfo.nFunc; i++){
98283       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98284       sqlcipher3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98285     }
98286     if( db->mallocFailed ) goto select_end;
98287
98288     /* Processing for aggregates with GROUP BY is very different and
98289     ** much more complex than aggregates without a GROUP BY.
98290     */
98291     if( pGroupBy ){
98292       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
98293       int j1;             /* A-vs-B comparision jump */
98294       int addrOutputRow;  /* Start of subroutine that outputs a result row */
98295       int regOutputRow;   /* Return address register for output subroutine */
98296       int addrSetAbort;   /* Set the abort flag and return */
98297       int addrTopOfLoop;  /* Top of the input loop */
98298       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
98299       int addrReset;      /* Subroutine for resetting the accumulator */
98300       int regReset;       /* Return address register for reset subroutine */
98301
98302       /* If there is a GROUP BY clause we might need a sorting index to
98303       ** implement it.  Allocate that sorting index now.  If it turns out
98304       ** that we do not need it after all, the OP_SorterOpen instruction
98305       ** will be converted into a Noop.  
98306       */
98307       sAggInfo.sortingIdx = pParse->nTab++;
98308       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
98309       addrSortingIdx = sqlcipher3VdbeAddOp4(v, OP_SorterOpen, 
98310           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
98311           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98312
98313       /* Initialize memory locations used by GROUP BY aggregate processing
98314       */
98315       iUseFlag = ++pParse->nMem;
98316       iAbortFlag = ++pParse->nMem;
98317       regOutputRow = ++pParse->nMem;
98318       addrOutputRow = sqlcipher3VdbeMakeLabel(v);
98319       regReset = ++pParse->nMem;
98320       addrReset = sqlcipher3VdbeMakeLabel(v);
98321       iAMem = pParse->nMem + 1;
98322       pParse->nMem += pGroupBy->nExpr;
98323       iBMem = pParse->nMem + 1;
98324       pParse->nMem += pGroupBy->nExpr;
98325       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
98326       VdbeComment((v, "clear abort flag"));
98327       sqlcipher3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
98328       VdbeComment((v, "indicate accumulator empty"));
98329
98330       /* Begin a loop that will extract all source rows in GROUP BY order.
98331       ** This might involve two separate loops with an OP_Sort in between, or
98332       ** it might be a single loop that uses an index to extract information
98333       ** in the right order to begin with.
98334       */
98335       sqlcipher3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98336       pWInfo = sqlcipher3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
98337       if( pWInfo==0 ) goto select_end;
98338       if( pGroupBy==0 ){
98339         /* The optimizer is able to deliver rows in group by order so
98340         ** we do not have to sort.  The OP_OpenEphemeral table will be
98341         ** cancelled later because we still need to use the pKeyInfo
98342         */
98343         pGroupBy = p->pGroupBy;
98344         groupBySort = 0;
98345       }else{
98346         /* Rows are coming out in undetermined order.  We have to push
98347         ** each row into a sorting index, terminate the first loop,
98348         ** then loop over the sorting index in order to get the output
98349         ** in sorted order
98350         */
98351         int regBase;
98352         int regRecord;
98353         int nCol;
98354         int nGroupBy;
98355
98356         explainTempTable(pParse, 
98357             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
98358
98359         groupBySort = 1;
98360         nGroupBy = pGroupBy->nExpr;
98361         nCol = nGroupBy + 1;
98362         j = nGroupBy+1;
98363         for(i=0; i<sAggInfo.nColumn; i++){
98364           if( sAggInfo.aCol[i].iSorterColumn>=j ){
98365             nCol++;
98366             j++;
98367           }
98368         }
98369         regBase = sqlcipher3GetTempRange(pParse, nCol);
98370         sqlcipher3ExprCacheClear(pParse);
98371         sqlcipher3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
98372         sqlcipher3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
98373         j = nGroupBy+1;
98374         for(i=0; i<sAggInfo.nColumn; i++){
98375           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
98376           if( pCol->iSorterColumn>=j ){
98377             int r1 = j + regBase;
98378             int r2;
98379
98380             r2 = sqlcipher3ExprCodeGetColumn(pParse, 
98381                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
98382             if( r1!=r2 ){
98383               sqlcipher3VdbeAddOp2(v, OP_SCopy, r2, r1);
98384             }
98385             j++;
98386           }
98387         }
98388         regRecord = sqlcipher3GetTempReg(pParse);
98389         sqlcipher3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
98390         sqlcipher3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
98391         sqlcipher3ReleaseTempReg(pParse, regRecord);
98392         sqlcipher3ReleaseTempRange(pParse, regBase, nCol);
98393         sqlcipher3WhereEnd(pWInfo);
98394         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
98395         sortOut = sqlcipher3GetTempReg(pParse);
98396         sqlcipher3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
98397         sqlcipher3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
98398         VdbeComment((v, "GROUP BY sort"));
98399         sAggInfo.useSortingIdx = 1;
98400         sqlcipher3ExprCacheClear(pParse);
98401       }
98402
98403       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
98404       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
98405       ** Then compare the current GROUP BY terms against the GROUP BY terms
98406       ** from the previous row currently stored in a0, a1, a2...
98407       */
98408       addrTopOfLoop = sqlcipher3VdbeCurrentAddr(v);
98409       sqlcipher3ExprCacheClear(pParse);
98410       if( groupBySort ){
98411         sqlcipher3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
98412       }
98413       for(j=0; j<pGroupBy->nExpr; j++){
98414         if( groupBySort ){
98415           sqlcipher3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
98416           if( j==0 ) sqlcipher3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
98417         }else{
98418           sAggInfo.directMode = 1;
98419           sqlcipher3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
98420         }
98421       }
98422       sqlcipher3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
98423                           (char*)pKeyInfo, P4_KEYINFO);
98424       j1 = sqlcipher3VdbeCurrentAddr(v);
98425       sqlcipher3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
98426
98427       /* Generate code that runs whenever the GROUP BY changes.
98428       ** Changes in the GROUP BY are detected by the previous code
98429       ** block.  If there were no changes, this block is skipped.
98430       **
98431       ** This code copies current group by terms in b0,b1,b2,...
98432       ** over to a0,a1,a2.  It then calls the output subroutine
98433       ** and resets the aggregate accumulator registers in preparation
98434       ** for the next GROUP BY batch.
98435       */
98436       sqlcipher3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
98437       sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98438       VdbeComment((v, "output one row"));
98439       sqlcipher3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
98440       VdbeComment((v, "check abort flag"));
98441       sqlcipher3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98442       VdbeComment((v, "reset accumulator"));
98443
98444       /* Update the aggregate accumulators based on the content of
98445       ** the current row
98446       */
98447       sqlcipher3VdbeJumpHere(v, j1);
98448       updateAccumulator(pParse, &sAggInfo);
98449       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
98450       VdbeComment((v, "indicate data in accumulator"));
98451
98452       /* End of the loop
98453       */
98454       if( groupBySort ){
98455         sqlcipher3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
98456       }else{
98457         sqlcipher3WhereEnd(pWInfo);
98458         sqlcipher3VdbeChangeToNoop(v, addrSortingIdx);
98459       }
98460
98461       /* Output the final row of result
98462       */
98463       sqlcipher3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98464       VdbeComment((v, "output final row"));
98465
98466       /* Jump over the subroutines
98467       */
98468       sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
98469
98470       /* Generate a subroutine that outputs a single row of the result
98471       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
98472       ** is less than or equal to zero, the subroutine is a no-op.  If
98473       ** the processing calls for the query to abort, this subroutine
98474       ** increments the iAbortFlag memory location before returning in
98475       ** order to signal the caller to abort.
98476       */
98477       addrSetAbort = sqlcipher3VdbeCurrentAddr(v);
98478       sqlcipher3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
98479       VdbeComment((v, "set abort flag"));
98480       sqlcipher3VdbeAddOp1(v, OP_Return, regOutputRow);
98481       sqlcipher3VdbeResolveLabel(v, addrOutputRow);
98482       addrOutputRow = sqlcipher3VdbeCurrentAddr(v);
98483       sqlcipher3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
98484       VdbeComment((v, "Groupby result generator entry point"));
98485       sqlcipher3VdbeAddOp1(v, OP_Return, regOutputRow);
98486       finalizeAggFunctions(pParse, &sAggInfo);
98487       sqlcipher3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLCIPHER_JUMPIFNULL);
98488       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
98489                       distinct, pDest,
98490                       addrOutputRow+1, addrSetAbort);
98491       sqlcipher3VdbeAddOp1(v, OP_Return, regOutputRow);
98492       VdbeComment((v, "end groupby result generator"));
98493
98494       /* Generate a subroutine that will reset the group-by accumulator
98495       */
98496       sqlcipher3VdbeResolveLabel(v, addrReset);
98497       resetAccumulator(pParse, &sAggInfo);
98498       sqlcipher3VdbeAddOp1(v, OP_Return, regReset);
98499      
98500     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
98501     else {
98502       ExprList *pDel = 0;
98503 #ifndef SQLCIPHER_OMIT_BTREECOUNT
98504       Table *pTab;
98505       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
98506         /* If isSimpleCount() returns a pointer to a Table structure, then
98507         ** the SQL statement is of the form:
98508         **
98509         **   SELECT count(*) FROM <tbl>
98510         **
98511         ** where the Table structure returned represents table <tbl>.
98512         **
98513         ** This statement is so common that it is optimized specially. The
98514         ** OP_Count instruction is executed either on the intkey table that
98515         ** contains the data for table <tbl> or on one of its indexes. It
98516         ** is better to execute the op on an index, as indexes are almost
98517         ** always spread across less pages than their corresponding tables.
98518         */
98519         const int iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
98520         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
98521         Index *pIdx;                         /* Iterator variable */
98522         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
98523         Index *pBest = 0;                    /* Best index found so far */
98524         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
98525
98526         sqlcipher3CodeVerifySchema(pParse, iDb);
98527         sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98528
98529         /* Search for the index that has the least amount of columns. If
98530         ** there is such an index, and it has less columns than the table
98531         ** does, then we can assume that it consumes less space on disk and
98532         ** will therefore be cheaper to scan to determine the query result.
98533         ** In this case set iRoot to the root page number of the index b-tree
98534         ** and pKeyInfo to the KeyInfo structure required to navigate the
98535         ** index.
98536         **
98537         ** (2011-04-15) Do not do a full scan of an unordered index.
98538         **
98539         ** In practice the KeyInfo structure will not be used. It is only 
98540         ** passed to keep OP_OpenRead happy.
98541         */
98542         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98543           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
98544             pBest = pIdx;
98545           }
98546         }
98547         if( pBest && pBest->nColumn<pTab->nCol ){
98548           iRoot = pBest->tnum;
98549           pKeyInfo = sqlcipher3IndexKeyinfo(pParse, pBest);
98550         }
98551
98552         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
98553         sqlcipher3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
98554         if( pKeyInfo ){
98555           sqlcipher3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
98556         }
98557         sqlcipher3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
98558         sqlcipher3VdbeAddOp1(v, OP_Close, iCsr);
98559         explainSimpleCount(pParse, pTab, pBest);
98560       }else
98561 #endif /* SQLCIPHER_OMIT_BTREECOUNT */
98562       {
98563         /* Check if the query is of one of the following forms:
98564         **
98565         **   SELECT min(x) FROM ...
98566         **   SELECT max(x) FROM ...
98567         **
98568         ** If it is, then ask the code in where.c to attempt to sort results
98569         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
98570         ** If where.c is able to produce results sorted in this order, then
98571         ** add vdbe code to break out of the processing loop after the 
98572         ** first iteration (since the first iteration of the loop is 
98573         ** guaranteed to operate on the row with the minimum or maximum 
98574         ** value of x, the only row required).
98575         **
98576         ** A special flag must be passed to sqlcipher3WhereBegin() to slightly
98577         ** modify behaviour as follows:
98578         **
98579         **   + If the query is a "SELECT min(x)", then the loop coded by
98580         **     where.c should not iterate over any values with a NULL value
98581         **     for x.
98582         **
98583         **   + The optimizer code in where.c (the thing that decides which
98584         **     index or indices to use) should place a different priority on 
98585         **     satisfying the 'ORDER BY' clause than it does in other cases.
98586         **     Refer to code and comments in where.c for details.
98587         */
98588         ExprList *pMinMax = 0;
98589         u8 flag = minMaxQuery(p);
98590         if( flag ){
98591           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
98592           pMinMax = sqlcipher3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
98593           pDel = pMinMax;
98594           if( pMinMax && !db->mallocFailed ){
98595             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
98596             pMinMax->a[0].pExpr->op = TK_COLUMN;
98597           }
98598         }
98599   
98600         /* This case runs if the aggregate has no GROUP BY clause.  The
98601         ** processing is much simpler since there is only a single row
98602         ** of output.
98603         */
98604         resetAccumulator(pParse, &sAggInfo);
98605         pWInfo = sqlcipher3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
98606         if( pWInfo==0 ){
98607           sqlcipher3ExprListDelete(db, pDel);
98608           goto select_end;
98609         }
98610         updateAccumulator(pParse, &sAggInfo);
98611         if( !pMinMax && flag ){
98612           sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
98613           VdbeComment((v, "%s() by index",
98614                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
98615         }
98616         sqlcipher3WhereEnd(pWInfo);
98617         finalizeAggFunctions(pParse, &sAggInfo);
98618       }
98619
98620       pOrderBy = 0;
98621       sqlcipher3ExprIfFalse(pParse, pHaving, addrEnd, SQLCIPHER_JUMPIFNULL);
98622       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
98623                       pDest, addrEnd, addrEnd);
98624       sqlcipher3ExprListDelete(db, pDel);
98625     }
98626     sqlcipher3VdbeResolveLabel(v, addrEnd);
98627     
98628   } /* endif aggregate query */
98629
98630   if( distinct>=0 ){
98631     explainTempTable(pParse, "DISTINCT");
98632   }
98633
98634   /* If there is an ORDER BY clause, then we need to sort the results
98635   ** and send them to the callback one by one.
98636   */
98637   if( pOrderBy ){
98638     explainTempTable(pParse, "ORDER BY");
98639     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
98640   }
98641
98642   /* Jump here to skip this query
98643   */
98644   sqlcipher3VdbeResolveLabel(v, iEnd);
98645
98646   /* The SELECT was successfully coded.   Set the return code to 0
98647   ** to indicate no errors.
98648   */
98649   rc = 0;
98650
98651   /* Control jumps to here if an error is encountered above, or upon
98652   ** successful coding of the SELECT.
98653   */
98654 select_end:
98655   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98656
98657   /* Identify column names if results of the SELECT are to be output.
98658   */
98659   if( rc==SQLCIPHER_OK && pDest->eDest==SRT_Output ){
98660     generateColumnNames(pParse, pTabList, pEList);
98661   }
98662
98663   sqlcipher3DbFree(db, sAggInfo.aCol);
98664   sqlcipher3DbFree(db, sAggInfo.aFunc);
98665   return rc;
98666 }
98667
98668 #if defined(SQLCIPHER_DEBUG)
98669 /*
98670 *******************************************************************************
98671 ** The following code is used for testing and debugging only.  The code
98672 ** that follows does not appear in normal builds.
98673 **
98674 ** These routines are used to print out the content of all or part of a 
98675 ** parse structures such as Select or Expr.  Such printouts are useful
98676 ** for helping to understand what is happening inside the code generator
98677 ** during the execution of complex SELECT statements.
98678 **
98679 ** These routine are not called anywhere from within the normal
98680 ** code base.  Then are intended to be called from within the debugger
98681 ** or from temporary "printf" statements inserted for debugging.
98682 */
98683 SQLCIPHER_PRIVATE void sqlcipher3PrintExpr(Expr *p){
98684   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
98685     sqlcipher3DebugPrintf("(%s", p->u.zToken);
98686   }else{
98687     sqlcipher3DebugPrintf("(%d", p->op);
98688   }
98689   if( p->pLeft ){
98690     sqlcipher3DebugPrintf(" ");
98691     sqlcipher3PrintExpr(p->pLeft);
98692   }
98693   if( p->pRight ){
98694     sqlcipher3DebugPrintf(" ");
98695     sqlcipher3PrintExpr(p->pRight);
98696   }
98697   sqlcipher3DebugPrintf(")");
98698 }
98699 SQLCIPHER_PRIVATE void sqlcipher3PrintExprList(ExprList *pList){
98700   int i;
98701   for(i=0; i<pList->nExpr; i++){
98702     sqlcipher3PrintExpr(pList->a[i].pExpr);
98703     if( i<pList->nExpr-1 ){
98704       sqlcipher3DebugPrintf(", ");
98705     }
98706   }
98707 }
98708 SQLCIPHER_PRIVATE void sqlcipher3PrintSelect(Select *p, int indent){
98709   sqlcipher3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
98710   sqlcipher3PrintExprList(p->pEList);
98711   sqlcipher3DebugPrintf("\n");
98712   if( p->pSrc ){
98713     char *zPrefix;
98714     int i;
98715     zPrefix = "FROM";
98716     for(i=0; i<p->pSrc->nSrc; i++){
98717       struct SrcList_item *pItem = &p->pSrc->a[i];
98718       sqlcipher3DebugPrintf("%*s ", indent+6, zPrefix);
98719       zPrefix = "";
98720       if( pItem->pSelect ){
98721         sqlcipher3DebugPrintf("(\n");
98722         sqlcipher3PrintSelect(pItem->pSelect, indent+10);
98723         sqlcipher3DebugPrintf("%*s)", indent+8, "");
98724       }else if( pItem->zName ){
98725         sqlcipher3DebugPrintf("%s", pItem->zName);
98726       }
98727       if( pItem->pTab ){
98728         sqlcipher3DebugPrintf("(table: %s)", pItem->pTab->zName);
98729       }
98730       if( pItem->zAlias ){
98731         sqlcipher3DebugPrintf(" AS %s", pItem->zAlias);
98732       }
98733       if( i<p->pSrc->nSrc-1 ){
98734         sqlcipher3DebugPrintf(",");
98735       }
98736       sqlcipher3DebugPrintf("\n");
98737     }
98738   }
98739   if( p->pWhere ){
98740     sqlcipher3DebugPrintf("%*s WHERE ", indent, "");
98741     sqlcipher3PrintExpr(p->pWhere);
98742     sqlcipher3DebugPrintf("\n");
98743   }
98744   if( p->pGroupBy ){
98745     sqlcipher3DebugPrintf("%*s GROUP BY ", indent, "");
98746     sqlcipher3PrintExprList(p->pGroupBy);
98747     sqlcipher3DebugPrintf("\n");
98748   }
98749   if( p->pHaving ){
98750     sqlcipher3DebugPrintf("%*s HAVING ", indent, "");
98751     sqlcipher3PrintExpr(p->pHaving);
98752     sqlcipher3DebugPrintf("\n");
98753   }
98754   if( p->pOrderBy ){
98755     sqlcipher3DebugPrintf("%*s ORDER BY ", indent, "");
98756     sqlcipher3PrintExprList(p->pOrderBy);
98757     sqlcipher3DebugPrintf("\n");
98758   }
98759 }
98760 /* End of the structure debug printing code
98761 *****************************************************************************/
98762 #endif /* defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG) */
98763
98764 /************** End of select.c **********************************************/
98765 /************** Begin file table.c *******************************************/
98766 /*
98767 ** 2001 September 15
98768 **
98769 ** The author disclaims copyright to this source code.  In place of
98770 ** a legal notice, here is a blessing:
98771 **
98772 **    May you do good and not evil.
98773 **    May you find forgiveness for yourself and forgive others.
98774 **    May you share freely, never taking more than you give.
98775 **
98776 *************************************************************************
98777 ** This file contains the sqlcipher3_get_table() and sqlcipher3_free_table()
98778 ** interface routines.  These are just wrappers around the main
98779 ** interface routine of sqlcipher3_exec().
98780 **
98781 ** These routines are in a separate files so that they will not be linked
98782 ** if they are not used.
98783 */
98784 /* #include <stdlib.h> */
98785 /* #include <string.h> */
98786
98787 #ifndef SQLCIPHER_OMIT_GET_TABLE
98788
98789 /*
98790 ** This structure is used to pass data from sqlcipher3_get_table() through
98791 ** to the callback function is uses to build the result.
98792 */
98793 typedef struct TabResult {
98794   char **azResult;   /* Accumulated output */
98795   char *zErrMsg;     /* Error message text, if an error occurs */
98796   int nAlloc;        /* Slots allocated for azResult[] */
98797   int nRow;          /* Number of rows in the result */
98798   int nColumn;       /* Number of columns in the result */
98799   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
98800   int rc;            /* Return code from sqlcipher3_exec() */
98801 } TabResult;
98802
98803 /*
98804 ** This routine is called once for each row in the result table.  Its job
98805 ** is to fill in the TabResult structure appropriately, allocating new
98806 ** memory as necessary.
98807 */
98808 static int sqlcipher3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
98809   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
98810   int need;                         /* Slots needed in p->azResult[] */
98811   int i;                            /* Loop counter */
98812   char *z;                          /* A single column of result */
98813
98814   /* Make sure there is enough space in p->azResult to hold everything
98815   ** we need to remember from this invocation of the callback.
98816   */
98817   if( p->nRow==0 && argv!=0 ){
98818     need = nCol*2;
98819   }else{
98820     need = nCol;
98821   }
98822   if( p->nData + need > p->nAlloc ){
98823     char **azNew;
98824     p->nAlloc = p->nAlloc*2 + need;
98825     azNew = sqlcipher3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
98826     if( azNew==0 ) goto malloc_failed;
98827     p->azResult = azNew;
98828   }
98829
98830   /* If this is the first row, then generate an extra row containing
98831   ** the names of all columns.
98832   */
98833   if( p->nRow==0 ){
98834     p->nColumn = nCol;
98835     for(i=0; i<nCol; i++){
98836       z = sqlcipher3_mprintf("%s", colv[i]);
98837       if( z==0 ) goto malloc_failed;
98838       p->azResult[p->nData++] = z;
98839     }
98840   }else if( p->nColumn!=nCol ){
98841     sqlcipher3_free(p->zErrMsg);
98842     p->zErrMsg = sqlcipher3_mprintf(
98843        "sqlcipher3_get_table() called with two or more incompatible queries"
98844     );
98845     p->rc = SQLCIPHER_ERROR;
98846     return 1;
98847   }
98848
98849   /* Copy over the row data
98850   */
98851   if( argv!=0 ){
98852     for(i=0; i<nCol; i++){
98853       if( argv[i]==0 ){
98854         z = 0;
98855       }else{
98856         int n = sqlcipher3Strlen30(argv[i])+1;
98857         z = sqlcipher3_malloc( n );
98858         if( z==0 ) goto malloc_failed;
98859         memcpy(z, argv[i], n);
98860       }
98861       p->azResult[p->nData++] = z;
98862     }
98863     p->nRow++;
98864   }
98865   return 0;
98866
98867 malloc_failed:
98868   p->rc = SQLCIPHER_NOMEM;
98869   return 1;
98870 }
98871
98872 /*
98873 ** Query the database.  But instead of invoking a callback for each row,
98874 ** malloc() for space to hold the result and return the entire results
98875 ** at the conclusion of the call.
98876 **
98877 ** The result that is written to ***pazResult is held in memory obtained
98878 ** from malloc().  But the caller cannot free this memory directly.  
98879 ** Instead, the entire table should be passed to sqlcipher3_free_table() when
98880 ** the calling procedure is finished using it.
98881 */
98882 SQLCIPHER_API int sqlcipher3_get_table(
98883   sqlcipher3 *db,                /* The database on which the SQL executes */
98884   const char *zSql,           /* The SQL to be executed */
98885   char ***pazResult,          /* Write the result table here */
98886   int *pnRow,                 /* Write the number of rows in the result here */
98887   int *pnColumn,              /* Write the number of columns of result here */
98888   char **pzErrMsg             /* Write error messages here */
98889 ){
98890   int rc;
98891   TabResult res;
98892
98893   *pazResult = 0;
98894   if( pnColumn ) *pnColumn = 0;
98895   if( pnRow ) *pnRow = 0;
98896   if( pzErrMsg ) *pzErrMsg = 0;
98897   res.zErrMsg = 0;
98898   res.nRow = 0;
98899   res.nColumn = 0;
98900   res.nData = 1;
98901   res.nAlloc = 20;
98902   res.rc = SQLCIPHER_OK;
98903   res.azResult = sqlcipher3_malloc(sizeof(char*)*res.nAlloc );
98904   if( res.azResult==0 ){
98905      db->errCode = SQLCIPHER_NOMEM;
98906      return SQLCIPHER_NOMEM;
98907   }
98908   res.azResult[0] = 0;
98909   rc = sqlcipher3_exec(db, zSql, sqlcipher3_get_table_cb, &res, pzErrMsg);
98910   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
98911   res.azResult[0] = SQLCIPHER_INT_TO_PTR(res.nData);
98912   if( (rc&0xff)==SQLCIPHER_ABORT ){
98913     sqlcipher3_free_table(&res.azResult[1]);
98914     if( res.zErrMsg ){
98915       if( pzErrMsg ){
98916         sqlcipher3_free(*pzErrMsg);
98917         *pzErrMsg = sqlcipher3_mprintf("%s",res.zErrMsg);
98918       }
98919       sqlcipher3_free(res.zErrMsg);
98920     }
98921     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
98922     return res.rc;
98923   }
98924   sqlcipher3_free(res.zErrMsg);
98925   if( rc!=SQLCIPHER_OK ){
98926     sqlcipher3_free_table(&res.azResult[1]);
98927     return rc;
98928   }
98929   if( res.nAlloc>res.nData ){
98930     char **azNew;
98931     azNew = sqlcipher3_realloc( res.azResult, sizeof(char*)*res.nData );
98932     if( azNew==0 ){
98933       sqlcipher3_free_table(&res.azResult[1]);
98934       db->errCode = SQLCIPHER_NOMEM;
98935       return SQLCIPHER_NOMEM;
98936     }
98937     res.azResult = azNew;
98938   }
98939   *pazResult = &res.azResult[1];
98940   if( pnColumn ) *pnColumn = res.nColumn;
98941   if( pnRow ) *pnRow = res.nRow;
98942   return rc;
98943 }
98944
98945 /*
98946 ** This routine frees the space the sqlcipher3_get_table() malloced.
98947 */
98948 SQLCIPHER_API void sqlcipher3_free_table(
98949   char **azResult            /* Result returned from from sqlcipher3_get_table() */
98950 ){
98951   if( azResult ){
98952     int i, n;
98953     azResult--;
98954     assert( azResult!=0 );
98955     n = SQLCIPHER_PTR_TO_INT(azResult[0]);
98956     for(i=1; i<n; i++){ if( azResult[i] ) sqlcipher3_free(azResult[i]); }
98957     sqlcipher3_free(azResult);
98958   }
98959 }
98960
98961 #endif /* SQLCIPHER_OMIT_GET_TABLE */
98962
98963 /************** End of table.c ***********************************************/
98964 /************** Begin file trigger.c *****************************************/
98965 /*
98966 **
98967 ** The author disclaims copyright to this source code.  In place of
98968 ** a legal notice, here is a blessing:
98969 **
98970 **    May you do good and not evil.
98971 **    May you find forgiveness for yourself and forgive others.
98972 **    May you share freely, never taking more than you give.
98973 **
98974 *************************************************************************
98975 ** This file contains the implementation for TRIGGERs
98976 */
98977
98978 #ifndef SQLCIPHER_OMIT_TRIGGER
98979 /*
98980 ** Delete a linked list of TriggerStep structures.
98981 */
98982 SQLCIPHER_PRIVATE void sqlcipher3DeleteTriggerStep(sqlcipher3 *db, TriggerStep *pTriggerStep){
98983   while( pTriggerStep ){
98984     TriggerStep * pTmp = pTriggerStep;
98985     pTriggerStep = pTriggerStep->pNext;
98986
98987     sqlcipher3ExprDelete(db, pTmp->pWhere);
98988     sqlcipher3ExprListDelete(db, pTmp->pExprList);
98989     sqlcipher3SelectDelete(db, pTmp->pSelect);
98990     sqlcipher3IdListDelete(db, pTmp->pIdList);
98991
98992     sqlcipher3DbFree(db, pTmp);
98993   }
98994 }
98995
98996 /*
98997 ** Given table pTab, return a list of all the triggers attached to 
98998 ** the table. The list is connected by Trigger.pNext pointers.
98999 **
99000 ** All of the triggers on pTab that are in the same database as pTab
99001 ** are already attached to pTab->pTrigger.  But there might be additional
99002 ** triggers on pTab in the TEMP schema.  This routine prepends all
99003 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
99004 ** and returns the combined list.
99005 **
99006 ** To state it another way:  This routine returns a list of all triggers
99007 ** that fire off of pTab.  The list will include any TEMP triggers on
99008 ** pTab as well as the triggers lised in pTab->pTrigger.
99009 */
99010 SQLCIPHER_PRIVATE Trigger *sqlcipher3TriggerList(Parse *pParse, Table *pTab){
99011   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
99012   Trigger *pList = 0;                  /* List of triggers to return */
99013
99014   if( pParse->disableTriggers ){
99015     return 0;
99016   }
99017
99018   if( pTmpSchema!=pTab->pSchema ){
99019     HashElem *p;
99020     assert( sqlcipher3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
99021     for(p=sqlcipherHashFirst(&pTmpSchema->trigHash); p; p=sqlcipherHashNext(p)){
99022       Trigger *pTrig = (Trigger *)sqlcipherHashData(p);
99023       if( pTrig->pTabSchema==pTab->pSchema
99024        && 0==sqlcipher3StrICmp(pTrig->table, pTab->zName) 
99025       ){
99026         pTrig->pNext = (pList ? pList : pTab->pTrigger);
99027         pList = pTrig;
99028       }
99029     }
99030   }
99031
99032   return (pList ? pList : pTab->pTrigger);
99033 }
99034
99035 /*
99036 ** This is called by the parser when it sees a CREATE TRIGGER statement
99037 ** up to the point of the BEGIN before the trigger actions.  A Trigger
99038 ** structure is generated based on the information available and stored
99039 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99040 ** sqlcipher3FinishTrigger() function is called to complete the trigger
99041 ** construction process.
99042 */
99043 SQLCIPHER_PRIVATE void sqlcipher3BeginTrigger(
99044   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99045   Token *pName1,      /* The name of the trigger */
99046   Token *pName2,      /* The name of the trigger */
99047   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99048   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99049   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99050   SrcList *pTableName,/* The name of the table/view the trigger applies to */
99051   Expr *pWhen,        /* WHEN clause */
99052   int isTemp,         /* True if the TEMPORARY keyword is present */
99053   int noErr           /* Suppress errors if the trigger already exists */
99054 ){
99055   Trigger *pTrigger = 0;  /* The new trigger */
99056   Table *pTab;            /* Table that the trigger fires off of */
99057   char *zName = 0;        /* Name of the trigger */
99058   sqlcipher3 *db = pParse->db;  /* The database connection */
99059   int iDb;                /* The database to store the trigger in */
99060   Token *pName;           /* The unqualified db name */
99061   DbFixer sFix;           /* State vector for the DB fixer */
99062   int iTabDb;             /* Index of the database holding pTab */
99063
99064   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99065   assert( pName2!=0 );
99066   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99067   assert( op>0 && op<0xff );
99068   if( isTemp ){
99069     /* If TEMP was specified, then the trigger name may not be qualified. */
99070     if( pName2->n>0 ){
99071       sqlcipher3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99072       goto trigger_cleanup;
99073     }
99074     iDb = 1;
99075     pName = pName1;
99076   }else{
99077     /* Figure out the db that the the trigger will be created in */
99078     iDb = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
99079     if( iDb<0 ){
99080       goto trigger_cleanup;
99081     }
99082   }
99083   if( !pTableName || db->mallocFailed ){
99084     goto trigger_cleanup;
99085   }
99086
99087   /* A long-standing parser bug is that this syntax was allowed:
99088   **
99089   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99090   **                                                 ^^^^^^^^
99091   **
99092   ** To maintain backwards compatibility, ignore the database
99093   ** name on pTableName if we are reparsing our of SQLCIPHER_MASTER.
99094   */
99095   if( db->init.busy && iDb!=1 ){
99096     sqlcipher3DbFree(db, pTableName->a[0].zDatabase);
99097     pTableName->a[0].zDatabase = 0;
99098   }
99099
99100   /* If the trigger name was unqualified, and the table is a temp table,
99101   ** then set iDb to 1 to create the trigger in the temporary database.
99102   ** If sqlcipher3SrcListLookup() returns 0, indicating the table does not
99103   ** exist, the error is caught by the block below.
99104   */
99105   pTab = sqlcipher3SrcListLookup(pParse, pTableName);
99106   if( db->init.busy==0 && pName2->n==0 && pTab
99107         && pTab->pSchema==db->aDb[1].pSchema ){
99108     iDb = 1;
99109   }
99110
99111   /* Ensure the table name matches database name and that the table exists */
99112   if( db->mallocFailed ) goto trigger_cleanup;
99113   assert( pTableName->nSrc==1 );
99114   if( sqlcipher3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
99115       sqlcipher3FixSrcList(&sFix, pTableName) ){
99116     goto trigger_cleanup;
99117   }
99118   pTab = sqlcipher3SrcListLookup(pParse, pTableName);
99119   if( !pTab ){
99120     /* The table does not exist. */
99121     if( db->init.iDb==1 ){
99122       /* Ticket #3810.
99123       ** Normally, whenever a table is dropped, all associated triggers are
99124       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99125       ** and the table is dropped by a different database connection, the
99126       ** trigger is not visible to the database connection that does the
99127       ** drop so the trigger cannot be dropped.  This results in an
99128       ** "orphaned trigger" - a trigger whose associated table is missing.
99129       */
99130       db->init.orphanTrigger = 1;
99131     }
99132     goto trigger_cleanup;
99133   }
99134   if( IsVirtual(pTab) ){
99135     sqlcipher3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99136     goto trigger_cleanup;
99137   }
99138
99139   /* Check that the trigger name is not reserved and that no trigger of the
99140   ** specified name exists */
99141   zName = sqlcipher3NameFromToken(db, pName);
99142   if( !zName || SQLCIPHER_OK!=sqlcipher3CheckObjectName(pParse, zName) ){
99143     goto trigger_cleanup;
99144   }
99145   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
99146   if( sqlcipher3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99147                       zName, sqlcipher3Strlen30(zName)) ){
99148     if( !noErr ){
99149       sqlcipher3ErrorMsg(pParse, "trigger %T already exists", pName);
99150     }else{
99151       assert( !db->init.busy );
99152       sqlcipher3CodeVerifySchema(pParse, iDb);
99153     }
99154     goto trigger_cleanup;
99155   }
99156
99157   /* Do not create a trigger on a system table */
99158   if( sqlcipher3StrNICmp(pTab->zName, "sqlcipher_", 7)==0 ){
99159     sqlcipher3ErrorMsg(pParse, "cannot create trigger on system table");
99160     pParse->nErr++;
99161     goto trigger_cleanup;
99162   }
99163
99164   /* INSTEAD of triggers are only for views and views only support INSTEAD
99165   ** of triggers.
99166   */
99167   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99168     sqlcipher3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
99169         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99170     goto trigger_cleanup;
99171   }
99172   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99173     sqlcipher3ErrorMsg(pParse, "cannot create INSTEAD OF"
99174         " trigger on table: %S", pTableName, 0);
99175     goto trigger_cleanup;
99176   }
99177   iTabDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
99178
99179 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
99180   {
99181     int code = SQLCIPHER_CREATE_TRIGGER;
99182     const char *zDb = db->aDb[iTabDb].zName;
99183     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99184     if( iTabDb==1 || isTemp ) code = SQLCIPHER_CREATE_TEMP_TRIGGER;
99185     if( sqlcipher3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99186       goto trigger_cleanup;
99187     }
99188     if( sqlcipher3AuthCheck(pParse, SQLCIPHER_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99189       goto trigger_cleanup;
99190     }
99191   }
99192 #endif
99193
99194   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99195   ** cannot appear on views.  So we might as well translate every
99196   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99197   ** elsewhere.
99198   */
99199   if (tr_tm == TK_INSTEAD){
99200     tr_tm = TK_BEFORE;
99201   }
99202
99203   /* Build the Trigger object */
99204   pTrigger = (Trigger*)sqlcipher3DbMallocZero(db, sizeof(Trigger));
99205   if( pTrigger==0 ) goto trigger_cleanup;
99206   pTrigger->zName = zName;
99207   zName = 0;
99208   pTrigger->table = sqlcipher3DbStrDup(db, pTableName->a[0].zName);
99209   pTrigger->pSchema = db->aDb[iDb].pSchema;
99210   pTrigger->pTabSchema = pTab->pSchema;
99211   pTrigger->op = (u8)op;
99212   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99213   pTrigger->pWhen = sqlcipher3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99214   pTrigger->pColumns = sqlcipher3IdListDup(db, pColumns);
99215   assert( pParse->pNewTrigger==0 );
99216   pParse->pNewTrigger = pTrigger;
99217
99218 trigger_cleanup:
99219   sqlcipher3DbFree(db, zName);
99220   sqlcipher3SrcListDelete(db, pTableName);
99221   sqlcipher3IdListDelete(db, pColumns);
99222   sqlcipher3ExprDelete(db, pWhen);
99223   if( !pParse->pNewTrigger ){
99224     sqlcipher3DeleteTrigger(db, pTrigger);
99225   }else{
99226     assert( pParse->pNewTrigger==pTrigger );
99227   }
99228 }
99229
99230 /*
99231 ** This routine is called after all of the trigger actions have been parsed
99232 ** in order to complete the process of building the trigger.
99233 */
99234 SQLCIPHER_PRIVATE void sqlcipher3FinishTrigger(
99235   Parse *pParse,          /* Parser context */
99236   TriggerStep *pStepList, /* The triggered program */
99237   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99238 ){
99239   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99240   char *zName;                            /* Name of trigger */
99241   sqlcipher3 *db = pParse->db;               /* The database */
99242   DbFixer sFix;                           /* Fixer object */
99243   int iDb;                                /* Database containing the trigger */
99244   Token nameToken;                        /* Trigger name for error reporting */
99245
99246   pParse->pNewTrigger = 0;
99247   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99248   zName = pTrig->zName;
99249   iDb = sqlcipher3SchemaToIndex(pParse->db, pTrig->pSchema);
99250   pTrig->step_list = pStepList;
99251   while( pStepList ){
99252     pStepList->pTrig = pTrig;
99253     pStepList = pStepList->pNext;
99254   }
99255   nameToken.z = pTrig->zName;
99256   nameToken.n = sqlcipher3Strlen30(nameToken.z);
99257   if( sqlcipher3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
99258           && sqlcipher3FixTriggerStep(&sFix, pTrig->step_list) ){
99259     goto triggerfinish_cleanup;
99260   }
99261
99262   /* if we are not initializing,
99263   ** build the sqlcipher_master entry
99264   */
99265   if( !db->init.busy ){
99266     Vdbe *v;
99267     char *z;
99268
99269     /* Make an entry in the sqlcipher_master table */
99270     v = sqlcipher3GetVdbe(pParse);
99271     if( v==0 ) goto triggerfinish_cleanup;
99272     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
99273     z = sqlcipher3DbStrNDup(db, (char*)pAll->z, pAll->n);
99274     sqlcipher3NestedParse(pParse,
99275        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
99276        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
99277        pTrig->table, z);
99278     sqlcipher3DbFree(db, z);
99279     sqlcipher3ChangeCookie(pParse, iDb);
99280     sqlcipher3VdbeAddParseSchemaOp(v, iDb,
99281         sqlcipher3MPrintf(db, "type='trigger' AND name='%q'", zName));
99282   }
99283
99284   if( db->init.busy ){
99285     Trigger *pLink = pTrig;
99286     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
99287     assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
99288     pTrig = sqlcipher3HashInsert(pHash, zName, sqlcipher3Strlen30(zName), pTrig);
99289     if( pTrig ){
99290       db->mallocFailed = 1;
99291     }else if( pLink->pSchema==pLink->pTabSchema ){
99292       Table *pTab;
99293       int n = sqlcipher3Strlen30(pLink->table);
99294       pTab = sqlcipher3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
99295       assert( pTab!=0 );
99296       pLink->pNext = pTab->pTrigger;
99297       pTab->pTrigger = pLink;
99298     }
99299   }
99300
99301 triggerfinish_cleanup:
99302   sqlcipher3DeleteTrigger(db, pTrig);
99303   assert( !pParse->pNewTrigger );
99304   sqlcipher3DeleteTriggerStep(db, pStepList);
99305 }
99306
99307 /*
99308 ** Turn a SELECT statement (that the pSelect parameter points to) into
99309 ** a trigger step.  Return a pointer to a TriggerStep structure.
99310 **
99311 ** The parser calls this routine when it finds a SELECT statement in
99312 ** body of a TRIGGER.  
99313 */
99314 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerSelectStep(sqlcipher3 *db, Select *pSelect){
99315   TriggerStep *pTriggerStep = sqlcipher3DbMallocZero(db, sizeof(TriggerStep));
99316   if( pTriggerStep==0 ) {
99317     sqlcipher3SelectDelete(db, pSelect);
99318     return 0;
99319   }
99320   pTriggerStep->op = TK_SELECT;
99321   pTriggerStep->pSelect = pSelect;
99322   pTriggerStep->orconf = OE_Default;
99323   return pTriggerStep;
99324 }
99325
99326 /*
99327 ** Allocate space to hold a new trigger step.  The allocated space
99328 ** holds both the TriggerStep object and the TriggerStep.target.z string.
99329 **
99330 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
99331 */
99332 static TriggerStep *triggerStepAllocate(
99333   sqlcipher3 *db,                /* Database connection */
99334   u8 op,                      /* Trigger opcode */
99335   Token *pName                /* The target name */
99336 ){
99337   TriggerStep *pTriggerStep;
99338
99339   pTriggerStep = sqlcipher3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
99340   if( pTriggerStep ){
99341     char *z = (char*)&pTriggerStep[1];
99342     memcpy(z, pName->z, pName->n);
99343     pTriggerStep->target.z = z;
99344     pTriggerStep->target.n = pName->n;
99345     pTriggerStep->op = op;
99346   }
99347   return pTriggerStep;
99348 }
99349
99350 /*
99351 ** Build a trigger step out of an INSERT statement.  Return a pointer
99352 ** to the new trigger step.
99353 **
99354 ** The parser calls this routine when it sees an INSERT inside the
99355 ** body of a trigger.
99356 */
99357 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerInsertStep(
99358   sqlcipher3 *db,        /* The database connection */
99359   Token *pTableName,  /* Name of the table into which we insert */
99360   IdList *pColumn,    /* List of columns in pTableName to insert into */
99361   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
99362   Select *pSelect,    /* A SELECT statement that supplies values */
99363   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
99364 ){
99365   TriggerStep *pTriggerStep;
99366
99367   assert(pEList == 0 || pSelect == 0);
99368   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
99369
99370   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
99371   if( pTriggerStep ){
99372     pTriggerStep->pSelect = sqlcipher3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99373     pTriggerStep->pIdList = pColumn;
99374     pTriggerStep->pExprList = sqlcipher3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99375     pTriggerStep->orconf = orconf;
99376   }else{
99377     sqlcipher3IdListDelete(db, pColumn);
99378   }
99379   sqlcipher3ExprListDelete(db, pEList);
99380   sqlcipher3SelectDelete(db, pSelect);
99381
99382   return pTriggerStep;
99383 }
99384
99385 /*
99386 ** Construct a trigger step that implements an UPDATE statement and return
99387 ** a pointer to that trigger step.  The parser calls this routine when it
99388 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
99389 */
99390 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerUpdateStep(
99391   sqlcipher3 *db,         /* The database connection */
99392   Token *pTableName,   /* Name of the table to be updated */
99393   ExprList *pEList,    /* The SET clause: list of column and new values */
99394   Expr *pWhere,        /* The WHERE clause */
99395   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
99396 ){
99397   TriggerStep *pTriggerStep;
99398
99399   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
99400   if( pTriggerStep ){
99401     pTriggerStep->pExprList = sqlcipher3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99402     pTriggerStep->pWhere = sqlcipher3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99403     pTriggerStep->orconf = orconf;
99404   }
99405   sqlcipher3ExprListDelete(db, pEList);
99406   sqlcipher3ExprDelete(db, pWhere);
99407   return pTriggerStep;
99408 }
99409
99410 /*
99411 ** Construct a trigger step that implements a DELETE statement and return
99412 ** a pointer to that trigger step.  The parser calls this routine when it
99413 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
99414 */
99415 SQLCIPHER_PRIVATE TriggerStep *sqlcipher3TriggerDeleteStep(
99416   sqlcipher3 *db,            /* Database connection */
99417   Token *pTableName,      /* The table from which rows are deleted */
99418   Expr *pWhere            /* The WHERE clause */
99419 ){
99420   TriggerStep *pTriggerStep;
99421
99422   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
99423   if( pTriggerStep ){
99424     pTriggerStep->pWhere = sqlcipher3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99425     pTriggerStep->orconf = OE_Default;
99426   }
99427   sqlcipher3ExprDelete(db, pWhere);
99428   return pTriggerStep;
99429 }
99430
99431 /* 
99432 ** Recursively delete a Trigger structure
99433 */
99434 SQLCIPHER_PRIVATE void sqlcipher3DeleteTrigger(sqlcipher3 *db, Trigger *pTrigger){
99435   if( pTrigger==0 ) return;
99436   sqlcipher3DeleteTriggerStep(db, pTrigger->step_list);
99437   sqlcipher3DbFree(db, pTrigger->zName);
99438   sqlcipher3DbFree(db, pTrigger->table);
99439   sqlcipher3ExprDelete(db, pTrigger->pWhen);
99440   sqlcipher3IdListDelete(db, pTrigger->pColumns);
99441   sqlcipher3DbFree(db, pTrigger);
99442 }
99443
99444 /*
99445 ** This function is called to drop a trigger from the database schema. 
99446 **
99447 ** This may be called directly from the parser and therefore identifies
99448 ** the trigger by name.  The sqlcipher3DropTriggerPtr() routine does the
99449 ** same job as this routine except it takes a pointer to the trigger
99450 ** instead of the trigger name.
99451 **/
99452 SQLCIPHER_PRIVATE void sqlcipher3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
99453   Trigger *pTrigger = 0;
99454   int i;
99455   const char *zDb;
99456   const char *zName;
99457   int nName;
99458   sqlcipher3 *db = pParse->db;
99459
99460   if( db->mallocFailed ) goto drop_trigger_cleanup;
99461   if( SQLCIPHER_OK!=sqlcipher3ReadSchema(pParse) ){
99462     goto drop_trigger_cleanup;
99463   }
99464
99465   assert( pName->nSrc==1 );
99466   zDb = pName->a[0].zDatabase;
99467   zName = pName->a[0].zName;
99468   nName = sqlcipher3Strlen30(zName);
99469   assert( zDb!=0 || sqlcipher3BtreeHoldsAllMutexes(db) );
99470   for(i=OMIT_TEMPDB; i<db->nDb; i++){
99471     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
99472     if( zDb && sqlcipher3StrICmp(db->aDb[j].zName, zDb) ) continue;
99473     assert( sqlcipher3SchemaMutexHeld(db, j, 0) );
99474     pTrigger = sqlcipher3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
99475     if( pTrigger ) break;
99476   }
99477   if( !pTrigger ){
99478     if( !noErr ){
99479       sqlcipher3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
99480     }else{
99481       sqlcipher3CodeVerifyNamedSchema(pParse, zDb);
99482     }
99483     pParse->checkSchema = 1;
99484     goto drop_trigger_cleanup;
99485   }
99486   sqlcipher3DropTriggerPtr(pParse, pTrigger);
99487
99488 drop_trigger_cleanup:
99489   sqlcipher3SrcListDelete(db, pName);
99490 }
99491
99492 /*
99493 ** Return a pointer to the Table structure for the table that a trigger
99494 ** is set on.
99495 */
99496 static Table *tableOfTrigger(Trigger *pTrigger){
99497   int n = sqlcipher3Strlen30(pTrigger->table);
99498   return sqlcipher3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
99499 }
99500
99501
99502 /*
99503 ** Drop a trigger given a pointer to that trigger. 
99504 */
99505 SQLCIPHER_PRIVATE void sqlcipher3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
99506   Table   *pTable;
99507   Vdbe *v;
99508   sqlcipher3 *db = pParse->db;
99509   int iDb;
99510
99511   iDb = sqlcipher3SchemaToIndex(pParse->db, pTrigger->pSchema);
99512   assert( iDb>=0 && iDb<db->nDb );
99513   pTable = tableOfTrigger(pTrigger);
99514   assert( pTable );
99515   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
99516 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
99517   {
99518     int code = SQLCIPHER_DROP_TRIGGER;
99519     const char *zDb = db->aDb[iDb].zName;
99520     const char *zTab = SCHEMA_TABLE(iDb);
99521     if( iDb==1 ) code = SQLCIPHER_DROP_TEMP_TRIGGER;
99522     if( sqlcipher3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
99523       sqlcipher3AuthCheck(pParse, SQLCIPHER_DELETE, zTab, 0, zDb) ){
99524       return;
99525     }
99526   }
99527 #endif
99528
99529   /* Generate code to destroy the database record of the trigger.
99530   */
99531   assert( pTable!=0 );
99532   if( (v = sqlcipher3GetVdbe(pParse))!=0 ){
99533     int base;
99534     static const VdbeOpList dropTrigger[] = {
99535       { OP_Rewind,     0, ADDR(9),  0},
99536       { OP_String8,    0, 1,        0}, /* 1 */
99537       { OP_Column,     0, 1,        2},
99538       { OP_Ne,         2, ADDR(8),  1},
99539       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
99540       { OP_Column,     0, 0,        2},
99541       { OP_Ne,         2, ADDR(8),  1},
99542       { OP_Delete,     0, 0,        0},
99543       { OP_Next,       0, ADDR(1),  0}, /* 8 */
99544     };
99545
99546     sqlcipher3BeginWriteOperation(pParse, 0, iDb);
99547     sqlcipher3OpenMasterTable(pParse, iDb);
99548     base = sqlcipher3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
99549     sqlcipher3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
99550     sqlcipher3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
99551     sqlcipher3ChangeCookie(pParse, iDb);
99552     sqlcipher3VdbeAddOp2(v, OP_Close, 0, 0);
99553     sqlcipher3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
99554     if( pParse->nMem<3 ){
99555       pParse->nMem = 3;
99556     }
99557   }
99558 }
99559
99560 /*
99561 ** Remove a trigger from the hash tables of the sqlcipher* pointer.
99562 */
99563 SQLCIPHER_PRIVATE void sqlcipher3UnlinkAndDeleteTrigger(sqlcipher3 *db, int iDb, const char *zName){
99564   Trigger *pTrigger;
99565   Hash *pHash;
99566
99567   assert( sqlcipher3SchemaMutexHeld(db, iDb, 0) );
99568   pHash = &(db->aDb[iDb].pSchema->trigHash);
99569   pTrigger = sqlcipher3HashInsert(pHash, zName, sqlcipher3Strlen30(zName), 0);
99570   if( ALWAYS(pTrigger) ){
99571     if( pTrigger->pSchema==pTrigger->pTabSchema ){
99572       Table *pTab = tableOfTrigger(pTrigger);
99573       Trigger **pp;
99574       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
99575       *pp = (*pp)->pNext;
99576     }
99577     sqlcipher3DeleteTrigger(db, pTrigger);
99578     db->flags |= SQLCIPHER_InternChanges;
99579   }
99580 }
99581
99582 /*
99583 ** pEList is the SET clause of an UPDATE statement.  Each entry
99584 ** in pEList is of the format <id>=<expr>.  If any of the entries
99585 ** in pEList have an <id> which matches an identifier in pIdList,
99586 ** then return TRUE.  If pIdList==NULL, then it is considered a
99587 ** wildcard that matches anything.  Likewise if pEList==NULL then
99588 ** it matches anything so always return true.  Return false only
99589 ** if there is no match.
99590 */
99591 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
99592   int e;
99593   if( pIdList==0 || NEVER(pEList==0) ) return 1;
99594   for(e=0; e<pEList->nExpr; e++){
99595     if( sqlcipher3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
99596   }
99597   return 0; 
99598 }
99599
99600 /*
99601 ** Return a list of all triggers on table pTab if there exists at least
99602 ** one trigger that must be fired when an operation of type 'op' is 
99603 ** performed on the table, and, if that operation is an UPDATE, if at
99604 ** least one of the columns in pChanges is being modified.
99605 */
99606 SQLCIPHER_PRIVATE Trigger *sqlcipher3TriggersExist(
99607   Parse *pParse,          /* Parse context */
99608   Table *pTab,            /* The table the contains the triggers */
99609   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
99610   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
99611   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99612 ){
99613   int mask = 0;
99614   Trigger *pList = 0;
99615   Trigger *p;
99616
99617   if( (pParse->db->flags & SQLCIPHER_EnableTrigger)!=0 ){
99618     pList = sqlcipher3TriggerList(pParse, pTab);
99619   }
99620   assert( pList==0 || IsVirtual(pTab)==0 );
99621   for(p=pList; p; p=p->pNext){
99622     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
99623       mask |= p->tr_tm;
99624     }
99625   }
99626   if( pMask ){
99627     *pMask = mask;
99628   }
99629   return (mask ? pList : 0);
99630 }
99631
99632 /*
99633 ** Convert the pStep->target token into a SrcList and return a pointer
99634 ** to that SrcList.
99635 **
99636 ** This routine adds a specific database name, if needed, to the target when
99637 ** forming the SrcList.  This prevents a trigger in one database from
99638 ** referring to a target in another database.  An exception is when the
99639 ** trigger is in TEMP in which case it can refer to any other database it
99640 ** wants.
99641 */
99642 static SrcList *targetSrcList(
99643   Parse *pParse,       /* The parsing context */
99644   TriggerStep *pStep   /* The trigger containing the target token */
99645 ){
99646   int iDb;             /* Index of the database to use */
99647   SrcList *pSrc;       /* SrcList to be returned */
99648
99649   pSrc = sqlcipher3SrcListAppend(pParse->db, 0, &pStep->target, 0);
99650   if( pSrc ){
99651     assert( pSrc->nSrc>0 );
99652     assert( pSrc->a!=0 );
99653     iDb = sqlcipher3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
99654     if( iDb==0 || iDb>=2 ){
99655       sqlcipher3 *db = pParse->db;
99656       assert( iDb<pParse->db->nDb );
99657       pSrc->a[pSrc->nSrc-1].zDatabase = sqlcipher3DbStrDup(db, db->aDb[iDb].zName);
99658     }
99659   }
99660   return pSrc;
99661 }
99662
99663 /*
99664 ** Generate VDBE code for the statements inside the body of a single 
99665 ** trigger.
99666 */
99667 static int codeTriggerProgram(
99668   Parse *pParse,            /* The parser context */
99669   TriggerStep *pStepList,   /* List of statements inside the trigger body */
99670   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
99671 ){
99672   TriggerStep *pStep;
99673   Vdbe *v = pParse->pVdbe;
99674   sqlcipher3 *db = pParse->db;
99675
99676   assert( pParse->pTriggerTab && pParse->pToplevel );
99677   assert( pStepList );
99678   assert( v!=0 );
99679   for(pStep=pStepList; pStep; pStep=pStep->pNext){
99680     /* Figure out the ON CONFLICT policy that will be used for this step
99681     ** of the trigger program. If the statement that caused this trigger
99682     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
99683     ** the ON CONFLICT policy that was specified as part of the trigger
99684     ** step statement. Example:
99685     **
99686     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
99687     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
99688     **   END;
99689     **
99690     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
99691     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
99692     */
99693     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
99694
99695     switch( pStep->op ){
99696       case TK_UPDATE: {
99697         sqlcipher3Update(pParse, 
99698           targetSrcList(pParse, pStep),
99699           sqlcipher3ExprListDup(db, pStep->pExprList, 0), 
99700           sqlcipher3ExprDup(db, pStep->pWhere, 0), 
99701           pParse->eOrconf
99702         );
99703         break;
99704       }
99705       case TK_INSERT: {
99706         sqlcipher3Insert(pParse, 
99707           targetSrcList(pParse, pStep),
99708           sqlcipher3ExprListDup(db, pStep->pExprList, 0), 
99709           sqlcipher3SelectDup(db, pStep->pSelect, 0), 
99710           sqlcipher3IdListDup(db, pStep->pIdList), 
99711           pParse->eOrconf
99712         );
99713         break;
99714       }
99715       case TK_DELETE: {
99716         sqlcipher3DeleteFrom(pParse, 
99717           targetSrcList(pParse, pStep),
99718           sqlcipher3ExprDup(db, pStep->pWhere, 0)
99719         );
99720         break;
99721       }
99722       default: assert( pStep->op==TK_SELECT ); {
99723         SelectDest sDest;
99724         Select *pSelect = sqlcipher3SelectDup(db, pStep->pSelect, 0);
99725         sqlcipher3SelectDestInit(&sDest, SRT_Discard, 0);
99726         sqlcipher3Select(pParse, pSelect, &sDest);
99727         sqlcipher3SelectDelete(db, pSelect);
99728         break;
99729       }
99730     } 
99731     if( pStep->op!=TK_SELECT ){
99732       sqlcipher3VdbeAddOp0(v, OP_ResetCount);
99733     }
99734   }
99735
99736   return 0;
99737 }
99738
99739 #ifdef SQLCIPHER_DEBUG
99740 /*
99741 ** This function is used to add VdbeComment() annotations to a VDBE
99742 ** program. It is not used in production code, only for debugging.
99743 */
99744 static const char *onErrorText(int onError){
99745   switch( onError ){
99746     case OE_Abort:    return "abort";
99747     case OE_Rollback: return "rollback";
99748     case OE_Fail:     return "fail";
99749     case OE_Replace:  return "replace";
99750     case OE_Ignore:   return "ignore";
99751     case OE_Default:  return "default";
99752   }
99753   return "n/a";
99754 }
99755 #endif
99756
99757 /*
99758 ** Parse context structure pFrom has just been used to create a sub-vdbe
99759 ** (trigger program). If an error has occurred, transfer error information
99760 ** from pFrom to pTo.
99761 */
99762 static void transferParseError(Parse *pTo, Parse *pFrom){
99763   assert( pFrom->zErrMsg==0 || pFrom->nErr );
99764   assert( pTo->zErrMsg==0 || pTo->nErr );
99765   if( pTo->nErr==0 ){
99766     pTo->zErrMsg = pFrom->zErrMsg;
99767     pTo->nErr = pFrom->nErr;
99768   }else{
99769     sqlcipher3DbFree(pFrom->db, pFrom->zErrMsg);
99770   }
99771 }
99772
99773 /*
99774 ** Create and populate a new TriggerPrg object with a sub-program 
99775 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
99776 */
99777 static TriggerPrg *codeRowTrigger(
99778   Parse *pParse,       /* Current parse context */
99779   Trigger *pTrigger,   /* Trigger to code */
99780   Table *pTab,         /* The table pTrigger is attached to */
99781   int orconf           /* ON CONFLICT policy to code trigger program with */
99782 ){
99783   Parse *pTop = sqlcipher3ParseToplevel(pParse);
99784   sqlcipher3 *db = pParse->db;   /* Database handle */
99785   TriggerPrg *pPrg;           /* Value to return */
99786   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
99787   Vdbe *v;                    /* Temporary VM */
99788   NameContext sNC;            /* Name context for sub-vdbe */
99789   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
99790   Parse *pSubParse;           /* Parse context for sub-vdbe */
99791   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
99792
99793   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
99794   assert( pTop->pVdbe );
99795
99796   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
99797   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
99798   ** list of the top-level Parse object sooner rather than later.  */
99799   pPrg = sqlcipher3DbMallocZero(db, sizeof(TriggerPrg));
99800   if( !pPrg ) return 0;
99801   pPrg->pNext = pTop->pTriggerPrg;
99802   pTop->pTriggerPrg = pPrg;
99803   pPrg->pProgram = pProgram = sqlcipher3DbMallocZero(db, sizeof(SubProgram));
99804   if( !pProgram ) return 0;
99805   sqlcipher3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
99806   pPrg->pTrigger = pTrigger;
99807   pPrg->orconf = orconf;
99808   pPrg->aColmask[0] = 0xffffffff;
99809   pPrg->aColmask[1] = 0xffffffff;
99810
99811   /* Allocate and populate a new Parse context to use for coding the 
99812   ** trigger sub-program.  */
99813   pSubParse = sqlcipher3StackAllocZero(db, sizeof(Parse));
99814   if( !pSubParse ) return 0;
99815   memset(&sNC, 0, sizeof(sNC));
99816   sNC.pParse = pSubParse;
99817   pSubParse->db = db;
99818   pSubParse->pTriggerTab = pTab;
99819   pSubParse->pToplevel = pTop;
99820   pSubParse->zAuthContext = pTrigger->zName;
99821   pSubParse->eTriggerOp = pTrigger->op;
99822   pSubParse->nQueryLoop = pParse->nQueryLoop;
99823
99824   v = sqlcipher3GetVdbe(pSubParse);
99825   if( v ){
99826     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
99827       pTrigger->zName, onErrorText(orconf),
99828       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
99829         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
99830         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
99831         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
99832       pTab->zName
99833     ));
99834 #ifndef SQLCIPHER_OMIT_TRACE
99835     sqlcipher3VdbeChangeP4(v, -1, 
99836       sqlcipher3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
99837     );
99838 #endif
99839
99840     /* If one was specified, code the WHEN clause. If it evaluates to false
99841     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
99842     ** OP_Halt inserted at the end of the program.  */
99843     if( pTrigger->pWhen ){
99844       pWhen = sqlcipher3ExprDup(db, pTrigger->pWhen, 0);
99845       if( SQLCIPHER_OK==sqlcipher3ResolveExprNames(&sNC, pWhen) 
99846        && db->mallocFailed==0 
99847       ){
99848         iEndTrigger = sqlcipher3VdbeMakeLabel(v);
99849         sqlcipher3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLCIPHER_JUMPIFNULL);
99850       }
99851       sqlcipher3ExprDelete(db, pWhen);
99852     }
99853
99854     /* Code the trigger program into the sub-vdbe. */
99855     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
99856
99857     /* Insert an OP_Halt at the end of the sub-program. */
99858     if( iEndTrigger ){
99859       sqlcipher3VdbeResolveLabel(v, iEndTrigger);
99860     }
99861     sqlcipher3VdbeAddOp0(v, OP_Halt);
99862     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
99863
99864     transferParseError(pParse, pSubParse);
99865     if( db->mallocFailed==0 ){
99866       pProgram->aOp = sqlcipher3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
99867     }
99868     pProgram->nMem = pSubParse->nMem;
99869     pProgram->nCsr = pSubParse->nTab;
99870     pProgram->token = (void *)pTrigger;
99871     pPrg->aColmask[0] = pSubParse->oldmask;
99872     pPrg->aColmask[1] = pSubParse->newmask;
99873     sqlcipher3VdbeDelete(v);
99874   }
99875
99876   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
99877   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
99878   sqlcipher3StackFree(db, pSubParse);
99879
99880   return pPrg;
99881 }
99882     
99883 /*
99884 ** Return a pointer to a TriggerPrg object containing the sub-program for
99885 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
99886 ** TriggerPrg object exists, a new object is allocated and populated before
99887 ** being returned.
99888 */
99889 static TriggerPrg *getRowTrigger(
99890   Parse *pParse,       /* Current parse context */
99891   Trigger *pTrigger,   /* Trigger to code */
99892   Table *pTab,         /* The table trigger pTrigger is attached to */
99893   int orconf           /* ON CONFLICT algorithm. */
99894 ){
99895   Parse *pRoot = sqlcipher3ParseToplevel(pParse);
99896   TriggerPrg *pPrg;
99897
99898   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
99899
99900   /* It may be that this trigger has already been coded (or is in the
99901   ** process of being coded). If this is the case, then an entry with
99902   ** a matching TriggerPrg.pTrigger field will be present somewhere
99903   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
99904   for(pPrg=pRoot->pTriggerPrg; 
99905       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
99906       pPrg=pPrg->pNext
99907   );
99908
99909   /* If an existing TriggerPrg could not be located, create a new one. */
99910   if( !pPrg ){
99911     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
99912   }
99913
99914   return pPrg;
99915 }
99916
99917 /*
99918 ** Generate code for the trigger program associated with trigger p on 
99919 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
99920 ** function are the same as those described in the header function for
99921 ** sqlcipher3CodeRowTrigger()
99922 */
99923 SQLCIPHER_PRIVATE void sqlcipher3CodeRowTriggerDirect(
99924   Parse *pParse,       /* Parse context */
99925   Trigger *p,          /* Trigger to code */
99926   Table *pTab,         /* The table to code triggers from */
99927   int reg,             /* Reg array containing OLD.* and NEW.* values */
99928   int orconf,          /* ON CONFLICT policy */
99929   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
99930 ){
99931   Vdbe *v = sqlcipher3GetVdbe(pParse); /* Main VM */
99932   TriggerPrg *pPrg;
99933   pPrg = getRowTrigger(pParse, p, pTab, orconf);
99934   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
99935
99936   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
99937   ** is a pointer to the sub-vdbe containing the trigger program.  */
99938   if( pPrg ){
99939     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLCIPHER_RecTriggers));
99940
99941     sqlcipher3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
99942     sqlcipher3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
99943     VdbeComment(
99944         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
99945
99946     /* Set the P5 operand of the OP_Program instruction to non-zero if
99947     ** recursive invocation of this trigger program is disallowed. Recursive
99948     ** invocation is disallowed if (a) the sub-program is really a trigger,
99949     ** not a foreign key action, and (b) the flag to enable recursive triggers
99950     ** is clear.  */
99951     sqlcipher3VdbeChangeP5(v, (u8)bRecursive);
99952   }
99953 }
99954
99955 /*
99956 ** This is called to code the required FOR EACH ROW triggers for an operation
99957 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
99958 ** is given by the op paramater. The tr_tm parameter determines whether the
99959 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
99960 ** parameter pChanges is passed the list of columns being modified.
99961 **
99962 ** If there are no triggers that fire at the specified time for the specified
99963 ** operation on pTab, this function is a no-op.
99964 **
99965 ** The reg argument is the address of the first in an array of registers 
99966 ** that contain the values substituted for the new.* and old.* references
99967 ** in the trigger program. If N is the number of columns in table pTab
99968 ** (a copy of pTab->nCol), then registers are populated as follows:
99969 **
99970 **   Register       Contains
99971 **   ------------------------------------------------------
99972 **   reg+0          OLD.rowid
99973 **   reg+1          OLD.* value of left-most column of pTab
99974 **   ...            ...
99975 **   reg+N          OLD.* value of right-most column of pTab
99976 **   reg+N+1        NEW.rowid
99977 **   reg+N+2        OLD.* value of left-most column of pTab
99978 **   ...            ...
99979 **   reg+N+N+1      NEW.* value of right-most column of pTab
99980 **
99981 ** For ON DELETE triggers, the registers containing the NEW.* values will
99982 ** never be accessed by the trigger program, so they are not allocated or 
99983 ** populated by the caller (there is no data to populate them with anyway). 
99984 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
99985 ** are never accessed, and so are not allocated by the caller. So, for an
99986 ** ON INSERT trigger, the value passed to this function as parameter reg
99987 ** is not a readable register, although registers (reg+N) through 
99988 ** (reg+N+N+1) are.
99989 **
99990 ** Parameter orconf is the default conflict resolution algorithm for the
99991 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
99992 ** is the instruction that control should jump to if a trigger program
99993 ** raises an IGNORE exception.
99994 */
99995 SQLCIPHER_PRIVATE void sqlcipher3CodeRowTrigger(
99996   Parse *pParse,       /* Parse context */
99997   Trigger *pTrigger,   /* List of triggers on table pTab */
99998   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
99999   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100000   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
100001   Table *pTab,         /* The table to code triggers from */
100002   int reg,             /* The first in an array of registers (see above) */
100003   int orconf,          /* ON CONFLICT policy */
100004   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100005 ){
100006   Trigger *p;          /* Used to iterate through pTrigger list */
100007
100008   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
100009   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
100010   assert( (op==TK_UPDATE)==(pChanges!=0) );
100011
100012   for(p=pTrigger; p; p=p->pNext){
100013
100014     /* Sanity checking:  The schema for the trigger and for the table are
100015     ** always defined.  The trigger must be in the same schema as the table
100016     ** or else it must be a TEMP trigger. */
100017     assert( p->pSchema!=0 );
100018     assert( p->pTabSchema!=0 );
100019     assert( p->pSchema==p->pTabSchema 
100020          || p->pSchema==pParse->db->aDb[1].pSchema );
100021
100022     /* Determine whether we should code this trigger */
100023     if( p->op==op 
100024      && p->tr_tm==tr_tm 
100025      && checkColumnOverlap(p->pColumns, pChanges)
100026     ){
100027       sqlcipher3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
100028     }
100029   }
100030 }
100031
100032 /*
100033 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
100034 ** This function returns a 32-bit bitmask indicating which columns of the 
100035 ** old.* or new.* tables actually are used by triggers. This information 
100036 ** may be used by the caller, for example, to avoid having to load the entire
100037 ** old.* record into memory when executing an UPDATE or DELETE command.
100038 **
100039 ** Bit 0 of the returned mask is set if the left-most column of the
100040 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100041 ** the second leftmost column value is required, and so on. If there
100042 ** are more than 32 columns in the table, and at least one of the columns
100043 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
100044 **
100045 ** It is not possible to determine if the old.rowid or new.rowid column is 
100046 ** accessed by triggers. The caller must always assume that it is.
100047 **
100048 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100049 ** applies to the old.* table. If 1, the new.* table.
100050 **
100051 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100052 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100053 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100054 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100055 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100056 */
100057 SQLCIPHER_PRIVATE u32 sqlcipher3TriggerColmask(
100058   Parse *pParse,       /* Parse context */
100059   Trigger *pTrigger,   /* List of triggers on table pTab */
100060   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100061   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100062   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100063   Table *pTab,         /* The table to code triggers from */
100064   int orconf           /* Default ON CONFLICT policy for trigger steps */
100065 ){
100066   const int op = pChanges ? TK_UPDATE : TK_DELETE;
100067   u32 mask = 0;
100068   Trigger *p;
100069
100070   assert( isNew==1 || isNew==0 );
100071   for(p=pTrigger; p; p=p->pNext){
100072     if( p->op==op && (tr_tm&p->tr_tm)
100073      && checkColumnOverlap(p->pColumns,pChanges)
100074     ){
100075       TriggerPrg *pPrg;
100076       pPrg = getRowTrigger(pParse, p, pTab, orconf);
100077       if( pPrg ){
100078         mask |= pPrg->aColmask[isNew];
100079       }
100080     }
100081   }
100082
100083   return mask;
100084 }
100085
100086 #endif /* !defined(SQLCIPHER_OMIT_TRIGGER) */
100087
100088 /************** End of trigger.c *********************************************/
100089 /************** Begin file update.c ******************************************/
100090 /*
100091 ** 2001 September 15
100092 **
100093 ** The author disclaims copyright to this source code.  In place of
100094 ** a legal notice, here is a blessing:
100095 **
100096 **    May you do good and not evil.
100097 **    May you find forgiveness for yourself and forgive others.
100098 **    May you share freely, never taking more than you give.
100099 **
100100 *************************************************************************
100101 ** This file contains C code routines that are called by the parser
100102 ** to handle UPDATE statements.
100103 */
100104
100105 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
100106 /* Forward declaration */
100107 static void updateVirtualTable(
100108   Parse *pParse,       /* The parsing context */
100109   SrcList *pSrc,       /* The virtual table to be modified */
100110   Table *pTab,         /* The virtual table */
100111   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100112   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100113   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100114   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100115   int onError          /* ON CONFLICT strategy */
100116 );
100117 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
100118
100119 /*
100120 ** The most recently coded instruction was an OP_Column to retrieve the
100121 ** i-th column of table pTab. This routine sets the P4 parameter of the 
100122 ** OP_Column to the default value, if any.
100123 **
100124 ** The default value of a column is specified by a DEFAULT clause in the 
100125 ** column definition. This was either supplied by the user when the table
100126 ** was created, or added later to the table definition by an ALTER TABLE
100127 ** command. If the latter, then the row-records in the table btree on disk
100128 ** may not contain a value for the column and the default value, taken
100129 ** from the P4 parameter of the OP_Column instruction, is returned instead.
100130 ** If the former, then all row-records are guaranteed to include a value
100131 ** for the column and the P4 value is not required.
100132 **
100133 ** Column definitions created by an ALTER TABLE command may only have 
100134 ** literal default values specified: a number, null or a string. (If a more
100135 ** complicated default expression value was provided, it is evaluated 
100136 ** when the ALTER TABLE is executed and one of the literal values written
100137 ** into the sqlcipher_master table.)
100138 **
100139 ** Therefore, the P4 parameter is only required if the default value for
100140 ** the column is a literal number, string or null. The sqlcipher3ValueFromExpr()
100141 ** function is capable of transforming these types of expressions into
100142 ** sqlcipher3_value objects.
100143 **
100144 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
100145 ** on register iReg. This is used when an equivalent integer value is 
100146 ** stored in place of an 8-byte floating point value in order to save 
100147 ** space.
100148 */
100149 SQLCIPHER_PRIVATE void sqlcipher3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100150   assert( pTab!=0 );
100151   if( !pTab->pSelect ){
100152     sqlcipher3_value *pValue;
100153     u8 enc = ENC(sqlcipher3VdbeDb(v));
100154     Column *pCol = &pTab->aCol[i];
100155     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100156     assert( i<pTab->nCol );
100157     sqlcipher3ValueFromExpr(sqlcipher3VdbeDb(v), pCol->pDflt, enc, 
100158                          pCol->affinity, &pValue);
100159     if( pValue ){
100160       sqlcipher3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100161     }
100162 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
100163     if( iReg>=0 && pTab->aCol[i].affinity==SQLCIPHER_AFF_REAL ){
100164       sqlcipher3VdbeAddOp1(v, OP_RealAffinity, iReg);
100165     }
100166 #endif
100167   }
100168 }
100169
100170 /*
100171 ** Process an UPDATE statement.
100172 **
100173 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100174 **          \_______/ \________/     \______/       \________________/
100175 *            onError   pTabList      pChanges             pWhere
100176 */
100177 SQLCIPHER_PRIVATE void sqlcipher3Update(
100178   Parse *pParse,         /* The parser context */
100179   SrcList *pTabList,     /* The table in which we should change things */
100180   ExprList *pChanges,    /* Things to be changed */
100181   Expr *pWhere,          /* The WHERE clause.  May be null */
100182   int onError            /* How to handle constraint errors */
100183 ){
100184   int i, j;              /* Loop counters */
100185   Table *pTab;           /* The table to be updated */
100186   int addr = 0;          /* VDBE instruction address of the start of the loop */
100187   WhereInfo *pWInfo;     /* Information about the WHERE clause */
100188   Vdbe *v;               /* The virtual database engine */
100189   Index *pIdx;           /* For looping over indices */
100190   int nIdx;              /* Number of indices that need updating */
100191   int iCur;              /* VDBE Cursor number of pTab */
100192   sqlcipher3 *db;           /* The database structure */
100193   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100194   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100195                          ** an expression for the i-th column of the table.
100196                          ** aXRef[i]==-1 if the i-th column is not changed. */
100197   int chngRowid;         /* True if the record number is being changed */
100198   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100199   int openAll = 0;       /* True if all indices need to be opened */
100200   AuthContext sContext;  /* The authorization context */
100201   NameContext sNC;       /* The name-context to resolve expressions in */
100202   int iDb;               /* Database containing the table being updated */
100203   int okOnePass;         /* True for one-pass algorithm without the FIFO */
100204   int hasFK;             /* True if foreign key processing is required */
100205
100206 #ifndef SQLCIPHER_OMIT_TRIGGER
100207   int isView;            /* True when updating a view (INSTEAD OF trigger) */
100208   Trigger *pTrigger;     /* List of triggers on pTab, if required */
100209   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100210 #endif
100211   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100212
100213   /* Register Allocations */
100214   int regRowCount = 0;   /* A count of rows changed */
100215   int regOldRowid;       /* The old rowid */
100216   int regNewRowid;       /* The new rowid */
100217   int regNew;
100218   int regOld = 0;
100219   int regRowSet = 0;     /* Rowset of rows to be updated */
100220
100221   memset(&sContext, 0, sizeof(sContext));
100222   db = pParse->db;
100223   if( pParse->nErr || db->mallocFailed ){
100224     goto update_cleanup;
100225   }
100226   assert( pTabList->nSrc==1 );
100227
100228   /* Locate the table which we want to update. 
100229   */
100230   pTab = sqlcipher3SrcListLookup(pParse, pTabList);
100231   if( pTab==0 ) goto update_cleanup;
100232   iDb = sqlcipher3SchemaToIndex(pParse->db, pTab->pSchema);
100233
100234   /* Figure out if we have any triggers and if the table being
100235   ** updated is a view.
100236   */
100237 #ifndef SQLCIPHER_OMIT_TRIGGER
100238   pTrigger = sqlcipher3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100239   isView = pTab->pSelect!=0;
100240   assert( pTrigger || tmask==0 );
100241 #else
100242 # define pTrigger 0
100243 # define isView 0
100244 # define tmask 0
100245 #endif
100246 #ifdef SQLCIPHER_OMIT_VIEW
100247 # undef isView
100248 # define isView 0
100249 #endif
100250
100251   if( sqlcipher3ViewGetColumnNames(pParse, pTab) ){
100252     goto update_cleanup;
100253   }
100254   if( sqlcipher3IsReadOnly(pParse, pTab, tmask) ){
100255     goto update_cleanup;
100256   }
100257   aXRef = sqlcipher3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100258   if( aXRef==0 ) goto update_cleanup;
100259   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100260
100261   /* Allocate a cursors for the main database table and for all indices.
100262   ** The index cursors might not be used, but if they are used they
100263   ** need to occur right after the database cursor.  So go ahead and
100264   ** allocate enough space, just in case.
100265   */
100266   pTabList->a[0].iCursor = iCur = pParse->nTab++;
100267   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100268     pParse->nTab++;
100269   }
100270
100271   /* Initialize the name-context */
100272   memset(&sNC, 0, sizeof(sNC));
100273   sNC.pParse = pParse;
100274   sNC.pSrcList = pTabList;
100275
100276   /* Resolve the column names in all the expressions of the
100277   ** of the UPDATE statement.  Also find the column index
100278   ** for each column to be updated in the pChanges array.  For each
100279   ** column to be updated, make sure we have authorization to change
100280   ** that column.
100281   */
100282   chngRowid = 0;
100283   for(i=0; i<pChanges->nExpr; i++){
100284     if( sqlcipher3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
100285       goto update_cleanup;
100286     }
100287     for(j=0; j<pTab->nCol; j++){
100288       if( sqlcipher3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
100289         if( j==pTab->iPKey ){
100290           chngRowid = 1;
100291           pRowidExpr = pChanges->a[i].pExpr;
100292         }
100293         aXRef[j] = i;
100294         break;
100295       }
100296     }
100297     if( j>=pTab->nCol ){
100298       if( sqlcipher3IsRowid(pChanges->a[i].zName) ){
100299         chngRowid = 1;
100300         pRowidExpr = pChanges->a[i].pExpr;
100301       }else{
100302         sqlcipher3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
100303         pParse->checkSchema = 1;
100304         goto update_cleanup;
100305       }
100306     }
100307 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
100308     {
100309       int rc;
100310       rc = sqlcipher3AuthCheck(pParse, SQLCIPHER_UPDATE, pTab->zName,
100311                            pTab->aCol[j].zName, db->aDb[iDb].zName);
100312       if( rc==SQLCIPHER_DENY ){
100313         goto update_cleanup;
100314       }else if( rc==SQLCIPHER_IGNORE ){
100315         aXRef[j] = -1;
100316       }
100317     }
100318 #endif
100319   }
100320
100321   hasFK = sqlcipher3FkRequired(pParse, pTab, aXRef, chngRowid);
100322
100323   /* Allocate memory for the array aRegIdx[].  There is one entry in the
100324   ** array for each index associated with table being updated.  Fill in
100325   ** the value with a register number for indices that are to be used
100326   ** and with zero for unused indices.
100327   */
100328   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
100329   if( nIdx>0 ){
100330     aRegIdx = sqlcipher3DbMallocRaw(db, sizeof(Index*) * nIdx );
100331     if( aRegIdx==0 ) goto update_cleanup;
100332   }
100333   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
100334     int reg;
100335     if( hasFK || chngRowid ){
100336       reg = ++pParse->nMem;
100337     }else{
100338       reg = 0;
100339       for(i=0; i<pIdx->nColumn; i++){
100340         if( aXRef[pIdx->aiColumn[i]]>=0 ){
100341           reg = ++pParse->nMem;
100342           break;
100343         }
100344       }
100345     }
100346     aRegIdx[j] = reg;
100347   }
100348
100349   /* Begin generating code. */
100350   v = sqlcipher3GetVdbe(pParse);
100351   if( v==0 ) goto update_cleanup;
100352   if( pParse->nested==0 ) sqlcipher3VdbeCountChanges(v);
100353   sqlcipher3BeginWriteOperation(pParse, 1, iDb);
100354
100355 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
100356   /* Virtual tables must be handled separately */
100357   if( IsVirtual(pTab) ){
100358     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
100359                        pWhere, onError);
100360     pWhere = 0;
100361     pTabList = 0;
100362     goto update_cleanup;
100363   }
100364 #endif
100365
100366   /* Allocate required registers. */
100367   regOldRowid = regNewRowid = ++pParse->nMem;
100368   if( pTrigger || hasFK ){
100369     regOld = pParse->nMem + 1;
100370     pParse->nMem += pTab->nCol;
100371   }
100372   if( chngRowid || pTrigger || hasFK ){
100373     regNewRowid = ++pParse->nMem;
100374   }
100375   regNew = pParse->nMem + 1;
100376   pParse->nMem += pTab->nCol;
100377
100378   /* Start the view context. */
100379   if( isView ){
100380     sqlcipher3AuthContextPush(pParse, &sContext, pTab->zName);
100381   }
100382
100383   /* If we are trying to update a view, realize that view into
100384   ** a ephemeral table.
100385   */
100386 #if !defined(SQLCIPHER_OMIT_VIEW) && !defined(SQLCIPHER_OMIT_TRIGGER)
100387   if( isView ){
100388     sqlcipher3MaterializeView(pParse, pTab, pWhere, iCur);
100389   }
100390 #endif
100391
100392   /* Resolve the column names in all the expressions in the
100393   ** WHERE clause.
100394   */
100395   if( sqlcipher3ResolveExprNames(&sNC, pWhere) ){
100396     goto update_cleanup;
100397   }
100398
100399   /* Begin the database scan
100400   */
100401   sqlcipher3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
100402   pWInfo = sqlcipher3WhereBegin(
100403       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
100404   );
100405   if( pWInfo==0 ) goto update_cleanup;
100406   okOnePass = pWInfo->okOnePass;
100407
100408   /* Remember the rowid of every item to be updated.
100409   */
100410   sqlcipher3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
100411   if( !okOnePass ){
100412     regRowSet = ++pParse->nMem;
100413     sqlcipher3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
100414   }
100415
100416   /* End the database scan loop.
100417   */
100418   sqlcipher3WhereEnd(pWInfo);
100419
100420   /* Initialize the count of updated rows
100421   */
100422   if( (db->flags & SQLCIPHER_CountRows) && !pParse->pTriggerTab ){
100423     regRowCount = ++pParse->nMem;
100424     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100425   }
100426
100427   if( !isView ){
100428     /* 
100429     ** Open every index that needs updating.  Note that if any
100430     ** index could potentially invoke a REPLACE conflict resolution 
100431     ** action, then we need to open all indices because we might need
100432     ** to be deleting some records.
100433     */
100434     if( !okOnePass ) sqlcipher3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
100435     if( onError==OE_Replace ){
100436       openAll = 1;
100437     }else{
100438       openAll = 0;
100439       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100440         if( pIdx->onError==OE_Replace ){
100441           openAll = 1;
100442           break;
100443         }
100444       }
100445     }
100446     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100447       assert( aRegIdx );
100448       if( openAll || aRegIdx[i]>0 ){
100449         KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIdx);
100450         sqlcipher3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
100451                        (char*)pKey, P4_KEYINFO_HANDOFF);
100452         assert( pParse->nTab>iCur+i+1 );
100453       }
100454     }
100455   }
100456
100457   /* Top of the update loop */
100458   if( okOnePass ){
100459     int a1 = sqlcipher3VdbeAddOp1(v, OP_NotNull, regOldRowid);
100460     addr = sqlcipher3VdbeAddOp0(v, OP_Goto);
100461     sqlcipher3VdbeJumpHere(v, a1);
100462   }else{
100463     addr = sqlcipher3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
100464   }
100465
100466   /* Make cursor iCur point to the record that is being updated. If
100467   ** this record does not exist for some reason (deleted by a trigger,
100468   ** for example, then jump to the next iteration of the RowSet loop.  */
100469   sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100470
100471   /* If the record number will change, set register regNewRowid to
100472   ** contain the new value. If the record number is not being modified,
100473   ** then regNewRowid is the same register as regOldRowid, which is
100474   ** already populated.  */
100475   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
100476   if( chngRowid ){
100477     sqlcipher3ExprCode(pParse, pRowidExpr, regNewRowid);
100478     sqlcipher3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
100479   }
100480
100481   /* If there are triggers on this table, populate an array of registers 
100482   ** with the required old.* column data.  */
100483   if( hasFK || pTrigger ){
100484     u32 oldmask = (hasFK ? sqlcipher3FkOldmask(pParse, pTab) : 0);
100485     oldmask |= sqlcipher3TriggerColmask(pParse, 
100486         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
100487     );
100488     for(i=0; i<pTab->nCol; i++){
100489       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
100490         sqlcipher3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
100491       }else{
100492         sqlcipher3VdbeAddOp2(v, OP_Null, 0, regOld+i);
100493       }
100494     }
100495     if( chngRowid==0 ){
100496       sqlcipher3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
100497     }
100498   }
100499
100500   /* Populate the array of registers beginning at regNew with the new
100501   ** row data. This array is used to check constaints, create the new
100502   ** table and index records, and as the values for any new.* references
100503   ** made by triggers.
100504   **
100505   ** If there are one or more BEFORE triggers, then do not populate the
100506   ** registers associated with columns that are (a) not modified by
100507   ** this UPDATE statement and (b) not accessed by new.* references. The
100508   ** values for registers not modified by the UPDATE must be reloaded from 
100509   ** the database after the BEFORE triggers are fired anyway (as the trigger 
100510   ** may have modified them). So not loading those that are not going to
100511   ** be used eliminates some redundant opcodes.
100512   */
100513   newmask = sqlcipher3TriggerColmask(
100514       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
100515   );
100516   for(i=0; i<pTab->nCol; i++){
100517     if( i==pTab->iPKey ){
100518       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regNew+i);
100519     }else{
100520       j = aXRef[i];
100521       if( j>=0 ){
100522         sqlcipher3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
100523       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
100524         /* This branch loads the value of a column that will not be changed 
100525         ** into a register. This is done if there are no BEFORE triggers, or
100526         ** if there are one or more BEFORE triggers that use this value via
100527         ** a new.* reference in a trigger program.
100528         */
100529         testcase( i==31 );
100530         testcase( i==32 );
100531         sqlcipher3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100532         sqlcipher3ColumnDefault(v, pTab, i, regNew+i);
100533       }
100534     }
100535   }
100536
100537   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
100538   ** verified. One could argue that this is wrong.
100539   */
100540   if( tmask&TRIGGER_BEFORE ){
100541     sqlcipher3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
100542     sqlcipher3TableAffinityStr(v, pTab);
100543     sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100544         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
100545
100546     /* The row-trigger may have deleted the row being updated. In this
100547     ** case, jump to the next row. No updates or AFTER triggers are 
100548     ** required. This behaviour - what happens when the row being updated
100549     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
100550     ** documentation.
100551     */
100552     sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100553
100554     /* If it did not delete it, the row-trigger may still have modified 
100555     ** some of the columns of the row being updated. Load the values for 
100556     ** all columns not modified by the update statement into their 
100557     ** registers in case this has happened.
100558     */
100559     for(i=0; i<pTab->nCol; i++){
100560       if( aXRef[i]<0 && i!=pTab->iPKey ){
100561         sqlcipher3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100562         sqlcipher3ColumnDefault(v, pTab, i, regNew+i);
100563       }
100564     }
100565   }
100566
100567   if( !isView ){
100568     int j1;                       /* Address of jump instruction */
100569
100570     /* Do constraint checks. */
100571     sqlcipher3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
100572         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
100573
100574     /* Do FK constraint checks. */
100575     if( hasFK ){
100576       sqlcipher3FkCheck(pParse, pTab, regOldRowid, 0);
100577     }
100578
100579     /* Delete the index entries associated with the current record.  */
100580     j1 = sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
100581     sqlcipher3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
100582   
100583     /* If changing the record number, delete the old record.  */
100584     if( hasFK || chngRowid ){
100585       sqlcipher3VdbeAddOp2(v, OP_Delete, iCur, 0);
100586     }
100587     sqlcipher3VdbeJumpHere(v, j1);
100588
100589     if( hasFK ){
100590       sqlcipher3FkCheck(pParse, pTab, 0, regNewRowid);
100591     }
100592   
100593     /* Insert the new index entries and the new record. */
100594     sqlcipher3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
100595
100596     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
100597     ** handle rows (possibly in other tables) that refer via a foreign key
100598     ** to the row just updated. */ 
100599     if( hasFK ){
100600       sqlcipher3FkActions(pParse, pTab, pChanges, regOldRowid);
100601     }
100602   }
100603
100604   /* Increment the row counter 
100605   */
100606   if( (db->flags & SQLCIPHER_CountRows) && !pParse->pTriggerTab){
100607     sqlcipher3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100608   }
100609
100610   sqlcipher3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100611       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
100612
100613   /* Repeat the above with the next record to be updated, until
100614   ** all record selected by the WHERE clause have been updated.
100615   */
100616   sqlcipher3VdbeAddOp2(v, OP_Goto, 0, addr);
100617   sqlcipher3VdbeJumpHere(v, addr);
100618
100619   /* Close all tables */
100620   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100621     assert( aRegIdx );
100622     if( openAll || aRegIdx[i]>0 ){
100623       sqlcipher3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
100624     }
100625   }
100626   sqlcipher3VdbeAddOp2(v, OP_Close, iCur, 0);
100627
100628   /* Update the sqlcipher_sequence table by storing the content of the
100629   ** maximum rowid counter values recorded while inserting into
100630   ** autoincrement tables.
100631   */
100632   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100633     sqlcipher3AutoincrementEnd(pParse);
100634   }
100635
100636   /*
100637   ** Return the number of rows that were changed. If this routine is 
100638   ** generating code because of a call to sqlcipher3NestedParse(), do not
100639   ** invoke the callback function.
100640   */
100641   if( (db->flags&SQLCIPHER_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
100642     sqlcipher3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100643     sqlcipher3VdbeSetNumCols(v, 1);
100644     sqlcipher3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLCIPHER_STATIC);
100645   }
100646
100647 update_cleanup:
100648   sqlcipher3AuthContextPop(&sContext);
100649   sqlcipher3DbFree(db, aRegIdx);
100650   sqlcipher3DbFree(db, aXRef);
100651   sqlcipher3SrcListDelete(db, pTabList);
100652   sqlcipher3ExprListDelete(db, pChanges);
100653   sqlcipher3ExprDelete(db, pWhere);
100654   return;
100655 }
100656 /* Make sure "isView" and other macros defined above are undefined. Otherwise
100657 ** thely may interfere with compilation of other functions in this file
100658 ** (or in another file, if this file becomes part of the amalgamation).  */
100659 #ifdef isView
100660  #undef isView
100661 #endif
100662 #ifdef pTrigger
100663  #undef pTrigger
100664 #endif
100665
100666 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
100667 /*
100668 ** Generate code for an UPDATE of a virtual table.
100669 **
100670 ** The strategy is that we create an ephemerial table that contains
100671 ** for each row to be changed:
100672 **
100673 **   (A)  The original rowid of that row.
100674 **   (B)  The revised rowid for the row. (note1)
100675 **   (C)  The content of every column in the row.
100676 **
100677 ** Then we loop over this ephemeral table and for each row in
100678 ** the ephermeral table call VUpdate.
100679 **
100680 ** When finished, drop the ephemeral table.
100681 **
100682 ** (note1) Actually, if we know in advance that (A) is always the same
100683 ** as (B) we only store (A), then duplicate (A) when pulling
100684 ** it out of the ephemeral table before calling VUpdate.
100685 */
100686 static void updateVirtualTable(
100687   Parse *pParse,       /* The parsing context */
100688   SrcList *pSrc,       /* The virtual table to be modified */
100689   Table *pTab,         /* The virtual table */
100690   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100691   Expr *pRowid,        /* Expression used to recompute the rowid */
100692   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100693   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100694   int onError          /* ON CONFLICT strategy */
100695 ){
100696   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
100697   ExprList *pEList = 0;     /* The result set of the SELECT statement */
100698   Select *pSelect = 0;      /* The SELECT statement */
100699   Expr *pExpr;              /* Temporary expression */
100700   int ephemTab;             /* Table holding the result of the SELECT */
100701   int i;                    /* Loop counter */
100702   int addr;                 /* Address of top of loop */
100703   int iReg;                 /* First register in set passed to OP_VUpdate */
100704   sqlcipher3 *db = pParse->db; /* Database connection */
100705   const char *pVTab = (const char*)sqlcipher3GetVTable(db, pTab);
100706   SelectDest dest;
100707
100708   /* Construct the SELECT statement that will find the new values for
100709   ** all updated rows. 
100710   */
100711   pEList = sqlcipher3ExprListAppend(pParse, 0, sqlcipher3Expr(db, TK_ID, "_rowid_"));
100712   if( pRowid ){
100713     pEList = sqlcipher3ExprListAppend(pParse, pEList,
100714                                    sqlcipher3ExprDup(db, pRowid, 0));
100715   }
100716   assert( pTab->iPKey<0 );
100717   for(i=0; i<pTab->nCol; i++){
100718     if( aXRef[i]>=0 ){
100719       pExpr = sqlcipher3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
100720     }else{
100721       pExpr = sqlcipher3Expr(db, TK_ID, pTab->aCol[i].zName);
100722     }
100723     pEList = sqlcipher3ExprListAppend(pParse, pEList, pExpr);
100724   }
100725   pSelect = sqlcipher3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
100726   
100727   /* Create the ephemeral table into which the update results will
100728   ** be stored.
100729   */
100730   assert( v );
100731   ephemTab = pParse->nTab++;
100732   sqlcipher3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
100733   sqlcipher3VdbeChangeP5(v, BTREE_UNORDERED);
100734
100735   /* fill the ephemeral table 
100736   */
100737   sqlcipher3SelectDestInit(&dest, SRT_Table, ephemTab);
100738   sqlcipher3Select(pParse, pSelect, &dest);
100739
100740   /* Generate code to scan the ephemeral table and call VUpdate. */
100741   iReg = ++pParse->nMem;
100742   pParse->nMem += pTab->nCol+1;
100743   addr = sqlcipher3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
100744   sqlcipher3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
100745   sqlcipher3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
100746   for(i=0; i<pTab->nCol; i++){
100747     sqlcipher3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
100748   }
100749   sqlcipher3VtabMakeWritable(pParse, pTab);
100750   sqlcipher3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
100751   sqlcipher3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
100752   sqlcipher3MayAbort(pParse);
100753   sqlcipher3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
100754   sqlcipher3VdbeJumpHere(v, addr);
100755   sqlcipher3VdbeAddOp2(v, OP_Close, ephemTab, 0);
100756
100757   /* Cleanup */
100758   sqlcipher3SelectDelete(db, pSelect);  
100759 }
100760 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
100761
100762 /************** End of update.c **********************************************/
100763 /************** Begin file vacuum.c ******************************************/
100764 /*
100765 ** 2003 April 6
100766 **
100767 ** The author disclaims copyright to this source code.  In place of
100768 ** a legal notice, here is a blessing:
100769 **
100770 **    May you do good and not evil.
100771 **    May you find forgiveness for yourself and forgive others.
100772 **    May you share freely, never taking more than you give.
100773 **
100774 *************************************************************************
100775 ** This file contains code used to implement the VACUUM command.
100776 **
100777 ** Most of the code in this file may be omitted by defining the
100778 ** SQLCIPHER_OMIT_VACUUM macro.
100779 */
100780
100781 #if !defined(SQLCIPHER_OMIT_VACUUM) && !defined(SQLCIPHER_OMIT_ATTACH)
100782 /*
100783 ** Finalize a prepared statement.  If there was an error, store the
100784 ** text of the error message in *pzErrMsg.  Return the result code.
100785 */
100786 static int vacuumFinalize(sqlcipher3 *db, sqlcipher3_stmt *pStmt, char **pzErrMsg){
100787   int rc;
100788   rc = sqlcipher3VdbeFinalize((Vdbe*)pStmt);
100789   if( rc ){
100790     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
100791   }
100792   return rc;
100793 }
100794
100795 /*
100796 ** Execute zSql on database db. Return an error code.
100797 */
100798 static int execSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
100799   sqlcipher3_stmt *pStmt;
100800   VVA_ONLY( int rc; )
100801   if( !zSql ){
100802     return SQLCIPHER_NOMEM;
100803   }
100804   if( SQLCIPHER_OK!=sqlcipher3_prepare(db, zSql, -1, &pStmt, 0) ){
100805     sqlcipher3SetString(pzErrMsg, db, sqlcipher3_errmsg(db));
100806     return sqlcipher3_errcode(db);
100807   }
100808   VVA_ONLY( rc = ) sqlcipher3_step(pStmt);
100809   assert( rc!=SQLCIPHER_ROW || (db->flags&SQLCIPHER_CountRows) );
100810   return vacuumFinalize(db, pStmt, pzErrMsg);
100811 }
100812
100813 /*
100814 ** Execute zSql on database db. The statement returns exactly
100815 ** one column. Execute this as SQL on the same database.
100816 */
100817 static int execExecSql(sqlcipher3 *db, char **pzErrMsg, const char *zSql){
100818   sqlcipher3_stmt *pStmt;
100819   int rc;
100820
100821   rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
100822   if( rc!=SQLCIPHER_OK ) return rc;
100823
100824   while( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
100825     rc = execSql(db, pzErrMsg, (char*)sqlcipher3_column_text(pStmt, 0));
100826     if( rc!=SQLCIPHER_OK ){
100827       vacuumFinalize(db, pStmt, pzErrMsg);
100828       return rc;
100829     }
100830   }
100831
100832   return vacuumFinalize(db, pStmt, pzErrMsg);
100833 }
100834
100835 /*
100836 ** The non-standard VACUUM command is used to clean up the database,
100837 ** collapse free space, etc.  It is modelled after the VACUUM command
100838 ** in PostgreSQL.
100839 **
100840 ** In version 1.0.x of SQLite, the VACUUM command would call
100841 ** gdbm_reorganize() on all the database tables.  But beginning
100842 ** with 2.0.0, SQLite no longer uses GDBM so this command has
100843 ** become a no-op.
100844 */
100845 SQLCIPHER_PRIVATE void sqlcipher3Vacuum(Parse *pParse){
100846   Vdbe *v = sqlcipher3GetVdbe(pParse);
100847   if( v ){
100848     sqlcipher3VdbeAddOp2(v, OP_Vacuum, 0, 0);
100849   }
100850   return;
100851 }
100852
100853 /*
100854 ** This routine implements the OP_Vacuum opcode of the VDBE.
100855 */
100856 SQLCIPHER_PRIVATE int sqlcipher3RunVacuum(char **pzErrMsg, sqlcipher3 *db){
100857   int rc = SQLCIPHER_OK;     /* Return code from service routines */
100858   Btree *pMain;           /* The database being vacuumed */
100859   Btree *pTemp;           /* The temporary database we vacuum into */
100860   char *zSql = 0;         /* SQL statements */
100861   int saved_flags;        /* Saved value of the db->flags */
100862   int saved_nChange;      /* Saved value of db->nChange */
100863   int saved_nTotalChange; /* Saved value of db->nTotalChange */
100864   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
100865   Db *pDb = 0;            /* Database to detach at end of vacuum */
100866   int isMemDb;            /* True if vacuuming a :memory: database */
100867   int nRes;               /* Bytes of reserved space at the end of each page */
100868   int nDb;                /* Number of attached databases */
100869
100870   if( !db->autoCommit ){
100871     sqlcipher3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
100872     return SQLCIPHER_ERROR;
100873   }
100874   if( db->activeVdbeCnt>1 ){
100875     sqlcipher3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
100876     return SQLCIPHER_ERROR;
100877   }
100878
100879   /* Save the current value of the database flags so that it can be 
100880   ** restored before returning. Then set the writable-schema flag, and
100881   ** disable CHECK and foreign key constraints.  */
100882   saved_flags = db->flags;
100883   saved_nChange = db->nChange;
100884   saved_nTotalChange = db->nTotalChange;
100885   saved_xTrace = db->xTrace;
100886   db->flags |= SQLCIPHER_WriteSchema | SQLCIPHER_IgnoreChecks | SQLCIPHER_PreferBuiltin;
100887   db->flags &= ~(SQLCIPHER_ForeignKeys | SQLCIPHER_ReverseOrder);
100888   db->xTrace = 0;
100889
100890   pMain = db->aDb[0].pBt;
100891   isMemDb = sqlcipher3PagerIsMemdb(sqlcipher3BtreePager(pMain));
100892
100893   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
100894   ** can be set to 'off' for this file, as it is not recovered if a crash
100895   ** occurs anyway. The integrity of the database is maintained by a
100896   ** (possibly synchronous) transaction opened on the main database before
100897   ** sqlcipher3BtreeCopyFile() is called.
100898   **
100899   ** An optimisation would be to use a non-journaled pager.
100900   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
100901   ** that actually made the VACUUM run slower.  Very little journalling
100902   ** actually occurs when doing a vacuum since the vacuum_db is initially
100903   ** empty.  Only the journal header is written.  Apparently it takes more
100904   ** time to parse and run the PRAGMA to turn journalling off than it does
100905   ** to write the journal header file.
100906   */
100907   nDb = db->nDb;
100908   if( sqlcipher3TempInMemory(db) ){
100909     zSql = "ATTACH ':memory:' AS vacuum_db;";
100910   }else{
100911     zSql = "ATTACH '' AS vacuum_db;";
100912   }
100913   rc = execSql(db, pzErrMsg, zSql);
100914   if( db->nDb>nDb ){
100915     pDb = &db->aDb[db->nDb-1];
100916     assert( strcmp(pDb->zName,"vacuum_db")==0 );
100917   }
100918   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100919   pTemp = db->aDb[db->nDb-1].pBt;
100920
100921   /* The call to execSql() to attach the temp database has left the file
100922   ** locked (as there was more than one active statement when the transaction
100923   ** to read the schema was concluded. Unlock it here so that this doesn't
100924   ** cause problems for the call to BtreeSetPageSize() below.  */
100925   sqlcipher3BtreeCommit(pTemp);
100926
100927   nRes = sqlcipher3BtreeGetReserve(pMain);
100928
100929   /* A VACUUM cannot change the pagesize of an encrypted database. */
100930 #ifdef SQLCIPHER_HAS_CODEC
100931   if( db->nextPagesize ){
100932     extern void sqlcipher3CodecGetKey(sqlcipher3*, int, void**, int*);
100933     int nKey = 0;
100934     char *zKey = NULL;
100935     sqlcipher3CodecGetKey(db, 0, (void**)&zKey, &nKey);
100936     if( nKey ) db->nextPagesize = 0;
100937   }
100938 #endif
100939
100940   /* Do not attempt to change the page size for a WAL database */
100941   if( sqlcipher3PagerGetJournalMode(sqlcipher3BtreePager(pMain))
100942                                                ==PAGER_JOURNALMODE_WAL ){
100943     db->nextPagesize = 0;
100944   }
100945
100946   if( sqlcipher3BtreeSetPageSize(pTemp, sqlcipher3BtreeGetPageSize(pMain), nRes, 0)
100947    || (!isMemDb && sqlcipher3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
100948    || NEVER(db->mallocFailed)
100949   ){
100950     rc = SQLCIPHER_NOMEM;
100951     goto end_of_vacuum;
100952   }
100953   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
100954   if( rc!=SQLCIPHER_OK ){
100955     goto end_of_vacuum;
100956   }
100957
100958 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
100959   sqlcipher3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
100960                                            sqlcipher3BtreeGetAutoVacuum(pMain));
100961 #endif
100962
100963   /* Begin a transaction */
100964   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
100965   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100966
100967   /* Query the schema of the main database. Create a mirror schema
100968   ** in the temporary database.
100969   */
100970   rc = execExecSql(db, pzErrMsg,
100971       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
100972       "  FROM sqlcipher_master WHERE type='table' AND name!='sqlcipher_sequence'"
100973       "   AND rootpage>0"
100974   );
100975   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100976   rc = execExecSql(db, pzErrMsg,
100977       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
100978       "  FROM sqlcipher_master WHERE sql LIKE 'CREATE INDEX %' ");
100979   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100980   rc = execExecSql(db, pzErrMsg,
100981       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
100982       "  FROM sqlcipher_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
100983   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100984
100985   /* Loop through the tables in the main database. For each, do
100986   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
100987   ** the contents to the temporary database.
100988   */
100989   rc = execExecSql(db, pzErrMsg,
100990       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
100991       "|| ' SELECT * FROM main.' || quote(name) || ';'"
100992       "FROM main.sqlcipher_master "
100993       "WHERE type = 'table' AND name!='sqlcipher_sequence' "
100994       "  AND rootpage>0"
100995   );
100996   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
100997
100998   /* Copy over the sequence table
100999   */
101000   rc = execExecSql(db, pzErrMsg,
101001       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
101002       "FROM vacuum_db.sqlcipher_master WHERE name='sqlcipher_sequence' "
101003   );
101004   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
101005   rc = execExecSql(db, pzErrMsg,
101006       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101007       "|| ' SELECT * FROM main.' || quote(name) || ';' "
101008       "FROM vacuum_db.sqlcipher_master WHERE name=='sqlcipher_sequence';"
101009   );
101010   if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
101011
101012
101013   /* Copy the triggers, views, and virtual tables from the main database
101014   ** over to the temporary database.  None of these objects has any
101015   ** associated storage, so all we have to do is copy their entries
101016   ** from the SQLCIPHER_MASTER table.
101017   */
101018   rc = execSql(db, pzErrMsg,
101019       "INSERT INTO vacuum_db.sqlcipher_master "
101020       "  SELECT type, name, tbl_name, rootpage, sql"
101021       "    FROM main.sqlcipher_master"
101022       "   WHERE type='view' OR type='trigger'"
101023       "      OR (type='table' AND rootpage=0)"
101024   );
101025   if( rc ) goto end_of_vacuum;
101026
101027   /* At this point, there is a write transaction open on both the 
101028   ** vacuum database and the main database. Assuming no error occurs,
101029   ** both transactions are closed by this block - the main database
101030   ** transaction by sqlcipher3BtreeCopyFile() and the other by an explicit
101031   ** call to sqlcipher3BtreeCommit().
101032   */
101033   {
101034     u32 meta;
101035     int i;
101036
101037     /* This array determines which meta meta values are preserved in the
101038     ** vacuum.  Even entries are the meta value number and odd entries
101039     ** are an increment to apply to the meta value after the vacuum.
101040     ** The increment is used to increase the schema cookie so that other
101041     ** connections to the same database will know to reread the schema.
101042     */
101043     static const unsigned char aCopy[] = {
101044        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101045        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101046        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101047        BTREE_USER_VERSION,       0,  /* Preserve the user version */
101048     };
101049
101050     assert( 1==sqlcipher3BtreeIsInTrans(pTemp) );
101051     assert( 1==sqlcipher3BtreeIsInTrans(pMain) );
101052
101053     /* Copy Btree meta values */
101054     for(i=0; i<ArraySize(aCopy); i+=2){
101055       /* GetMeta() and UpdateMeta() cannot fail in this context because
101056       ** we already have page 1 loaded into cache and marked dirty. */
101057       sqlcipher3BtreeGetMeta(pMain, aCopy[i], &meta);
101058       rc = sqlcipher3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101059       if( NEVER(rc!=SQLCIPHER_OK) ) goto end_of_vacuum;
101060     }
101061
101062     rc = sqlcipher3BtreeCopyFile(pMain, pTemp);
101063     if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
101064     rc = sqlcipher3BtreeCommit(pTemp);
101065     if( rc!=SQLCIPHER_OK ) goto end_of_vacuum;
101066 #ifndef SQLCIPHER_OMIT_AUTOVACUUM
101067     sqlcipher3BtreeSetAutoVacuum(pMain, sqlcipher3BtreeGetAutoVacuum(pTemp));
101068 #endif
101069   }
101070
101071   assert( rc==SQLCIPHER_OK );
101072   rc = sqlcipher3BtreeSetPageSize(pMain, sqlcipher3BtreeGetPageSize(pTemp), nRes,1);
101073
101074 end_of_vacuum:
101075   /* Restore the original value of db->flags */
101076   db->flags = saved_flags;
101077   db->nChange = saved_nChange;
101078   db->nTotalChange = saved_nTotalChange;
101079   db->xTrace = saved_xTrace;
101080   sqlcipher3BtreeSetPageSize(pMain, -1, -1, 1);
101081
101082   /* Currently there is an SQL level transaction open on the vacuum
101083   ** database. No locks are held on any other files (since the main file
101084   ** was committed at the btree level). So it safe to end the transaction
101085   ** by manually setting the autoCommit flag to true and detaching the
101086   ** vacuum database. The vacuum_db journal file is deleted when the pager
101087   ** is closed by the DETACH.
101088   */
101089   db->autoCommit = 1;
101090
101091   if( pDb ){
101092     sqlcipher3BtreeClose(pDb->pBt);
101093     pDb->pBt = 0;
101094     pDb->pSchema = 0;
101095   }
101096
101097   /* This both clears the schemas and reduces the size of the db->aDb[]
101098   ** array. */ 
101099   sqlcipher3ResetInternalSchema(db, -1);
101100
101101   return rc;
101102 }
101103
101104 #endif  /* SQLCIPHER_OMIT_VACUUM && SQLCIPHER_OMIT_ATTACH */
101105
101106 /************** End of vacuum.c **********************************************/
101107 /************** Begin file vtab.c ********************************************/
101108 /*
101109 ** 2006 June 10
101110 **
101111 ** The author disclaims copyright to this source code.  In place of
101112 ** a legal notice, here is a blessing:
101113 **
101114 **    May you do good and not evil.
101115 **    May you find forgiveness for yourself and forgive others.
101116 **    May you share freely, never taking more than you give.
101117 **
101118 *************************************************************************
101119 ** This file contains code used to help implement virtual tables.
101120 */
101121 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
101122
101123 /*
101124 ** Before a virtual table xCreate() or xConnect() method is invoked, the
101125 ** sqlcipher3.pVtabCtx member variable is set to point to an instance of
101126 ** this struct allocated on the stack. It is used by the implementation of 
101127 ** the sqlcipher3_declare_vtab() and sqlcipher3_vtab_config() APIs, both of which
101128 ** are invoked only from within xCreate and xConnect methods.
101129 */
101130 struct VtabCtx {
101131   Table *pTab;
101132   VTable *pVTable;
101133 };
101134
101135 /*
101136 ** The actual function that does the work of creating a new module.
101137 ** This function implements the sqlcipher3_create_module() and
101138 ** sqlcipher3_create_module_v2() interfaces.
101139 */
101140 static int createModule(
101141   sqlcipher3 *db,                    /* Database in which module is registered */
101142   const char *zName,              /* Name assigned to this module */
101143   const sqlcipher3_module *pModule,  /* The definition of the module */
101144   void *pAux,                     /* Context pointer for xCreate/xConnect */
101145   void (*xDestroy)(void *)        /* Module destructor function */
101146 ){
101147   int rc, nName;
101148   Module *pMod;
101149
101150   sqlcipher3_mutex_enter(db->mutex);
101151   nName = sqlcipher3Strlen30(zName);
101152   pMod = (Module *)sqlcipher3DbMallocRaw(db, sizeof(Module) + nName + 1);
101153   if( pMod ){
101154     Module *pDel;
101155     char *zCopy = (char *)(&pMod[1]);
101156     memcpy(zCopy, zName, nName+1);
101157     pMod->zName = zCopy;
101158     pMod->pModule = pModule;
101159     pMod->pAux = pAux;
101160     pMod->xDestroy = xDestroy;
101161     pDel = (Module *)sqlcipher3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
101162     if( pDel && pDel->xDestroy ){
101163       sqlcipher3ResetInternalSchema(db, -1);
101164       pDel->xDestroy(pDel->pAux);
101165     }
101166     sqlcipher3DbFree(db, pDel);
101167     if( pDel==pMod ){
101168       db->mallocFailed = 1;
101169     }
101170   }else if( xDestroy ){
101171     xDestroy(pAux);
101172   }
101173   rc = sqlcipher3ApiExit(db, SQLCIPHER_OK);
101174   sqlcipher3_mutex_leave(db->mutex);
101175   return rc;
101176 }
101177
101178
101179 /*
101180 ** External API function used to create a new virtual-table module.
101181 */
101182 SQLCIPHER_API int sqlcipher3_create_module(
101183   sqlcipher3 *db,                    /* Database in which module is registered */
101184   const char *zName,              /* Name assigned to this module */
101185   const sqlcipher3_module *pModule,  /* The definition of the module */
101186   void *pAux                      /* Context pointer for xCreate/xConnect */
101187 ){
101188   return createModule(db, zName, pModule, pAux, 0);
101189 }
101190
101191 /*
101192 ** External API function used to create a new virtual-table module.
101193 */
101194 SQLCIPHER_API int sqlcipher3_create_module_v2(
101195   sqlcipher3 *db,                    /* Database in which module is registered */
101196   const char *zName,              /* Name assigned to this module */
101197   const sqlcipher3_module *pModule,  /* The definition of the module */
101198   void *pAux,                     /* Context pointer for xCreate/xConnect */
101199   void (*xDestroy)(void *)        /* Module destructor function */
101200 ){
101201   return createModule(db, zName, pModule, pAux, xDestroy);
101202 }
101203
101204 /*
101205 ** Lock the virtual table so that it cannot be disconnected.
101206 ** Locks nest.  Every lock should have a corresponding unlock.
101207 ** If an unlock is omitted, resources leaks will occur.  
101208 **
101209 ** If a disconnect is attempted while a virtual table is locked,
101210 ** the disconnect is deferred until all locks have been removed.
101211 */
101212 SQLCIPHER_PRIVATE void sqlcipher3VtabLock(VTable *pVTab){
101213   pVTab->nRef++;
101214 }
101215
101216
101217 /*
101218 ** pTab is a pointer to a Table structure representing a virtual-table.
101219 ** Return a pointer to the VTable object used by connection db to access 
101220 ** this virtual-table, if one has been created, or NULL otherwise.
101221 */
101222 SQLCIPHER_PRIVATE VTable *sqlcipher3GetVTable(sqlcipher3 *db, Table *pTab){
101223   VTable *pVtab;
101224   assert( IsVirtual(pTab) );
101225   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101226   return pVtab;
101227 }
101228
101229 /*
101230 ** Decrement the ref-count on a virtual table object. When the ref-count
101231 ** reaches zero, call the xDisconnect() method to delete the object.
101232 */
101233 SQLCIPHER_PRIVATE void sqlcipher3VtabUnlock(VTable *pVTab){
101234   sqlcipher3 *db = pVTab->db;
101235
101236   assert( db );
101237   assert( pVTab->nRef>0 );
101238   assert( sqlcipher3SafetyCheckOk(db) );
101239
101240   pVTab->nRef--;
101241   if( pVTab->nRef==0 ){
101242     sqlcipher3_vtab *p = pVTab->pVtab;
101243     if( p ){
101244       p->pModule->xDisconnect(p);
101245     }
101246     sqlcipher3DbFree(db, pVTab);
101247   }
101248 }
101249
101250 /*
101251 ** Table p is a virtual table. This function moves all elements in the
101252 ** p->pVTable list to the sqlcipher3.pDisconnect lists of their associated
101253 ** database connections to be disconnected at the next opportunity. 
101254 ** Except, if argument db is not NULL, then the entry associated with
101255 ** connection db is left in the p->pVTable list.
101256 */
101257 static VTable *vtabDisconnectAll(sqlcipher3 *db, Table *p){
101258   VTable *pRet = 0;
101259   VTable *pVTable = p->pVTable;
101260   p->pVTable = 0;
101261
101262   /* Assert that the mutex (if any) associated with the BtShared database 
101263   ** that contains table p is held by the caller. See header comments 
101264   ** above function sqlcipher3VtabUnlockList() for an explanation of why
101265   ** this makes it safe to access the sqlcipher3.pDisconnect list of any
101266   ** database connection that may have an entry in the p->pVTable list.
101267   */
101268   assert( db==0 || sqlcipher3SchemaMutexHeld(db, 0, p->pSchema) );
101269
101270   while( pVTable ){
101271     sqlcipher3 *db2 = pVTable->db;
101272     VTable *pNext = pVTable->pNext;
101273     assert( db2 );
101274     if( db2==db ){
101275       pRet = pVTable;
101276       p->pVTable = pRet;
101277       pRet->pNext = 0;
101278     }else{
101279       pVTable->pNext = db2->pDisconnect;
101280       db2->pDisconnect = pVTable;
101281     }
101282     pVTable = pNext;
101283   }
101284
101285   assert( !db || pRet );
101286   return pRet;
101287 }
101288
101289
101290 /*
101291 ** Disconnect all the virtual table objects in the sqlcipher3.pDisconnect list.
101292 **
101293 ** This function may only be called when the mutexes associated with all
101294 ** shared b-tree databases opened using connection db are held by the 
101295 ** caller. This is done to protect the sqlcipher3.pDisconnect list. The
101296 ** sqlcipher3.pDisconnect list is accessed only as follows:
101297 **
101298 **   1) By this function. In this case, all BtShared mutexes and the mutex
101299 **      associated with the database handle itself must be held.
101300 **
101301 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
101302 **      the sqlcipher3.pDisconnect list. In this case either the BtShared mutex
101303 **      associated with the database the virtual table is stored in is held
101304 **      or, if the virtual table is stored in a non-sharable database, then
101305 **      the database handle mutex is held.
101306 **
101307 ** As a result, a sqlcipher3.pDisconnect cannot be accessed simultaneously 
101308 ** by multiple threads. It is thread-safe.
101309 */
101310 SQLCIPHER_PRIVATE void sqlcipher3VtabUnlockList(sqlcipher3 *db){
101311   VTable *p = db->pDisconnect;
101312   db->pDisconnect = 0;
101313
101314   assert( sqlcipher3BtreeHoldsAllMutexes(db) );
101315   assert( sqlcipher3_mutex_held(db->mutex) );
101316
101317   if( p ){
101318     sqlcipher3ExpirePreparedStatements(db);
101319     do {
101320       VTable *pNext = p->pNext;
101321       sqlcipher3VtabUnlock(p);
101322       p = pNext;
101323     }while( p );
101324   }
101325 }
101326
101327 /*
101328 ** Clear any and all virtual-table information from the Table record.
101329 ** This routine is called, for example, just before deleting the Table
101330 ** record.
101331 **
101332 ** Since it is a virtual-table, the Table structure contains a pointer
101333 ** to the head of a linked list of VTable structures. Each VTable 
101334 ** structure is associated with a single sqlcipher3* user of the schema.
101335 ** The reference count of the VTable structure associated with database 
101336 ** connection db is decremented immediately (which may lead to the 
101337 ** structure being xDisconnected and free). Any other VTable structures
101338 ** in the list are moved to the sqlcipher3.pDisconnect list of the associated 
101339 ** database connection.
101340 */
101341 SQLCIPHER_PRIVATE void sqlcipher3VtabClear(sqlcipher3 *db, Table *p){
101342   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
101343   if( p->azModuleArg ){
101344     int i;
101345     for(i=0; i<p->nModuleArg; i++){
101346       sqlcipher3DbFree(db, p->azModuleArg[i]);
101347     }
101348     sqlcipher3DbFree(db, p->azModuleArg);
101349   }
101350 }
101351
101352 /*
101353 ** Add a new module argument to pTable->azModuleArg[].
101354 ** The string is not copied - the pointer is stored.  The
101355 ** string will be freed automatically when the table is
101356 ** deleted.
101357 */
101358 static void addModuleArgument(sqlcipher3 *db, Table *pTable, char *zArg){
101359   int i = pTable->nModuleArg++;
101360   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
101361   char **azModuleArg;
101362   azModuleArg = sqlcipher3DbRealloc(db, pTable->azModuleArg, nBytes);
101363   if( azModuleArg==0 ){
101364     int j;
101365     for(j=0; j<i; j++){
101366       sqlcipher3DbFree(db, pTable->azModuleArg[j]);
101367     }
101368     sqlcipher3DbFree(db, zArg);
101369     sqlcipher3DbFree(db, pTable->azModuleArg);
101370     pTable->nModuleArg = 0;
101371   }else{
101372     azModuleArg[i] = zArg;
101373     azModuleArg[i+1] = 0;
101374   }
101375   pTable->azModuleArg = azModuleArg;
101376 }
101377
101378 /*
101379 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
101380 ** statement.  The module name has been parsed, but the optional list
101381 ** of parameters that follow the module name are still pending.
101382 */
101383 SQLCIPHER_PRIVATE void sqlcipher3VtabBeginParse(
101384   Parse *pParse,        /* Parsing context */
101385   Token *pName1,        /* Name of new table, or database name */
101386   Token *pName2,        /* Name of new table or NULL */
101387   Token *pModuleName    /* Name of the module for the virtual table */
101388 ){
101389   int iDb;              /* The database the table is being created in */
101390   Table *pTable;        /* The new virtual table */
101391   sqlcipher3 *db;          /* Database connection */
101392
101393   sqlcipher3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
101394   pTable = pParse->pNewTable;
101395   if( pTable==0 ) return;
101396   assert( 0==pTable->pIndex );
101397
101398   db = pParse->db;
101399   iDb = sqlcipher3SchemaToIndex(db, pTable->pSchema);
101400   assert( iDb>=0 );
101401
101402   pTable->tabFlags |= TF_Virtual;
101403   pTable->nModuleArg = 0;
101404   addModuleArgument(db, pTable, sqlcipher3NameFromToken(db, pModuleName));
101405   addModuleArgument(db, pTable, sqlcipher3DbStrDup(db, db->aDb[iDb].zName));
101406   addModuleArgument(db, pTable, sqlcipher3DbStrDup(db, pTable->zName));
101407   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
101408
101409 #ifndef SQLCIPHER_OMIT_AUTHORIZATION
101410   /* Creating a virtual table invokes the authorization callback twice.
101411   ** The first invocation, to obtain permission to INSERT a row into the
101412   ** sqlcipher_master table, has already been made by sqlcipher3StartTable().
101413   ** The second call, to obtain permission to create the table, is made now.
101414   */
101415   if( pTable->azModuleArg ){
101416     sqlcipher3AuthCheck(pParse, SQLCIPHER_CREATE_VTABLE, pTable->zName, 
101417             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
101418   }
101419 #endif
101420 }
101421
101422 /*
101423 ** This routine takes the module argument that has been accumulating
101424 ** in pParse->zArg[] and appends it to the list of arguments on the
101425 ** virtual table currently under construction in pParse->pTable.
101426 */
101427 static void addArgumentToVtab(Parse *pParse){
101428   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
101429     const char *z = (const char*)pParse->sArg.z;
101430     int n = pParse->sArg.n;
101431     sqlcipher3 *db = pParse->db;
101432     addModuleArgument(db, pParse->pNewTable, sqlcipher3DbStrNDup(db, z, n));
101433   }
101434 }
101435
101436 /*
101437 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
101438 ** has been completely parsed.
101439 */
101440 SQLCIPHER_PRIVATE void sqlcipher3VtabFinishParse(Parse *pParse, Token *pEnd){
101441   Table *pTab = pParse->pNewTable;  /* The table being constructed */
101442   sqlcipher3 *db = pParse->db;         /* The database connection */
101443
101444   if( pTab==0 ) return;
101445   addArgumentToVtab(pParse);
101446   pParse->sArg.z = 0;
101447   if( pTab->nModuleArg<1 ) return;
101448   
101449   /* If the CREATE VIRTUAL TABLE statement is being entered for the
101450   ** first time (in other words if the virtual table is actually being
101451   ** created now instead of just being read out of sqlcipher_master) then
101452   ** do additional initialization work and store the statement text
101453   ** in the sqlcipher_master table.
101454   */
101455   if( !db->init.busy ){
101456     char *zStmt;
101457     char *zWhere;
101458     int iDb;
101459     Vdbe *v;
101460
101461     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
101462     if( pEnd ){
101463       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
101464     }
101465     zStmt = sqlcipher3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
101466
101467     /* A slot for the record has already been allocated in the 
101468     ** SQLCIPHER_MASTER table.  We just need to update that slot with all
101469     ** the information we've collected.  
101470     **
101471     ** The VM register number pParse->regRowid holds the rowid of an
101472     ** entry in the sqlcipher_master table tht was created for this vtab
101473     ** by sqlcipher3StartTable().
101474     */
101475     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
101476     sqlcipher3NestedParse(pParse,
101477       "UPDATE %Q.%s "
101478          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
101479        "WHERE rowid=#%d",
101480       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
101481       pTab->zName,
101482       pTab->zName,
101483       zStmt,
101484       pParse->regRowid
101485     );
101486     sqlcipher3DbFree(db, zStmt);
101487     v = sqlcipher3GetVdbe(pParse);
101488     sqlcipher3ChangeCookie(pParse, iDb);
101489
101490     sqlcipher3VdbeAddOp2(v, OP_Expire, 0, 0);
101491     zWhere = sqlcipher3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
101492     sqlcipher3VdbeAddParseSchemaOp(v, iDb, zWhere);
101493     sqlcipher3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
101494                          pTab->zName, sqlcipher3Strlen30(pTab->zName) + 1);
101495   }
101496
101497   /* If we are rereading the sqlcipher_master table create the in-memory
101498   ** record of the table. The xConnect() method is not called until
101499   ** the first time the virtual table is used in an SQL statement. This
101500   ** allows a schema that contains virtual tables to be loaded before
101501   ** the required virtual table implementations are registered.  */
101502   else {
101503     Table *pOld;
101504     Schema *pSchema = pTab->pSchema;
101505     const char *zName = pTab->zName;
101506     int nName = sqlcipher3Strlen30(zName);
101507     assert( sqlcipher3SchemaMutexHeld(db, 0, pSchema) );
101508     pOld = sqlcipher3HashInsert(&pSchema->tblHash, zName, nName, pTab);
101509     if( pOld ){
101510       db->mallocFailed = 1;
101511       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
101512       return;
101513     }
101514     pParse->pNewTable = 0;
101515   }
101516 }
101517
101518 /*
101519 ** The parser calls this routine when it sees the first token
101520 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
101521 */
101522 SQLCIPHER_PRIVATE void sqlcipher3VtabArgInit(Parse *pParse){
101523   addArgumentToVtab(pParse);
101524   pParse->sArg.z = 0;
101525   pParse->sArg.n = 0;
101526 }
101527
101528 /*
101529 ** The parser calls this routine for each token after the first token
101530 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
101531 */
101532 SQLCIPHER_PRIVATE void sqlcipher3VtabArgExtend(Parse *pParse, Token *p){
101533   Token *pArg = &pParse->sArg;
101534   if( pArg->z==0 ){
101535     pArg->z = p->z;
101536     pArg->n = p->n;
101537   }else{
101538     assert(pArg->z < p->z);
101539     pArg->n = (int)(&p->z[p->n] - pArg->z);
101540   }
101541 }
101542
101543 /*
101544 ** Invoke a virtual table constructor (either xCreate or xConnect). The
101545 ** pointer to the function to invoke is passed as the fourth parameter
101546 ** to this procedure.
101547 */
101548 static int vtabCallConstructor(
101549   sqlcipher3 *db, 
101550   Table *pTab,
101551   Module *pMod,
101552   int (*xConstruct)(sqlcipher3*,void*,int,const char*const*,sqlcipher3_vtab**,char**),
101553   char **pzErr
101554 ){
101555   VtabCtx sCtx;
101556   VTable *pVTable;
101557   int rc;
101558   const char *const*azArg = (const char *const*)pTab->azModuleArg;
101559   int nArg = pTab->nModuleArg;
101560   char *zErr = 0;
101561   char *zModuleName = sqlcipher3MPrintf(db, "%s", pTab->zName);
101562
101563   if( !zModuleName ){
101564     return SQLCIPHER_NOMEM;
101565   }
101566
101567   pVTable = sqlcipher3DbMallocZero(db, sizeof(VTable));
101568   if( !pVTable ){
101569     sqlcipher3DbFree(db, zModuleName);
101570     return SQLCIPHER_NOMEM;
101571   }
101572   pVTable->db = db;
101573   pVTable->pMod = pMod;
101574
101575   /* Invoke the virtual table constructor */
101576   assert( &db->pVtabCtx );
101577   assert( xConstruct );
101578   sCtx.pTab = pTab;
101579   sCtx.pVTable = pVTable;
101580   db->pVtabCtx = &sCtx;
101581   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
101582   db->pVtabCtx = 0;
101583   if( rc==SQLCIPHER_NOMEM ) db->mallocFailed = 1;
101584
101585   if( SQLCIPHER_OK!=rc ){
101586     if( zErr==0 ){
101587       *pzErr = sqlcipher3MPrintf(db, "vtable constructor failed: %s", zModuleName);
101588     }else {
101589       *pzErr = sqlcipher3MPrintf(db, "%s", zErr);
101590       sqlcipher3_free(zErr);
101591     }
101592     sqlcipher3DbFree(db, pVTable);
101593   }else if( ALWAYS(pVTable->pVtab) ){
101594     /* Justification of ALWAYS():  A correct vtab constructor must allocate
101595     ** the sqlcipher3_vtab object if successful.  */
101596     pVTable->pVtab->pModule = pMod->pModule;
101597     pVTable->nRef = 1;
101598     if( sCtx.pTab ){
101599       const char *zFormat = "vtable constructor did not declare schema: %s";
101600       *pzErr = sqlcipher3MPrintf(db, zFormat, pTab->zName);
101601       sqlcipher3VtabUnlock(pVTable);
101602       rc = SQLCIPHER_ERROR;
101603     }else{
101604       int iCol;
101605       /* If everything went according to plan, link the new VTable structure
101606       ** into the linked list headed by pTab->pVTable. Then loop through the 
101607       ** columns of the table to see if any of them contain the token "hidden".
101608       ** If so, set the Column.isHidden flag and remove the token from
101609       ** the type string.  */
101610       pVTable->pNext = pTab->pVTable;
101611       pTab->pVTable = pVTable;
101612
101613       for(iCol=0; iCol<pTab->nCol; iCol++){
101614         char *zType = pTab->aCol[iCol].zType;
101615         int nType;
101616         int i = 0;
101617         if( !zType ) continue;
101618         nType = sqlcipher3Strlen30(zType);
101619         if( sqlcipher3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
101620           for(i=0; i<nType; i++){
101621             if( (0==sqlcipher3StrNICmp(" hidden", &zType[i], 7))
101622              && (zType[i+7]=='\0' || zType[i+7]==' ')
101623             ){
101624               i++;
101625               break;
101626             }
101627           }
101628         }
101629         if( i<nType ){
101630           int j;
101631           int nDel = 6 + (zType[i+6] ? 1 : 0);
101632           for(j=i; (j+nDel)<=nType; j++){
101633             zType[j] = zType[j+nDel];
101634           }
101635           if( zType[i]=='\0' && i>0 ){
101636             assert(zType[i-1]==' ');
101637             zType[i-1] = '\0';
101638           }
101639           pTab->aCol[iCol].isHidden = 1;
101640         }
101641       }
101642     }
101643   }
101644
101645   sqlcipher3DbFree(db, zModuleName);
101646   return rc;
101647 }
101648
101649 /*
101650 ** This function is invoked by the parser to call the xConnect() method
101651 ** of the virtual table pTab. If an error occurs, an error code is returned 
101652 ** and an error left in pParse.
101653 **
101654 ** This call is a no-op if table pTab is not a virtual table.
101655 */
101656 SQLCIPHER_PRIVATE int sqlcipher3VtabCallConnect(Parse *pParse, Table *pTab){
101657   sqlcipher3 *db = pParse->db;
101658   const char *zMod;
101659   Module *pMod;
101660   int rc;
101661
101662   assert( pTab );
101663   if( (pTab->tabFlags & TF_Virtual)==0 || sqlcipher3GetVTable(db, pTab) ){
101664     return SQLCIPHER_OK;
101665   }
101666
101667   /* Locate the required virtual table module */
101668   zMod = pTab->azModuleArg[0];
101669   pMod = (Module*)sqlcipher3HashFind(&db->aModule, zMod, sqlcipher3Strlen30(zMod));
101670
101671   if( !pMod ){
101672     const char *zModule = pTab->azModuleArg[0];
101673     sqlcipher3ErrorMsg(pParse, "no such module: %s", zModule);
101674     rc = SQLCIPHER_ERROR;
101675   }else{
101676     char *zErr = 0;
101677     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
101678     if( rc!=SQLCIPHER_OK ){
101679       sqlcipher3ErrorMsg(pParse, "%s", zErr);
101680     }
101681     sqlcipher3DbFree(db, zErr);
101682   }
101683
101684   return rc;
101685 }
101686 /*
101687 ** Grow the db->aVTrans[] array so that there is room for at least one
101688 ** more v-table. Return SQLCIPHER_NOMEM if a malloc fails, or SQLCIPHER_OK otherwise.
101689 */
101690 static int growVTrans(sqlcipher3 *db){
101691   const int ARRAY_INCR = 5;
101692
101693   /* Grow the sqlcipher3.aVTrans array if required */
101694   if( (db->nVTrans%ARRAY_INCR)==0 ){
101695     VTable **aVTrans;
101696     int nBytes = sizeof(sqlcipher3_vtab *) * (db->nVTrans + ARRAY_INCR);
101697     aVTrans = sqlcipher3DbRealloc(db, (void *)db->aVTrans, nBytes);
101698     if( !aVTrans ){
101699       return SQLCIPHER_NOMEM;
101700     }
101701     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlcipher3_vtab *)*ARRAY_INCR);
101702     db->aVTrans = aVTrans;
101703   }
101704
101705   return SQLCIPHER_OK;
101706 }
101707
101708 /*
101709 ** Add the virtual table pVTab to the array sqlcipher3.aVTrans[]. Space should
101710 ** have already been reserved using growVTrans().
101711 */
101712 static void addToVTrans(sqlcipher3 *db, VTable *pVTab){
101713   /* Add pVtab to the end of sqlcipher3.aVTrans */
101714   db->aVTrans[db->nVTrans++] = pVTab;
101715   sqlcipher3VtabLock(pVTab);
101716 }
101717
101718 /*
101719 ** This function is invoked by the vdbe to call the xCreate method
101720 ** of the virtual table named zTab in database iDb. 
101721 **
101722 ** If an error occurs, *pzErr is set to point an an English language
101723 ** description of the error and an SQLCIPHER_XXX error code is returned.
101724 ** In this case the caller must call sqlcipher3DbFree(db, ) on *pzErr.
101725 */
101726 SQLCIPHER_PRIVATE int sqlcipher3VtabCallCreate(sqlcipher3 *db, int iDb, const char *zTab, char **pzErr){
101727   int rc = SQLCIPHER_OK;
101728   Table *pTab;
101729   Module *pMod;
101730   const char *zMod;
101731
101732   pTab = sqlcipher3FindTable(db, zTab, db->aDb[iDb].zName);
101733   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
101734
101735   /* Locate the required virtual table module */
101736   zMod = pTab->azModuleArg[0];
101737   pMod = (Module*)sqlcipher3HashFind(&db->aModule, zMod, sqlcipher3Strlen30(zMod));
101738
101739   /* If the module has been registered and includes a Create method, 
101740   ** invoke it now. If the module has not been registered, return an 
101741   ** error. Otherwise, do nothing.
101742   */
101743   if( !pMod ){
101744     *pzErr = sqlcipher3MPrintf(db, "no such module: %s", zMod);
101745     rc = SQLCIPHER_ERROR;
101746   }else{
101747     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
101748   }
101749
101750   /* Justification of ALWAYS():  The xConstructor method is required to
101751   ** create a valid sqlcipher3_vtab if it returns SQLCIPHER_OK. */
101752   if( rc==SQLCIPHER_OK && ALWAYS(sqlcipher3GetVTable(db, pTab)) ){
101753     rc = growVTrans(db);
101754     if( rc==SQLCIPHER_OK ){
101755       addToVTrans(db, sqlcipher3GetVTable(db, pTab));
101756     }
101757   }
101758
101759   return rc;
101760 }
101761
101762 /*
101763 ** This function is used to set the schema of a virtual table.  It is only
101764 ** valid to call this function from within the xCreate() or xConnect() of a
101765 ** virtual table module.
101766 */
101767 SQLCIPHER_API int sqlcipher3_declare_vtab(sqlcipher3 *db, const char *zCreateTable){
101768   Parse *pParse;
101769
101770   int rc = SQLCIPHER_OK;
101771   Table *pTab;
101772   char *zErr = 0;
101773
101774   sqlcipher3_mutex_enter(db->mutex);
101775   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
101776     sqlcipher3Error(db, SQLCIPHER_MISUSE, 0);
101777     sqlcipher3_mutex_leave(db->mutex);
101778     return SQLCIPHER_MISUSE_BKPT;
101779   }
101780   assert( (pTab->tabFlags & TF_Virtual)!=0 );
101781
101782   pParse = sqlcipher3StackAllocZero(db, sizeof(*pParse));
101783   if( pParse==0 ){
101784     rc = SQLCIPHER_NOMEM;
101785   }else{
101786     pParse->declareVtab = 1;
101787     pParse->db = db;
101788     pParse->nQueryLoop = 1;
101789   
101790     if( SQLCIPHER_OK==sqlcipher3RunParser(pParse, zCreateTable, &zErr) 
101791      && pParse->pNewTable
101792      && !db->mallocFailed
101793      && !pParse->pNewTable->pSelect
101794      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
101795     ){
101796       if( !pTab->aCol ){
101797         pTab->aCol = pParse->pNewTable->aCol;
101798         pTab->nCol = pParse->pNewTable->nCol;
101799         pParse->pNewTable->nCol = 0;
101800         pParse->pNewTable->aCol = 0;
101801       }
101802       db->pVtabCtx->pTab = 0;
101803     }else{
101804       sqlcipher3Error(db, SQLCIPHER_ERROR, (zErr ? "%s" : 0), zErr);
101805       sqlcipher3DbFree(db, zErr);
101806       rc = SQLCIPHER_ERROR;
101807     }
101808     pParse->declareVtab = 0;
101809   
101810     if( pParse->pVdbe ){
101811       sqlcipher3VdbeFinalize(pParse->pVdbe);
101812     }
101813     sqlcipher3DeleteTable(db, pParse->pNewTable);
101814     sqlcipher3StackFree(db, pParse);
101815   }
101816
101817   assert( (rc&0xff)==rc );
101818   rc = sqlcipher3ApiExit(db, rc);
101819   sqlcipher3_mutex_leave(db->mutex);
101820   return rc;
101821 }
101822
101823 /*
101824 ** This function is invoked by the vdbe to call the xDestroy method
101825 ** of the virtual table named zTab in database iDb. This occurs
101826 ** when a DROP TABLE is mentioned.
101827 **
101828 ** This call is a no-op if zTab is not a virtual table.
101829 */
101830 SQLCIPHER_PRIVATE int sqlcipher3VtabCallDestroy(sqlcipher3 *db, int iDb, const char *zTab){
101831   int rc = SQLCIPHER_OK;
101832   Table *pTab;
101833
101834   pTab = sqlcipher3FindTable(db, zTab, db->aDb[iDb].zName);
101835   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
101836     VTable *p = vtabDisconnectAll(db, pTab);
101837
101838     assert( rc==SQLCIPHER_OK );
101839     rc = p->pMod->pModule->xDestroy(p->pVtab);
101840
101841     /* Remove the sqlcipher3_vtab* from the aVTrans[] array, if applicable */
101842     if( rc==SQLCIPHER_OK ){
101843       assert( pTab->pVTable==p && p->pNext==0 );
101844       p->pVtab = 0;
101845       pTab->pVTable = 0;
101846       sqlcipher3VtabUnlock(p);
101847     }
101848   }
101849
101850   return rc;
101851 }
101852
101853 /*
101854 ** This function invokes either the xRollback or xCommit method
101855 ** of each of the virtual tables in the sqlcipher3.aVTrans array. The method
101856 ** called is identified by the second argument, "offset", which is
101857 ** the offset of the method to call in the sqlcipher3_module structure.
101858 **
101859 ** The array is cleared after invoking the callbacks. 
101860 */
101861 static void callFinaliser(sqlcipher3 *db, int offset){
101862   int i;
101863   if( db->aVTrans ){
101864     for(i=0; i<db->nVTrans; i++){
101865       VTable *pVTab = db->aVTrans[i];
101866       sqlcipher3_vtab *p = pVTab->pVtab;
101867       if( p ){
101868         int (*x)(sqlcipher3_vtab *);
101869         x = *(int (**)(sqlcipher3_vtab *))((char *)p->pModule + offset);
101870         if( x ) x(p);
101871       }
101872       pVTab->iSavepoint = 0;
101873       sqlcipher3VtabUnlock(pVTab);
101874     }
101875     sqlcipher3DbFree(db, db->aVTrans);
101876     db->nVTrans = 0;
101877     db->aVTrans = 0;
101878   }
101879 }
101880
101881 /*
101882 ** Invoke the xSync method of all virtual tables in the sqlcipher3.aVTrans
101883 ** array. Return the error code for the first error that occurs, or
101884 ** SQLCIPHER_OK if all xSync operations are successful.
101885 **
101886 ** Set *pzErrmsg to point to a buffer that should be released using 
101887 ** sqlcipher3DbFree() containing an error message, if one is available.
101888 */
101889 SQLCIPHER_PRIVATE int sqlcipher3VtabSync(sqlcipher3 *db, char **pzErrmsg){
101890   int i;
101891   int rc = SQLCIPHER_OK;
101892   VTable **aVTrans = db->aVTrans;
101893
101894   db->aVTrans = 0;
101895   for(i=0; rc==SQLCIPHER_OK && i<db->nVTrans; i++){
101896     int (*x)(sqlcipher3_vtab *);
101897     sqlcipher3_vtab *pVtab = aVTrans[i]->pVtab;
101898     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
101899       rc = x(pVtab);
101900       sqlcipher3DbFree(db, *pzErrmsg);
101901       *pzErrmsg = sqlcipher3DbStrDup(db, pVtab->zErrMsg);
101902       sqlcipher3_free(pVtab->zErrMsg);
101903     }
101904   }
101905   db->aVTrans = aVTrans;
101906   return rc;
101907 }
101908
101909 /*
101910 ** Invoke the xRollback method of all virtual tables in the 
101911 ** sqlcipher3.aVTrans array. Then clear the array itself.
101912 */
101913 SQLCIPHER_PRIVATE int sqlcipher3VtabRollback(sqlcipher3 *db){
101914   callFinaliser(db, offsetof(sqlcipher3_module,xRollback));
101915   return SQLCIPHER_OK;
101916 }
101917
101918 /*
101919 ** Invoke the xCommit method of all virtual tables in the 
101920 ** sqlcipher3.aVTrans array. Then clear the array itself.
101921 */
101922 SQLCIPHER_PRIVATE int sqlcipher3VtabCommit(sqlcipher3 *db){
101923   callFinaliser(db, offsetof(sqlcipher3_module,xCommit));
101924   return SQLCIPHER_OK;
101925 }
101926
101927 /*
101928 ** If the virtual table pVtab supports the transaction interface
101929 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
101930 ** not currently open, invoke the xBegin method now.
101931 **
101932 ** If the xBegin call is successful, place the sqlcipher3_vtab pointer
101933 ** in the sqlcipher3.aVTrans array.
101934 */
101935 SQLCIPHER_PRIVATE int sqlcipher3VtabBegin(sqlcipher3 *db, VTable *pVTab){
101936   int rc = SQLCIPHER_OK;
101937   const sqlcipher3_module *pModule;
101938
101939   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
101940   ** than zero, then this function is being called from within a
101941   ** virtual module xSync() callback. It is illegal to write to 
101942   ** virtual module tables in this case, so return SQLCIPHER_LOCKED.
101943   */
101944   if( sqlcipher3VtabInSync(db) ){
101945     return SQLCIPHER_LOCKED;
101946   }
101947   if( !pVTab ){
101948     return SQLCIPHER_OK;
101949   } 
101950   pModule = pVTab->pVtab->pModule;
101951
101952   if( pModule->xBegin ){
101953     int i;
101954
101955     /* If pVtab is already in the aVTrans array, return early */
101956     for(i=0; i<db->nVTrans; i++){
101957       if( db->aVTrans[i]==pVTab ){
101958         return SQLCIPHER_OK;
101959       }
101960     }
101961
101962     /* Invoke the xBegin method. If successful, add the vtab to the 
101963     ** sqlcipher3.aVTrans[] array. */
101964     rc = growVTrans(db);
101965     if( rc==SQLCIPHER_OK ){
101966       rc = pModule->xBegin(pVTab->pVtab);
101967       if( rc==SQLCIPHER_OK ){
101968         addToVTrans(db, pVTab);
101969       }
101970     }
101971   }
101972   return rc;
101973 }
101974
101975 /*
101976 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
101977 ** virtual tables that currently have an open transaction. Pass iSavepoint
101978 ** as the second argument to the virtual table method invoked.
101979 **
101980 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
101981 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
101982 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
101983 ** an open transaction is invoked.
101984 **
101985 ** If any virtual table method returns an error code other than SQLCIPHER_OK, 
101986 ** processing is abandoned and the error returned to the caller of this
101987 ** function immediately. If all calls to virtual table methods are successful,
101988 ** SQLCIPHER_OK is returned.
101989 */
101990 SQLCIPHER_PRIVATE int sqlcipher3VtabSavepoint(sqlcipher3 *db, int op, int iSavepoint){
101991   int rc = SQLCIPHER_OK;
101992
101993   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
101994   assert( iSavepoint>=0 );
101995   if( db->aVTrans ){
101996     int i;
101997     for(i=0; rc==SQLCIPHER_OK && i<db->nVTrans; i++){
101998       VTable *pVTab = db->aVTrans[i];
101999       const sqlcipher3_module *pMod = pVTab->pMod->pModule;
102000       if( pVTab->pVtab && pMod->iVersion>=2 ){
102001         int (*xMethod)(sqlcipher3_vtab *, int);
102002         switch( op ){
102003           case SAVEPOINT_BEGIN:
102004             xMethod = pMod->xSavepoint;
102005             pVTab->iSavepoint = iSavepoint+1;
102006             break;
102007           case SAVEPOINT_ROLLBACK:
102008             xMethod = pMod->xRollbackTo;
102009             break;
102010           default:
102011             xMethod = pMod->xRelease;
102012             break;
102013         }
102014         if( xMethod && pVTab->iSavepoint>iSavepoint ){
102015           rc = xMethod(pVTab->pVtab, iSavepoint);
102016         }
102017       }
102018     }
102019   }
102020   return rc;
102021 }
102022
102023 /*
102024 ** The first parameter (pDef) is a function implementation.  The
102025 ** second parameter (pExpr) is the first argument to this function.
102026 ** If pExpr is a column in a virtual table, then let the virtual
102027 ** table implementation have an opportunity to overload the function.
102028 **
102029 ** This routine is used to allow virtual table implementations to
102030 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
102031 **
102032 ** Return either the pDef argument (indicating no change) or a 
102033 ** new FuncDef structure that is marked as ephemeral using the
102034 ** SQLCIPHER_FUNC_EPHEM flag.
102035 */
102036 SQLCIPHER_PRIVATE FuncDef *sqlcipher3VtabOverloadFunction(
102037   sqlcipher3 *db,    /* Database connection for reporting malloc problems */
102038   FuncDef *pDef,  /* Function to possibly overload */
102039   int nArg,       /* Number of arguments to the function */
102040   Expr *pExpr     /* First argument to the function */
102041 ){
102042   Table *pTab;
102043   sqlcipher3_vtab *pVtab;
102044   sqlcipher3_module *pMod;
102045   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**) = 0;
102046   void *pArg = 0;
102047   FuncDef *pNew;
102048   int rc = 0;
102049   char *zLowerName;
102050   unsigned char *z;
102051
102052
102053   /* Check to see the left operand is a column in a virtual table */
102054   if( NEVER(pExpr==0) ) return pDef;
102055   if( pExpr->op!=TK_COLUMN ) return pDef;
102056   pTab = pExpr->pTab;
102057   if( NEVER(pTab==0) ) return pDef;
102058   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102059   pVtab = sqlcipher3GetVTable(db, pTab)->pVtab;
102060   assert( pVtab!=0 );
102061   assert( pVtab->pModule!=0 );
102062   pMod = (sqlcipher3_module *)pVtab->pModule;
102063   if( pMod->xFindFunction==0 ) return pDef;
102064  
102065   /* Call the xFindFunction method on the virtual table implementation
102066   ** to see if the implementation wants to overload this function 
102067   */
102068   zLowerName = sqlcipher3DbStrDup(db, pDef->zName);
102069   if( zLowerName ){
102070     for(z=(unsigned char*)zLowerName; *z; z++){
102071       *z = sqlcipher3UpperToLower[*z];
102072     }
102073     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102074     sqlcipher3DbFree(db, zLowerName);
102075   }
102076   if( rc==0 ){
102077     return pDef;
102078   }
102079
102080   /* Create a new ephemeral function definition for the overloaded
102081   ** function */
102082   pNew = sqlcipher3DbMallocZero(db, sizeof(*pNew)
102083                              + sqlcipher3Strlen30(pDef->zName) + 1);
102084   if( pNew==0 ){
102085     return pDef;
102086   }
102087   *pNew = *pDef;
102088   pNew->zName = (char *)&pNew[1];
102089   memcpy(pNew->zName, pDef->zName, sqlcipher3Strlen30(pDef->zName)+1);
102090   pNew->xFunc = xFunc;
102091   pNew->pUserData = pArg;
102092   pNew->flags |= SQLCIPHER_FUNC_EPHEM;
102093   return pNew;
102094 }
102095
102096 /*
102097 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102098 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
102099 ** array if it is missing.  If pTab is already in the array, this routine
102100 ** is a no-op.
102101 */
102102 SQLCIPHER_PRIVATE void sqlcipher3VtabMakeWritable(Parse *pParse, Table *pTab){
102103   Parse *pToplevel = sqlcipher3ParseToplevel(pParse);
102104   int i, n;
102105   Table **apVtabLock;
102106
102107   assert( IsVirtual(pTab) );
102108   for(i=0; i<pToplevel->nVtabLock; i++){
102109     if( pTab==pToplevel->apVtabLock[i] ) return;
102110   }
102111   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102112   apVtabLock = sqlcipher3_realloc(pToplevel->apVtabLock, n);
102113   if( apVtabLock ){
102114     pToplevel->apVtabLock = apVtabLock;
102115     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102116   }else{
102117     pToplevel->db->mallocFailed = 1;
102118   }
102119 }
102120
102121 /*
102122 ** Return the ON CONFLICT resolution mode in effect for the virtual
102123 ** table update operation currently in progress.
102124 **
102125 ** The results of this routine are undefined unless it is called from
102126 ** within an xUpdate method.
102127 */
102128 SQLCIPHER_API int sqlcipher3_vtab_on_conflict(sqlcipher3 *db){
102129   static const unsigned char aMap[] = { 
102130     SQLCIPHER_ROLLBACK, SQLCIPHER_ABORT, SQLCIPHER_FAIL, SQLCIPHER_IGNORE, SQLCIPHER_REPLACE 
102131   };
102132   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102133   assert( OE_Ignore==4 && OE_Replace==5 );
102134   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102135   return (int)aMap[db->vtabOnConflict-1];
102136 }
102137
102138 /*
102139 ** Call from within the xCreate() or xConnect() methods to provide 
102140 ** the SQLite core with additional information about the behavior
102141 ** of the virtual table being implemented.
102142 */
102143 SQLCIPHER_API int sqlcipher3_vtab_config(sqlcipher3 *db, int op, ...){
102144   va_list ap;
102145   int rc = SQLCIPHER_OK;
102146
102147   sqlcipher3_mutex_enter(db->mutex);
102148
102149   va_start(ap, op);
102150   switch( op ){
102151     case SQLCIPHER_VTAB_CONSTRAINT_SUPPORT: {
102152       VtabCtx *p = db->pVtabCtx;
102153       if( !p ){
102154         rc = SQLCIPHER_MISUSE_BKPT;
102155       }else{
102156         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102157         p->pVTable->bConstraint = (u8)va_arg(ap, int);
102158       }
102159       break;
102160     }
102161     default:
102162       rc = SQLCIPHER_MISUSE_BKPT;
102163       break;
102164   }
102165   va_end(ap);
102166
102167   if( rc!=SQLCIPHER_OK ) sqlcipher3Error(db, rc, 0);
102168   sqlcipher3_mutex_leave(db->mutex);
102169   return rc;
102170 }
102171
102172 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
102173
102174 /************** End of vtab.c ************************************************/
102175 /************** Begin file where.c *******************************************/
102176 /*
102177 ** 2001 September 15
102178 **
102179 ** The author disclaims copyright to this source code.  In place of
102180 ** a legal notice, here is a blessing:
102181 **
102182 **    May you do good and not evil.
102183 **    May you find forgiveness for yourself and forgive others.
102184 **    May you share freely, never taking more than you give.
102185 **
102186 *************************************************************************
102187 ** This module contains C code that generates VDBE code used to process
102188 ** the WHERE clause of SQL statements.  This module is responsible for
102189 ** generating the code that loops through a table looking for applicable
102190 ** rows.  Indices are selected and used to speed the search when doing
102191 ** so is applicable.  Because this module is responsible for selecting
102192 ** indices, you might also think of this module as the "query optimizer".
102193 */
102194
102195
102196 /*
102197 ** Trace output macros
102198 */
102199 #if defined(SQLCIPHER_TEST) || defined(SQLCIPHER_DEBUG)
102200 SQLCIPHER_PRIVATE int sqlcipher3WhereTrace = 0;
102201 #endif
102202 #if defined(SQLCIPHER_TEST) && defined(SQLCIPHER_DEBUG)
102203 # define WHERETRACE(X)  if(sqlcipher3WhereTrace) sqlcipher3DebugPrintf X
102204 #else
102205 # define WHERETRACE(X)
102206 #endif
102207
102208 /* Forward reference
102209 */
102210 typedef struct WhereClause WhereClause;
102211 typedef struct WhereMaskSet WhereMaskSet;
102212 typedef struct WhereOrInfo WhereOrInfo;
102213 typedef struct WhereAndInfo WhereAndInfo;
102214 typedef struct WhereCost WhereCost;
102215
102216 /*
102217 ** The query generator uses an array of instances of this structure to
102218 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102219 ** clause subexpression is separated from the others by AND operators,
102220 ** usually, or sometimes subexpressions separated by OR.
102221 **
102222 ** All WhereTerms are collected into a single WhereClause structure.  
102223 ** The following identity holds:
102224 **
102225 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
102226 **
102227 ** When a term is of the form:
102228 **
102229 **              X <op> <expr>
102230 **
102231 ** where X is a column name and <op> is one of certain operators,
102232 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
102233 ** cursor number and column number for X.  WhereTerm.eOperator records
102234 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
102235 ** use of a bitmask encoding for the operator allows us to search
102236 ** quickly for terms that match any of several different operators.
102237 **
102238 ** A WhereTerm might also be two or more subterms connected by OR:
102239 **
102240 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
102241 **
102242 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
102243 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
102244 ** is collected about the
102245 **
102246 ** If a term in the WHERE clause does not match either of the two previous
102247 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
102248 ** to the original subexpression content and wtFlags is set up appropriately
102249 ** but no other fields in the WhereTerm object are meaningful.
102250 **
102251 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
102252 ** but they do so indirectly.  A single WhereMaskSet structure translates
102253 ** cursor number into bits and the translated bit is stored in the prereq
102254 ** fields.  The translation is used in order to maximize the number of
102255 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
102256 ** spread out over the non-negative integers.  For example, the cursor
102257 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
102258 ** translates these sparse cursor numbers into consecutive integers
102259 ** beginning with 0 in order to make the best possible use of the available
102260 ** bits in the Bitmask.  So, in the example above, the cursor numbers
102261 ** would be mapped into integers 0 through 7.
102262 **
102263 ** The number of terms in a join is limited by the number of bits
102264 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
102265 ** is only able to process joins with 64 or fewer tables.
102266 */
102267 typedef struct WhereTerm WhereTerm;
102268 struct WhereTerm {
102269   Expr *pExpr;            /* Pointer to the subexpression that is this term */
102270   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
102271   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
102272   union {
102273     int leftColumn;         /* Column number of X in "X <op> <expr>" */
102274     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
102275     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
102276   } u;
102277   u16 eOperator;          /* A WO_xx value describing <op> */
102278   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
102279   u8 nChild;              /* Number of children that must disable us */
102280   WhereClause *pWC;       /* The clause this term is part of */
102281   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
102282   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
102283 };
102284
102285 /*
102286 ** Allowed values of WhereTerm.wtFlags
102287 */
102288 #define TERM_DYNAMIC    0x01   /* Need to call sqlcipher3ExprDelete(db, pExpr) */
102289 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
102290 #define TERM_CODED      0x04   /* This term is already coded */
102291 #define TERM_COPIED     0x08   /* Has a child */
102292 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
102293 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
102294 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
102295 #ifdef SQLCIPHER_ENABLE_STAT3
102296 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
102297 #else
102298 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
102299 #endif
102300
102301 /*
102302 ** An instance of the following structure holds all information about a
102303 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
102304 **
102305 ** Explanation of pOuter:  For a WHERE clause of the form
102306 **
102307 **           a AND ((b AND c) OR (d AND e)) AND f
102308 **
102309 ** There are separate WhereClause objects for the whole clause and for
102310 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
102311 ** subclauses points to the WhereClause object for the whole clause.
102312 */
102313 struct WhereClause {
102314   Parse *pParse;           /* The parser context */
102315   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
102316   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
102317   WhereClause *pOuter;     /* Outer conjunction */
102318   u8 op;                   /* Split operator.  TK_AND or TK_OR */
102319   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
102320   int nTerm;               /* Number of terms */
102321   int nSlot;               /* Number of entries in a[] */
102322   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
102323 #if defined(SQLCIPHER_SMALL_STACK)
102324   WhereTerm aStatic[1];    /* Initial static space for a[] */
102325 #else
102326   WhereTerm aStatic[8];    /* Initial static space for a[] */
102327 #endif
102328 };
102329
102330 /*
102331 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
102332 ** a dynamically allocated instance of the following structure.
102333 */
102334 struct WhereOrInfo {
102335   WhereClause wc;          /* Decomposition into subterms */
102336   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
102337 };
102338
102339 /*
102340 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
102341 ** a dynamically allocated instance of the following structure.
102342 */
102343 struct WhereAndInfo {
102344   WhereClause wc;          /* The subexpression broken out */
102345 };
102346
102347 /*
102348 ** An instance of the following structure keeps track of a mapping
102349 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
102350 **
102351 ** The VDBE cursor numbers are small integers contained in 
102352 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
102353 ** clause, the cursor numbers might not begin with 0 and they might
102354 ** contain gaps in the numbering sequence.  But we want to make maximum
102355 ** use of the bits in our bitmasks.  This structure provides a mapping
102356 ** from the sparse cursor numbers into consecutive integers beginning
102357 ** with 0.
102358 **
102359 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
102360 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
102361 **
102362 ** For example, if the WHERE clause expression used these VDBE
102363 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
102364 ** would map those cursor numbers into bits 0 through 5.
102365 **
102366 ** Note that the mapping is not necessarily ordered.  In the example
102367 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
102368 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
102369 ** does not really matter.  What is important is that sparse cursor
102370 ** numbers all get mapped into bit numbers that begin with 0 and contain
102371 ** no gaps.
102372 */
102373 struct WhereMaskSet {
102374   int n;                        /* Number of assigned cursor values */
102375   int ix[BMS];                  /* Cursor assigned to each bit */
102376 };
102377
102378 /*
102379 ** A WhereCost object records a lookup strategy and the estimated
102380 ** cost of pursuing that strategy.
102381 */
102382 struct WhereCost {
102383   WherePlan plan;    /* The lookup strategy */
102384   double rCost;      /* Overall cost of pursuing this search strategy */
102385   Bitmask used;      /* Bitmask of cursors used by this plan */
102386 };
102387
102388 /*
102389 ** Bitmasks for the operators that indices are able to exploit.  An
102390 ** OR-ed combination of these values can be used when searching for
102391 ** terms in the where clause.
102392 */
102393 #define WO_IN     0x001
102394 #define WO_EQ     0x002
102395 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
102396 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
102397 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
102398 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
102399 #define WO_MATCH  0x040
102400 #define WO_ISNULL 0x080
102401 #define WO_OR     0x100       /* Two or more OR-connected terms */
102402 #define WO_AND    0x200       /* Two or more AND-connected terms */
102403 #define WO_NOOP   0x800       /* This term does not restrict search space */
102404
102405 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
102406 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
102407
102408 /*
102409 ** Value for wsFlags returned by bestIndex() and stored in
102410 ** WhereLevel.wsFlags.  These flags determine which search
102411 ** strategies are appropriate.
102412 **
102413 ** The least significant 12 bits is reserved as a mask for WO_ values above.
102414 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
102415 ** But if the table is the right table of a left join, WhereLevel.wsFlags
102416 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
102417 ** the "op" parameter to findTerm when we are resolving equality constraints.
102418 ** ISNULL constraints will then not be used on the right table of a left
102419 ** join.  Tickets #2177 and #2189.
102420 */
102421 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
102422 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
102423 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
102424 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
102425 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
102426 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
102427 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
102428 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
102429 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
102430 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
102431 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
102432 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
102433 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
102434 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
102435 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
102436 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
102437 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
102438 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
102439 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
102440 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
102441
102442 /*
102443 ** Initialize a preallocated WhereClause structure.
102444 */
102445 static void whereClauseInit(
102446   WhereClause *pWC,        /* The WhereClause to be initialized */
102447   Parse *pParse,           /* The parsing context */
102448   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
102449   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
102450 ){
102451   pWC->pParse = pParse;
102452   pWC->pMaskSet = pMaskSet;
102453   pWC->pOuter = 0;
102454   pWC->nTerm = 0;
102455   pWC->nSlot = ArraySize(pWC->aStatic);
102456   pWC->a = pWC->aStatic;
102457   pWC->vmask = 0;
102458   pWC->wctrlFlags = wctrlFlags;
102459 }
102460
102461 /* Forward reference */
102462 static void whereClauseClear(WhereClause*);
102463
102464 /*
102465 ** Deallocate all memory associated with a WhereOrInfo object.
102466 */
102467 static void whereOrInfoDelete(sqlcipher3 *db, WhereOrInfo *p){
102468   whereClauseClear(&p->wc);
102469   sqlcipher3DbFree(db, p);
102470 }
102471
102472 /*
102473 ** Deallocate all memory associated with a WhereAndInfo object.
102474 */
102475 static void whereAndInfoDelete(sqlcipher3 *db, WhereAndInfo *p){
102476   whereClauseClear(&p->wc);
102477   sqlcipher3DbFree(db, p);
102478 }
102479
102480 /*
102481 ** Deallocate a WhereClause structure.  The WhereClause structure
102482 ** itself is not freed.  This routine is the inverse of whereClauseInit().
102483 */
102484 static void whereClauseClear(WhereClause *pWC){
102485   int i;
102486   WhereTerm *a;
102487   sqlcipher3 *db = pWC->pParse->db;
102488   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
102489     if( a->wtFlags & TERM_DYNAMIC ){
102490       sqlcipher3ExprDelete(db, a->pExpr);
102491     }
102492     if( a->wtFlags & TERM_ORINFO ){
102493       whereOrInfoDelete(db, a->u.pOrInfo);
102494     }else if( a->wtFlags & TERM_ANDINFO ){
102495       whereAndInfoDelete(db, a->u.pAndInfo);
102496     }
102497   }
102498   if( pWC->a!=pWC->aStatic ){
102499     sqlcipher3DbFree(db, pWC->a);
102500   }
102501 }
102502
102503 /*
102504 ** Add a single new WhereTerm entry to the WhereClause object pWC.
102505 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
102506 ** The index in pWC->a[] of the new WhereTerm is returned on success.
102507 ** 0 is returned if the new WhereTerm could not be added due to a memory
102508 ** allocation error.  The memory allocation failure will be recorded in
102509 ** the db->mallocFailed flag so that higher-level functions can detect it.
102510 **
102511 ** This routine will increase the size of the pWC->a[] array as necessary.
102512 **
102513 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
102514 ** for freeing the expression p is assumed by the WhereClause object pWC.
102515 ** This is true even if this routine fails to allocate a new WhereTerm.
102516 **
102517 ** WARNING:  This routine might reallocate the space used to store
102518 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
102519 ** calling this routine.  Such pointers may be reinitialized by referencing
102520 ** the pWC->a[] array.
102521 */
102522 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
102523   WhereTerm *pTerm;
102524   int idx;
102525   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
102526   if( pWC->nTerm>=pWC->nSlot ){
102527     WhereTerm *pOld = pWC->a;
102528     sqlcipher3 *db = pWC->pParse->db;
102529     pWC->a = sqlcipher3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
102530     if( pWC->a==0 ){
102531       if( wtFlags & TERM_DYNAMIC ){
102532         sqlcipher3ExprDelete(db, p);
102533       }
102534       pWC->a = pOld;
102535       return 0;
102536     }
102537     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
102538     if( pOld!=pWC->aStatic ){
102539       sqlcipher3DbFree(db, pOld);
102540     }
102541     pWC->nSlot = sqlcipher3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
102542   }
102543   pTerm = &pWC->a[idx = pWC->nTerm++];
102544   pTerm->pExpr = p;
102545   pTerm->wtFlags = wtFlags;
102546   pTerm->pWC = pWC;
102547   pTerm->iParent = -1;
102548   return idx;
102549 }
102550
102551 /*
102552 ** This routine identifies subexpressions in the WHERE clause where
102553 ** each subexpression is separated by the AND operator or some other
102554 ** operator specified in the op parameter.  The WhereClause structure
102555 ** is filled with pointers to subexpressions.  For example:
102556 **
102557 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
102558 **           \________/     \_______________/     \________________/
102559 **            slot[0]            slot[1]               slot[2]
102560 **
102561 ** The original WHERE clause in pExpr is unaltered.  All this routine
102562 ** does is make slot[] entries point to substructure within pExpr.
102563 **
102564 ** In the previous sentence and in the diagram, "slot[]" refers to
102565 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
102566 ** all terms of the WHERE clause.
102567 */
102568 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
102569   pWC->op = (u8)op;
102570   if( pExpr==0 ) return;
102571   if( pExpr->op!=op ){
102572     whereClauseInsert(pWC, pExpr, 0);
102573   }else{
102574     whereSplit(pWC, pExpr->pLeft, op);
102575     whereSplit(pWC, pExpr->pRight, op);
102576   }
102577 }
102578
102579 /*
102580 ** Initialize an expression mask set (a WhereMaskSet object)
102581 */
102582 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
102583
102584 /*
102585 ** Return the bitmask for the given cursor number.  Return 0 if
102586 ** iCursor is not in the set.
102587 */
102588 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
102589   int i;
102590   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
102591   for(i=0; i<pMaskSet->n; i++){
102592     if( pMaskSet->ix[i]==iCursor ){
102593       return ((Bitmask)1)<<i;
102594     }
102595   }
102596   return 0;
102597 }
102598
102599 /*
102600 ** Create a new mask for cursor iCursor.
102601 **
102602 ** There is one cursor per table in the FROM clause.  The number of
102603 ** tables in the FROM clause is limited by a test early in the
102604 ** sqlcipher3WhereBegin() routine.  So we know that the pMaskSet->ix[]
102605 ** array will never overflow.
102606 */
102607 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
102608   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
102609   pMaskSet->ix[pMaskSet->n++] = iCursor;
102610 }
102611
102612 /*
102613 ** This routine walks (recursively) an expression tree and generates
102614 ** a bitmask indicating which tables are used in that expression
102615 ** tree.
102616 **
102617 ** In order for this routine to work, the calling function must have
102618 ** previously invoked sqlcipher3ResolveExprNames() on the expression.  See
102619 ** the header comment on that routine for additional information.
102620 ** The sqlcipher3ResolveExprNames() routines looks for column names and
102621 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
102622 ** the VDBE cursor number of the table.  This routine just has to
102623 ** translate the cursor numbers into bitmask values and OR all
102624 ** the bitmasks together.
102625 */
102626 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
102627 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
102628 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
102629   Bitmask mask = 0;
102630   if( p==0 ) return 0;
102631   if( p->op==TK_COLUMN ){
102632     mask = getMask(pMaskSet, p->iTable);
102633     return mask;
102634   }
102635   mask = exprTableUsage(pMaskSet, p->pRight);
102636   mask |= exprTableUsage(pMaskSet, p->pLeft);
102637   if( ExprHasProperty(p, EP_xIsSelect) ){
102638     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
102639   }else{
102640     mask |= exprListTableUsage(pMaskSet, p->x.pList);
102641   }
102642   return mask;
102643 }
102644 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
102645   int i;
102646   Bitmask mask = 0;
102647   if( pList ){
102648     for(i=0; i<pList->nExpr; i++){
102649       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
102650     }
102651   }
102652   return mask;
102653 }
102654 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
102655   Bitmask mask = 0;
102656   while( pS ){
102657     SrcList *pSrc = pS->pSrc;
102658     mask |= exprListTableUsage(pMaskSet, pS->pEList);
102659     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
102660     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
102661     mask |= exprTableUsage(pMaskSet, pS->pWhere);
102662     mask |= exprTableUsage(pMaskSet, pS->pHaving);
102663     if( ALWAYS(pSrc!=0) ){
102664       int i;
102665       for(i=0; i<pSrc->nSrc; i++){
102666         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
102667         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
102668       }
102669     }
102670     pS = pS->pPrior;
102671   }
102672   return mask;
102673 }
102674
102675 /*
102676 ** Return TRUE if the given operator is one of the operators that is
102677 ** allowed for an indexable WHERE clause term.  The allowed operators are
102678 ** "=", "<", ">", "<=", ">=", and "IN".
102679 **
102680 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
102681 ** of one of the following forms: column = expression column > expression
102682 ** column >= expression column < expression column <= expression
102683 ** expression = column expression > column expression >= column
102684 ** expression < column expression <= column column IN
102685 ** (expression-list) column IN (subquery) column IS NULL
102686 */
102687 static int allowedOp(int op){
102688   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
102689   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
102690   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
102691   assert( TK_GE==TK_EQ+4 );
102692   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
102693 }
102694
102695 /*
102696 ** Swap two objects of type TYPE.
102697 */
102698 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
102699
102700 /*
102701 ** Commute a comparison operator.  Expressions of the form "X op Y"
102702 ** are converted into "Y op X".
102703 **
102704 ** If a collation sequence is associated with either the left or right
102705 ** side of the comparison, it remains associated with the same side after
102706 ** the commutation. So "Y collate NOCASE op X" becomes 
102707 ** "X collate NOCASE op Y". This is because any collation sequence on
102708 ** the left hand side of a comparison overrides any collation sequence 
102709 ** attached to the right. For the same reason the EP_ExpCollate flag
102710 ** is not commuted.
102711 */
102712 static void exprCommute(Parse *pParse, Expr *pExpr){
102713   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
102714   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
102715   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
102716   pExpr->pRight->pColl = sqlcipher3ExprCollSeq(pParse, pExpr->pRight);
102717   pExpr->pLeft->pColl = sqlcipher3ExprCollSeq(pParse, pExpr->pLeft);
102718   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
102719   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
102720   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
102721   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
102722   if( pExpr->op>=TK_GT ){
102723     assert( TK_LT==TK_GT+2 );
102724     assert( TK_GE==TK_LE+2 );
102725     assert( TK_GT>TK_EQ );
102726     assert( TK_GT<TK_LE );
102727     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
102728     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
102729   }
102730 }
102731
102732 /*
102733 ** Translate from TK_xx operator to WO_xx bitmask.
102734 */
102735 static u16 operatorMask(int op){
102736   u16 c;
102737   assert( allowedOp(op) );
102738   if( op==TK_IN ){
102739     c = WO_IN;
102740   }else if( op==TK_ISNULL ){
102741     c = WO_ISNULL;
102742   }else{
102743     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
102744     c = (u16)(WO_EQ<<(op-TK_EQ));
102745   }
102746   assert( op!=TK_ISNULL || c==WO_ISNULL );
102747   assert( op!=TK_IN || c==WO_IN );
102748   assert( op!=TK_EQ || c==WO_EQ );
102749   assert( op!=TK_LT || c==WO_LT );
102750   assert( op!=TK_LE || c==WO_LE );
102751   assert( op!=TK_GT || c==WO_GT );
102752   assert( op!=TK_GE || c==WO_GE );
102753   return c;
102754 }
102755
102756 /*
102757 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
102758 ** where X is a reference to the iColumn of table iCur and <op> is one of
102759 ** the WO_xx operator codes specified by the op parameter.
102760 ** Return a pointer to the term.  Return 0 if not found.
102761 */
102762 static WhereTerm *findTerm(
102763   WhereClause *pWC,     /* The WHERE clause to be searched */
102764   int iCur,             /* Cursor number of LHS */
102765   int iColumn,          /* Column number of LHS */
102766   Bitmask notReady,     /* RHS must not overlap with this mask */
102767   u32 op,               /* Mask of WO_xx values describing operator */
102768   Index *pIdx           /* Must be compatible with this index, if not NULL */
102769 ){
102770   WhereTerm *pTerm;
102771   int k;
102772   assert( iCur>=0 );
102773   op &= WO_ALL;
102774   for(; pWC; pWC=pWC->pOuter){
102775     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
102776       if( pTerm->leftCursor==iCur
102777          && (pTerm->prereqRight & notReady)==0
102778          && pTerm->u.leftColumn==iColumn
102779          && (pTerm->eOperator & op)!=0
102780       ){
102781         if( pIdx && pTerm->eOperator!=WO_ISNULL ){
102782           Expr *pX = pTerm->pExpr;
102783           CollSeq *pColl;
102784           char idxaff;
102785           int j;
102786           Parse *pParse = pWC->pParse;
102787   
102788           idxaff = pIdx->pTable->aCol[iColumn].affinity;
102789           if( !sqlcipher3IndexAffinityOk(pX, idxaff) ) continue;
102790   
102791           /* Figure out the collation sequence required from an index for
102792           ** it to be useful for optimising expression pX. Store this
102793           ** value in variable pColl.
102794           */
102795           assert(pX->pLeft);
102796           pColl = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
102797           assert(pColl || pParse->nErr);
102798   
102799           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
102800             if( NEVER(j>=pIdx->nColumn) ) return 0;
102801           }
102802           if( pColl && sqlcipher3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
102803         }
102804         return pTerm;
102805       }
102806     }
102807   }
102808   return 0;
102809 }
102810
102811 /* Forward reference */
102812 static void exprAnalyze(SrcList*, WhereClause*, int);
102813
102814 /*
102815 ** Call exprAnalyze on all terms in a WHERE clause.  
102816 **
102817 **
102818 */
102819 static void exprAnalyzeAll(
102820   SrcList *pTabList,       /* the FROM clause */
102821   WhereClause *pWC         /* the WHERE clause to be analyzed */
102822 ){
102823   int i;
102824   for(i=pWC->nTerm-1; i>=0; i--){
102825     exprAnalyze(pTabList, pWC, i);
102826   }
102827 }
102828
102829 #ifndef SQLCIPHER_OMIT_LIKE_OPTIMIZATION
102830 /*
102831 ** Check to see if the given expression is a LIKE or GLOB operator that
102832 ** can be optimized using inequality constraints.  Return TRUE if it is
102833 ** so and false if not.
102834 **
102835 ** In order for the operator to be optimizible, the RHS must be a string
102836 ** literal that does not begin with a wildcard.  
102837 */
102838 static int isLikeOrGlob(
102839   Parse *pParse,    /* Parsing and code generating context */
102840   Expr *pExpr,      /* Test this expression */
102841   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
102842   int *pisComplete, /* True if the only wildcard is % in the last character */
102843   int *pnoCase      /* True if uppercase is equivalent to lowercase */
102844 ){
102845   const char *z = 0;         /* String on RHS of LIKE operator */
102846   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
102847   ExprList *pList;           /* List of operands to the LIKE operator */
102848   int c;                     /* One character in z[] */
102849   int cnt;                   /* Number of non-wildcard prefix characters */
102850   char wc[3];                /* Wildcard characters */
102851   sqlcipher3 *db = pParse->db;  /* Database connection */
102852   sqlcipher3_value *pVal = 0;
102853   int op;                    /* Opcode of pRight */
102854
102855   if( !sqlcipher3IsLikeFunction(db, pExpr, pnoCase, wc) ){
102856     return 0;
102857   }
102858 #ifdef SQLCIPHER_EBCDIC
102859   if( *pnoCase ) return 0;
102860 #endif
102861   pList = pExpr->x.pList;
102862   pLeft = pList->a[1].pExpr;
102863   if( pLeft->op!=TK_COLUMN || sqlcipher3ExprAffinity(pLeft)!=SQLCIPHER_AFF_TEXT ){
102864     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
102865     ** be the name of an indexed column with TEXT affinity. */
102866     return 0;
102867   }
102868   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
102869
102870   pRight = pList->a[0].pExpr;
102871   op = pRight->op;
102872   if( op==TK_REGISTER ){
102873     op = pRight->op2;
102874   }
102875   if( op==TK_VARIABLE ){
102876     Vdbe *pReprepare = pParse->pReprepare;
102877     int iCol = pRight->iColumn;
102878     pVal = sqlcipher3VdbeGetValue(pReprepare, iCol, SQLCIPHER_AFF_NONE);
102879     if( pVal && sqlcipher3_value_type(pVal)==SQLCIPHER_TEXT ){
102880       z = (char *)sqlcipher3_value_text(pVal);
102881     }
102882     sqlcipher3VdbeSetVarmask(pParse->pVdbe, iCol);
102883     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
102884   }else if( op==TK_STRING ){
102885     z = pRight->u.zToken;
102886   }
102887   if( z ){
102888     cnt = 0;
102889     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
102890       cnt++;
102891     }
102892     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
102893       Expr *pPrefix;
102894       *pisComplete = c==wc[0] && z[cnt+1]==0;
102895       pPrefix = sqlcipher3Expr(db, TK_STRING, z);
102896       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
102897       *ppPrefix = pPrefix;
102898       if( op==TK_VARIABLE ){
102899         Vdbe *v = pParse->pVdbe;
102900         sqlcipher3VdbeSetVarmask(v, pRight->iColumn);
102901         if( *pisComplete && pRight->u.zToken[1] ){
102902           /* If the rhs of the LIKE expression is a variable, and the current
102903           ** value of the variable means there is no need to invoke the LIKE
102904           ** function, then no OP_Variable will be added to the program.
102905           ** This causes problems for the sqlcipher3_bind_parameter_name()
102906           ** API. To workaround them, add a dummy OP_Variable here.
102907           */ 
102908           int r1 = sqlcipher3GetTempReg(pParse);
102909           sqlcipher3ExprCodeTarget(pParse, pRight, r1);
102910           sqlcipher3VdbeChangeP3(v, sqlcipher3VdbeCurrentAddr(v)-1, 0);
102911           sqlcipher3ReleaseTempReg(pParse, r1);
102912         }
102913       }
102914     }else{
102915       z = 0;
102916     }
102917   }
102918
102919   sqlcipher3ValueFree(pVal);
102920   return (z!=0);
102921 }
102922 #endif /* SQLCIPHER_OMIT_LIKE_OPTIMIZATION */
102923
102924
102925 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
102926 /*
102927 ** Check to see if the given expression is of the form
102928 **
102929 **         column MATCH expr
102930 **
102931 ** If it is then return TRUE.  If not, return FALSE.
102932 */
102933 static int isMatchOfColumn(
102934   Expr *pExpr      /* Test this expression */
102935 ){
102936   ExprList *pList;
102937
102938   if( pExpr->op!=TK_FUNCTION ){
102939     return 0;
102940   }
102941   if( sqlcipher3StrICmp(pExpr->u.zToken,"match")!=0 ){
102942     return 0;
102943   }
102944   pList = pExpr->x.pList;
102945   if( pList->nExpr!=2 ){
102946     return 0;
102947   }
102948   if( pList->a[1].pExpr->op != TK_COLUMN ){
102949     return 0;
102950   }
102951   return 1;
102952 }
102953 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
102954
102955 /*
102956 ** If the pBase expression originated in the ON or USING clause of
102957 ** a join, then transfer the appropriate markings over to derived.
102958 */
102959 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
102960   pDerived->flags |= pBase->flags & EP_FromJoin;
102961   pDerived->iRightJoinTable = pBase->iRightJoinTable;
102962 }
102963
102964 #if !defined(SQLCIPHER_OMIT_OR_OPTIMIZATION) && !defined(SQLCIPHER_OMIT_SUBQUERY)
102965 /*
102966 ** Analyze a term that consists of two or more OR-connected
102967 ** subterms.  So in:
102968 **
102969 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
102970 **                          ^^^^^^^^^^^^^^^^^^^^
102971 **
102972 ** This routine analyzes terms such as the middle term in the above example.
102973 ** A WhereOrTerm object is computed and attached to the term under
102974 ** analysis, regardless of the outcome of the analysis.  Hence:
102975 **
102976 **     WhereTerm.wtFlags   |=  TERM_ORINFO
102977 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
102978 **
102979 ** The term being analyzed must have two or more of OR-connected subterms.
102980 ** A single subterm might be a set of AND-connected sub-subterms.
102981 ** Examples of terms under analysis:
102982 **
102983 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
102984 **     (B)     x=expr1 OR expr2=x OR x=expr3
102985 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
102986 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
102987 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
102988 **
102989 ** CASE 1:
102990 **
102991 ** If all subterms are of the form T.C=expr for some single column of C
102992 ** a single table T (as shown in example B above) then create a new virtual
102993 ** term that is an equivalent IN expression.  In other words, if the term
102994 ** being analyzed is:
102995 **
102996 **      x = expr1  OR  expr2 = x  OR  x = expr3
102997 **
102998 ** then create a new virtual term like this:
102999 **
103000 **      x IN (expr1,expr2,expr3)
103001 **
103002 ** CASE 2:
103003 **
103004 ** If all subterms are indexable by a single table T, then set
103005 **
103006 **     WhereTerm.eOperator              =  WO_OR
103007 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
103008 **
103009 ** A subterm is "indexable" if it is of the form
103010 ** "T.C <op> <expr>" where C is any column of table T and 
103011 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
103012 ** A subterm is also indexable if it is an AND of two or more
103013 ** subsubterms at least one of which is indexable.  Indexable AND 
103014 ** subterms have their eOperator set to WO_AND and they have
103015 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
103016 **
103017 ** From another point of view, "indexable" means that the subterm could
103018 ** potentially be used with an index if an appropriate index exists.
103019 ** This analysis does not consider whether or not the index exists; that
103020 ** is something the bestIndex() routine will determine.  This analysis
103021 ** only looks at whether subterms appropriate for indexing exist.
103022 **
103023 ** All examples A through E above all satisfy case 2.  But if a term
103024 ** also statisfies case 1 (such as B) we know that the optimizer will
103025 ** always prefer case 1, so in that case we pretend that case 2 is not
103026 ** satisfied.
103027 **
103028 ** It might be the case that multiple tables are indexable.  For example,
103029 ** (E) above is indexable on tables P, Q, and R.
103030 **
103031 ** Terms that satisfy case 2 are candidates for lookup by using
103032 ** separate indices to find rowids for each subterm and composing
103033 ** the union of all rowids using a RowSet object.  This is similar
103034 ** to "bitmap indices" in other database engines.
103035 **
103036 ** OTHERWISE:
103037 **
103038 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
103039 ** zero.  This term is not useful for search.
103040 */
103041 static void exprAnalyzeOrTerm(
103042   SrcList *pSrc,            /* the FROM clause */
103043   WhereClause *pWC,         /* the complete WHERE clause */
103044   int idxTerm               /* Index of the OR-term to be analyzed */
103045 ){
103046   Parse *pParse = pWC->pParse;            /* Parser context */
103047   sqlcipher3 *db = pParse->db;               /* Database connection */
103048   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103049   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103050   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103051   int i;                                  /* Loop counters */
103052   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103053   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103054   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103055   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103056   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103057
103058   /*
103059   ** Break the OR clause into its separate subterms.  The subterms are
103060   ** stored in a WhereClause structure containing within the WhereOrInfo
103061   ** object that is attached to the original OR clause term.
103062   */
103063   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103064   assert( pExpr->op==TK_OR );
103065   pTerm->u.pOrInfo = pOrInfo = sqlcipher3DbMallocZero(db, sizeof(*pOrInfo));
103066   if( pOrInfo==0 ) return;
103067   pTerm->wtFlags |= TERM_ORINFO;
103068   pOrWc = &pOrInfo->wc;
103069   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103070   whereSplit(pOrWc, pExpr, TK_OR);
103071   exprAnalyzeAll(pSrc, pOrWc);
103072   if( db->mallocFailed ) return;
103073   assert( pOrWc->nTerm>=2 );
103074
103075   /*
103076   ** Compute the set of tables that might satisfy cases 1 or 2.
103077   */
103078   indexable = ~(Bitmask)0;
103079   chngToIN = ~(pWC->vmask);
103080   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103081     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103082       WhereAndInfo *pAndInfo;
103083       assert( pOrTerm->eOperator==0 );
103084       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103085       chngToIN = 0;
103086       pAndInfo = sqlcipher3DbMallocRaw(db, sizeof(*pAndInfo));
103087       if( pAndInfo ){
103088         WhereClause *pAndWC;
103089         WhereTerm *pAndTerm;
103090         int j;
103091         Bitmask b = 0;
103092         pOrTerm->u.pAndInfo = pAndInfo;
103093         pOrTerm->wtFlags |= TERM_ANDINFO;
103094         pOrTerm->eOperator = WO_AND;
103095         pAndWC = &pAndInfo->wc;
103096         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103097         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103098         exprAnalyzeAll(pSrc, pAndWC);
103099         pAndWC->pOuter = pWC;
103100         testcase( db->mallocFailed );
103101         if( !db->mallocFailed ){
103102           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103103             assert( pAndTerm->pExpr );
103104             if( allowedOp(pAndTerm->pExpr->op) ){
103105               b |= getMask(pMaskSet, pAndTerm->leftCursor);
103106             }
103107           }
103108         }
103109         indexable &= b;
103110       }
103111     }else if( pOrTerm->wtFlags & TERM_COPIED ){
103112       /* Skip this term for now.  We revisit it when we process the
103113       ** corresponding TERM_VIRTUAL term */
103114     }else{
103115       Bitmask b;
103116       b = getMask(pMaskSet, pOrTerm->leftCursor);
103117       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103118         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
103119         b |= getMask(pMaskSet, pOther->leftCursor);
103120       }
103121       indexable &= b;
103122       if( pOrTerm->eOperator!=WO_EQ ){
103123         chngToIN = 0;
103124       }else{
103125         chngToIN &= b;
103126       }
103127     }
103128   }
103129
103130   /*
103131   ** Record the set of tables that satisfy case 2.  The set might be
103132   ** empty.
103133   */
103134   pOrInfo->indexable = indexable;
103135   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
103136
103137   /*
103138   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
103139   ** we have to do some additional checking to see if case 1 really
103140   ** is satisfied.
103141   **
103142   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
103143   ** that there is no possibility of transforming the OR clause into an
103144   ** IN operator because one or more terms in the OR clause contain
103145   ** something other than == on a column in the single table.  The 1-bit
103146   ** case means that every term of the OR clause is of the form
103147   ** "table.column=expr" for some single table.  The one bit that is set
103148   ** will correspond to the common table.  We still need to check to make
103149   ** sure the same column is used on all terms.  The 2-bit case is when
103150   ** the all terms are of the form "table1.column=table2.column".  It
103151   ** might be possible to form an IN operator with either table1.column
103152   ** or table2.column as the LHS if either is common to every term of
103153   ** the OR clause.
103154   **
103155   ** Note that terms of the form "table.column1=table.column2" (the
103156   ** same table on both sizes of the ==) cannot be optimized.
103157   */
103158   if( chngToIN ){
103159     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
103160     int iColumn = -1;         /* Column index on lhs of IN operator */
103161     int iCursor = -1;         /* Table cursor common to all terms */
103162     int j = 0;                /* Loop counter */
103163
103164     /* Search for a table and column that appears on one side or the
103165     ** other of the == operator in every subterm.  That table and column
103166     ** will be recorded in iCursor and iColumn.  There might not be any
103167     ** such table and column.  Set okToChngToIN if an appropriate table
103168     ** and column is found but leave okToChngToIN false if not found.
103169     */
103170     for(j=0; j<2 && !okToChngToIN; j++){
103171       pOrTerm = pOrWc->a;
103172       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
103173         assert( pOrTerm->eOperator==WO_EQ );
103174         pOrTerm->wtFlags &= ~TERM_OR_OK;
103175         if( pOrTerm->leftCursor==iCursor ){
103176           /* This is the 2-bit case and we are on the second iteration and
103177           ** current term is from the first iteration.  So skip this term. */
103178           assert( j==1 );
103179           continue;
103180         }
103181         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
103182           /* This term must be of the form t1.a==t2.b where t2 is in the
103183           ** chngToIN set but t1 is not.  This term will be either preceeded
103184           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
103185           ** and use its inversion. */
103186           testcase( pOrTerm->wtFlags & TERM_COPIED );
103187           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
103188           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
103189           continue;
103190         }
103191         iColumn = pOrTerm->u.leftColumn;
103192         iCursor = pOrTerm->leftCursor;
103193         break;
103194       }
103195       if( i<0 ){
103196         /* No candidate table+column was found.  This can only occur
103197         ** on the second iteration */
103198         assert( j==1 );
103199         assert( (chngToIN&(chngToIN-1))==0 );
103200         assert( chngToIN==getMask(pMaskSet, iCursor) );
103201         break;
103202       }
103203       testcase( j==1 );
103204
103205       /* We have found a candidate table and column.  Check to see if that
103206       ** table and column is common to every term in the OR clause */
103207       okToChngToIN = 1;
103208       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
103209         assert( pOrTerm->eOperator==WO_EQ );
103210         if( pOrTerm->leftCursor!=iCursor ){
103211           pOrTerm->wtFlags &= ~TERM_OR_OK;
103212         }else if( pOrTerm->u.leftColumn!=iColumn ){
103213           okToChngToIN = 0;
103214         }else{
103215           int affLeft, affRight;
103216           /* If the right-hand side is also a column, then the affinities
103217           ** of both right and left sides must be such that no type
103218           ** conversions are required on the right.  (Ticket #2249)
103219           */
103220           affRight = sqlcipher3ExprAffinity(pOrTerm->pExpr->pRight);
103221           affLeft = sqlcipher3ExprAffinity(pOrTerm->pExpr->pLeft);
103222           if( affRight!=0 && affRight!=affLeft ){
103223             okToChngToIN = 0;
103224           }else{
103225             pOrTerm->wtFlags |= TERM_OR_OK;
103226           }
103227         }
103228       }
103229     }
103230
103231     /* At this point, okToChngToIN is true if original pTerm satisfies
103232     ** case 1.  In that case, construct a new virtual term that is 
103233     ** pTerm converted into an IN operator.
103234     **
103235     ** EV: R-00211-15100
103236     */
103237     if( okToChngToIN ){
103238       Expr *pDup;            /* A transient duplicate expression */
103239       ExprList *pList = 0;   /* The RHS of the IN operator */
103240       Expr *pLeft = 0;       /* The LHS of the IN operator */
103241       Expr *pNew;            /* The complete IN operator */
103242
103243       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
103244         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
103245         assert( pOrTerm->eOperator==WO_EQ );
103246         assert( pOrTerm->leftCursor==iCursor );
103247         assert( pOrTerm->u.leftColumn==iColumn );
103248         pDup = sqlcipher3ExprDup(db, pOrTerm->pExpr->pRight, 0);
103249         pList = sqlcipher3ExprListAppend(pWC->pParse, pList, pDup);
103250         pLeft = pOrTerm->pExpr->pLeft;
103251       }
103252       assert( pLeft!=0 );
103253       pDup = sqlcipher3ExprDup(db, pLeft, 0);
103254       pNew = sqlcipher3PExpr(pParse, TK_IN, pDup, 0, 0);
103255       if( pNew ){
103256         int idxNew;
103257         transferJoinMarkings(pNew, pExpr);
103258         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
103259         pNew->x.pList = pList;
103260         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
103261         testcase( idxNew==0 );
103262         exprAnalyze(pSrc, pWC, idxNew);
103263         pTerm = &pWC->a[idxTerm];
103264         pWC->a[idxNew].iParent = idxTerm;
103265         pTerm->nChild = 1;
103266       }else{
103267         sqlcipher3ExprListDelete(db, pList);
103268       }
103269       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
103270     }
103271   }
103272 }
103273 #endif /* !SQLCIPHER_OMIT_OR_OPTIMIZATION && !SQLCIPHER_OMIT_SUBQUERY */
103274
103275
103276 /*
103277 ** The input to this routine is an WhereTerm structure with only the
103278 ** "pExpr" field filled in.  The job of this routine is to analyze the
103279 ** subexpression and populate all the other fields of the WhereTerm
103280 ** structure.
103281 **
103282 ** If the expression is of the form "<expr> <op> X" it gets commuted
103283 ** to the standard form of "X <op> <expr>".
103284 **
103285 ** If the expression is of the form "X <op> Y" where both X and Y are
103286 ** columns, then the original expression is unchanged and a new virtual
103287 ** term of the form "Y <op> X" is added to the WHERE clause and
103288 ** analyzed separately.  The original term is marked with TERM_COPIED
103289 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
103290 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
103291 ** is a commuted copy of a prior term.)  The original term has nChild=1
103292 ** and the copy has idxParent set to the index of the original term.
103293 */
103294 static void exprAnalyze(
103295   SrcList *pSrc,            /* the FROM clause */
103296   WhereClause *pWC,         /* the WHERE clause */
103297   int idxTerm               /* Index of the term to be analyzed */
103298 ){
103299   WhereTerm *pTerm;                /* The term to be analyzed */
103300   WhereMaskSet *pMaskSet;          /* Set of table index masks */
103301   Expr *pExpr;                     /* The expression to be analyzed */
103302   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
103303   Bitmask prereqAll;               /* Prerequesites of pExpr */
103304   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
103305   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
103306   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
103307   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
103308   int op;                          /* Top-level operator.  pExpr->op */
103309   Parse *pParse = pWC->pParse;     /* Parsing context */
103310   sqlcipher3 *db = pParse->db;        /* Database connection */
103311
103312   if( db->mallocFailed ){
103313     return;
103314   }
103315   pTerm = &pWC->a[idxTerm];
103316   pMaskSet = pWC->pMaskSet;
103317   pExpr = pTerm->pExpr;
103318   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
103319   op = pExpr->op;
103320   if( op==TK_IN ){
103321     assert( pExpr->pRight==0 );
103322     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103323       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
103324     }else{
103325       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
103326     }
103327   }else if( op==TK_ISNULL ){
103328     pTerm->prereqRight = 0;
103329   }else{
103330     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
103331   }
103332   prereqAll = exprTableUsage(pMaskSet, pExpr);
103333   if( ExprHasProperty(pExpr, EP_FromJoin) ){
103334     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
103335     prereqAll |= x;
103336     extraRight = x-1;  /* ON clause terms may not be used with an index
103337                        ** on left table of a LEFT JOIN.  Ticket #3015 */
103338   }
103339   pTerm->prereqAll = prereqAll;
103340   pTerm->leftCursor = -1;
103341   pTerm->iParent = -1;
103342   pTerm->eOperator = 0;
103343   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
103344     Expr *pLeft = pExpr->pLeft;
103345     Expr *pRight = pExpr->pRight;
103346     if( pLeft->op==TK_COLUMN ){
103347       pTerm->leftCursor = pLeft->iTable;
103348       pTerm->u.leftColumn = pLeft->iColumn;
103349       pTerm->eOperator = operatorMask(op);
103350     }
103351     if( pRight && pRight->op==TK_COLUMN ){
103352       WhereTerm *pNew;
103353       Expr *pDup;
103354       if( pTerm->leftCursor>=0 ){
103355         int idxNew;
103356         pDup = sqlcipher3ExprDup(db, pExpr, 0);
103357         if( db->mallocFailed ){
103358           sqlcipher3ExprDelete(db, pDup);
103359           return;
103360         }
103361         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
103362         if( idxNew==0 ) return;
103363         pNew = &pWC->a[idxNew];
103364         pNew->iParent = idxTerm;
103365         pTerm = &pWC->a[idxTerm];
103366         pTerm->nChild = 1;
103367         pTerm->wtFlags |= TERM_COPIED;
103368       }else{
103369         pDup = pExpr;
103370         pNew = pTerm;
103371       }
103372       exprCommute(pParse, pDup);
103373       pLeft = pDup->pLeft;
103374       pNew->leftCursor = pLeft->iTable;
103375       pNew->u.leftColumn = pLeft->iColumn;
103376       testcase( (prereqLeft | extraRight) != prereqLeft );
103377       pNew->prereqRight = prereqLeft | extraRight;
103378       pNew->prereqAll = prereqAll;
103379       pNew->eOperator = operatorMask(pDup->op);
103380     }
103381   }
103382
103383 #ifndef SQLCIPHER_OMIT_BETWEEN_OPTIMIZATION
103384   /* If a term is the BETWEEN operator, create two new virtual terms
103385   ** that define the range that the BETWEEN implements.  For example:
103386   **
103387   **      a BETWEEN b AND c
103388   **
103389   ** is converted into:
103390   **
103391   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
103392   **
103393   ** The two new terms are added onto the end of the WhereClause object.
103394   ** The new terms are "dynamic" and are children of the original BETWEEN
103395   ** term.  That means that if the BETWEEN term is coded, the children are
103396   ** skipped.  Or, if the children are satisfied by an index, the original
103397   ** BETWEEN term is skipped.
103398   */
103399   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
103400     ExprList *pList = pExpr->x.pList;
103401     int i;
103402     static const u8 ops[] = {TK_GE, TK_LE};
103403     assert( pList!=0 );
103404     assert( pList->nExpr==2 );
103405     for(i=0; i<2; i++){
103406       Expr *pNewExpr;
103407       int idxNew;
103408       pNewExpr = sqlcipher3PExpr(pParse, ops[i], 
103409                              sqlcipher3ExprDup(db, pExpr->pLeft, 0),
103410                              sqlcipher3ExprDup(db, pList->a[i].pExpr, 0), 0);
103411       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103412       testcase( idxNew==0 );
103413       exprAnalyze(pSrc, pWC, idxNew);
103414       pTerm = &pWC->a[idxTerm];
103415       pWC->a[idxNew].iParent = idxTerm;
103416     }
103417     pTerm->nChild = 2;
103418   }
103419 #endif /* SQLCIPHER_OMIT_BETWEEN_OPTIMIZATION */
103420
103421 #if !defined(SQLCIPHER_OMIT_OR_OPTIMIZATION) && !defined(SQLCIPHER_OMIT_SUBQUERY)
103422   /* Analyze a term that is composed of two or more subterms connected by
103423   ** an OR operator.
103424   */
103425   else if( pExpr->op==TK_OR ){
103426     assert( pWC->op==TK_AND );
103427     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
103428     pTerm = &pWC->a[idxTerm];
103429   }
103430 #endif /* SQLCIPHER_OMIT_OR_OPTIMIZATION */
103431
103432 #ifndef SQLCIPHER_OMIT_LIKE_OPTIMIZATION
103433   /* Add constraints to reduce the search space on a LIKE or GLOB
103434   ** operator.
103435   **
103436   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
103437   **
103438   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
103439   **
103440   ** The last character of the prefix "abc" is incremented to form the
103441   ** termination condition "abd".
103442   */
103443   if( pWC->op==TK_AND 
103444    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
103445   ){
103446     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
103447     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
103448     Expr *pNewExpr1;
103449     Expr *pNewExpr2;
103450     int idxNew1;
103451     int idxNew2;
103452     CollSeq *pColl;    /* Collating sequence to use */
103453
103454     pLeft = pExpr->x.pList->a[1].pExpr;
103455     pStr2 = sqlcipher3ExprDup(db, pStr1, 0);
103456     if( !db->mallocFailed ){
103457       u8 c, *pC;       /* Last character before the first wildcard */
103458       pC = (u8*)&pStr2->u.zToken[sqlcipher3Strlen30(pStr2->u.zToken)-1];
103459       c = *pC;
103460       if( noCase ){
103461         /* The point is to increment the last character before the first
103462         ** wildcard.  But if we increment '@', that will push it into the
103463         ** alphabetic range where case conversions will mess up the 
103464         ** inequality.  To avoid this, make sure to also run the full
103465         ** LIKE on all candidate expressions by clearing the isComplete flag
103466         */
103467         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
103468
103469
103470         c = sqlcipher3UpperToLower[c];
103471       }
103472       *pC = c + 1;
103473     }
103474     pColl = sqlcipher3FindCollSeq(db, SQLCIPHER_UTF8, noCase ? "NOCASE" : "BINARY",0);
103475     pNewExpr1 = sqlcipher3PExpr(pParse, TK_GE, 
103476                      sqlcipher3ExprSetColl(sqlcipher3ExprDup(db,pLeft,0), pColl),
103477                      pStr1, 0);
103478     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
103479     testcase( idxNew1==0 );
103480     exprAnalyze(pSrc, pWC, idxNew1);
103481     pNewExpr2 = sqlcipher3PExpr(pParse, TK_LT,
103482                      sqlcipher3ExprSetColl(sqlcipher3ExprDup(db,pLeft,0), pColl),
103483                      pStr2, 0);
103484     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
103485     testcase( idxNew2==0 );
103486     exprAnalyze(pSrc, pWC, idxNew2);
103487     pTerm = &pWC->a[idxTerm];
103488     if( isComplete ){
103489       pWC->a[idxNew1].iParent = idxTerm;
103490       pWC->a[idxNew2].iParent = idxTerm;
103491       pTerm->nChild = 2;
103492     }
103493   }
103494 #endif /* SQLCIPHER_OMIT_LIKE_OPTIMIZATION */
103495
103496 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
103497   /* Add a WO_MATCH auxiliary term to the constraint set if the
103498   ** current expression is of the form:  column MATCH expr.
103499   ** This information is used by the xBestIndex methods of
103500   ** virtual tables.  The native query optimizer does not attempt
103501   ** to do anything with MATCH functions.
103502   */
103503   if( isMatchOfColumn(pExpr) ){
103504     int idxNew;
103505     Expr *pRight, *pLeft;
103506     WhereTerm *pNewTerm;
103507     Bitmask prereqColumn, prereqExpr;
103508
103509     pRight = pExpr->x.pList->a[0].pExpr;
103510     pLeft = pExpr->x.pList->a[1].pExpr;
103511     prereqExpr = exprTableUsage(pMaskSet, pRight);
103512     prereqColumn = exprTableUsage(pMaskSet, pLeft);
103513     if( (prereqExpr & prereqColumn)==0 ){
103514       Expr *pNewExpr;
103515       pNewExpr = sqlcipher3PExpr(pParse, TK_MATCH, 
103516                               0, sqlcipher3ExprDup(db, pRight, 0), 0);
103517       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103518       testcase( idxNew==0 );
103519       pNewTerm = &pWC->a[idxNew];
103520       pNewTerm->prereqRight = prereqExpr;
103521       pNewTerm->leftCursor = pLeft->iTable;
103522       pNewTerm->u.leftColumn = pLeft->iColumn;
103523       pNewTerm->eOperator = WO_MATCH;
103524       pNewTerm->iParent = idxTerm;
103525       pTerm = &pWC->a[idxTerm];
103526       pTerm->nChild = 1;
103527       pTerm->wtFlags |= TERM_COPIED;
103528       pNewTerm->prereqAll = pTerm->prereqAll;
103529     }
103530   }
103531 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
103532
103533 #ifdef SQLCIPHER_ENABLE_STAT3
103534   /* When sqlcipher_stat3 histogram data is available an operator of the
103535   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
103536   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
103537   ** virtual term of that form.
103538   **
103539   ** Note that the virtual term must be tagged with TERM_VNULL.  This
103540   ** TERM_VNULL tag will suppress the not-null check at the beginning
103541   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
103542   ** the start of the loop will prevent any results from being returned.
103543   */
103544   if( pExpr->op==TK_NOTNULL
103545    && pExpr->pLeft->op==TK_COLUMN
103546    && pExpr->pLeft->iColumn>=0
103547   ){
103548     Expr *pNewExpr;
103549     Expr *pLeft = pExpr->pLeft;
103550     int idxNew;
103551     WhereTerm *pNewTerm;
103552
103553     pNewExpr = sqlcipher3PExpr(pParse, TK_GT,
103554                             sqlcipher3ExprDup(db, pLeft, 0),
103555                             sqlcipher3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
103556
103557     idxNew = whereClauseInsert(pWC, pNewExpr,
103558                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
103559     if( idxNew ){
103560       pNewTerm = &pWC->a[idxNew];
103561       pNewTerm->prereqRight = 0;
103562       pNewTerm->leftCursor = pLeft->iTable;
103563       pNewTerm->u.leftColumn = pLeft->iColumn;
103564       pNewTerm->eOperator = WO_GT;
103565       pNewTerm->iParent = idxTerm;
103566       pTerm = &pWC->a[idxTerm];
103567       pTerm->nChild = 1;
103568       pTerm->wtFlags |= TERM_COPIED;
103569       pNewTerm->prereqAll = pTerm->prereqAll;
103570     }
103571   }
103572 #endif /* SQLCIPHER_ENABLE_STAT */
103573
103574   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
103575   ** an index for tables to the left of the join.
103576   */
103577   pTerm->prereqRight |= extraRight;
103578 }
103579
103580 /*
103581 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
103582 ** a reference to any table other than the iBase table.
103583 */
103584 static int referencesOtherTables(
103585   ExprList *pList,          /* Search expressions in ths list */
103586   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
103587   int iFirst,               /* Be searching with the iFirst-th expression */
103588   int iBase                 /* Ignore references to this table */
103589 ){
103590   Bitmask allowed = ~getMask(pMaskSet, iBase);
103591   while( iFirst<pList->nExpr ){
103592     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
103593       return 1;
103594     }
103595   }
103596   return 0;
103597 }
103598
103599 /*
103600 ** This function searches the expression list passed as the second argument
103601 ** for an expression of type TK_COLUMN that refers to the same column and
103602 ** uses the same collation sequence as the iCol'th column of index pIdx.
103603 ** Argument iBase is the cursor number used for the table that pIdx refers
103604 ** to.
103605 **
103606 ** If such an expression is found, its index in pList->a[] is returned. If
103607 ** no expression is found, -1 is returned.
103608 */
103609 static int findIndexCol(
103610   Parse *pParse,                  /* Parse context */
103611   ExprList *pList,                /* Expression list to search */
103612   int iBase,                      /* Cursor for table associated with pIdx */
103613   Index *pIdx,                    /* Index to match column of */
103614   int iCol                        /* Column of index to match */
103615 ){
103616   int i;
103617   const char *zColl = pIdx->azColl[iCol];
103618
103619   for(i=0; i<pList->nExpr; i++){
103620     Expr *p = pList->a[i].pExpr;
103621     if( p->op==TK_COLUMN
103622      && p->iColumn==pIdx->aiColumn[iCol]
103623      && p->iTable==iBase
103624     ){
103625       CollSeq *pColl = sqlcipher3ExprCollSeq(pParse, p);
103626       if( ALWAYS(pColl) && 0==sqlcipher3StrICmp(pColl->zName, zColl) ){
103627         return i;
103628       }
103629     }
103630   }
103631
103632   return -1;
103633 }
103634
103635 /*
103636 ** This routine determines if pIdx can be used to assist in processing a
103637 ** DISTINCT qualifier. In other words, it tests whether or not using this
103638 ** index for the outer loop guarantees that rows with equal values for
103639 ** all expressions in the pDistinct list are delivered grouped together.
103640 **
103641 ** For example, the query 
103642 **
103643 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
103644 **
103645 ** can benefit from any index on columns "b" and "c".
103646 */
103647 static int isDistinctIndex(
103648   Parse *pParse,                  /* Parsing context */
103649   WhereClause *pWC,               /* The WHERE clause */
103650   Index *pIdx,                    /* The index being considered */
103651   int base,                       /* Cursor number for the table pIdx is on */
103652   ExprList *pDistinct,            /* The DISTINCT expressions */
103653   int nEqCol                      /* Number of index columns with == */
103654 ){
103655   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
103656   int i;                          /* Iterator variable */
103657
103658   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
103659   testcase( pDistinct->nExpr==BMS-1 );
103660
103661   /* Loop through all the expressions in the distinct list. If any of them
103662   ** are not simple column references, return early. Otherwise, test if the
103663   ** WHERE clause contains a "col=X" clause. If it does, the expression
103664   ** can be ignored. If it does not, and the column does not belong to the
103665   ** same table as index pIdx, return early. Finally, if there is no
103666   ** matching "col=X" expression and the column is on the same table as pIdx,
103667   ** set the corresponding bit in variable mask.
103668   */
103669   for(i=0; i<pDistinct->nExpr; i++){
103670     WhereTerm *pTerm;
103671     Expr *p = pDistinct->a[i].pExpr;
103672     if( p->op!=TK_COLUMN ) return 0;
103673     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
103674     if( pTerm ){
103675       Expr *pX = pTerm->pExpr;
103676       CollSeq *p1 = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103677       CollSeq *p2 = sqlcipher3ExprCollSeq(pParse, p);
103678       if( p1==p2 ) continue;
103679     }
103680     if( p->iTable!=base ) return 0;
103681     mask |= (((Bitmask)1) << i);
103682   }
103683
103684   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
103685     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
103686     if( iExpr<0 ) break;
103687     mask &= ~(((Bitmask)1) << iExpr);
103688   }
103689
103690   return (mask==0);
103691 }
103692
103693
103694 /*
103695 ** Return true if the DISTINCT expression-list passed as the third argument
103696 ** is redundant. A DISTINCT list is redundant if the database contains a
103697 ** UNIQUE index that guarantees that the result of the query will be distinct
103698 ** anyway.
103699 */
103700 static int isDistinctRedundant(
103701   Parse *pParse,
103702   SrcList *pTabList,
103703   WhereClause *pWC,
103704   ExprList *pDistinct
103705 ){
103706   Table *pTab;
103707   Index *pIdx;
103708   int i;                          
103709   int iBase;
103710
103711   /* If there is more than one table or sub-select in the FROM clause of
103712   ** this query, then it will not be possible to show that the DISTINCT 
103713   ** clause is redundant. */
103714   if( pTabList->nSrc!=1 ) return 0;
103715   iBase = pTabList->a[0].iCursor;
103716   pTab = pTabList->a[0].pTab;
103717
103718   /* If any of the expressions is an IPK column on table iBase, then return 
103719   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
103720   ** current SELECT is a correlated sub-query.
103721   */
103722   for(i=0; i<pDistinct->nExpr; i++){
103723     Expr *p = pDistinct->a[i].pExpr;
103724     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
103725   }
103726
103727   /* Loop through all indices on the table, checking each to see if it makes
103728   ** the DISTINCT qualifier redundant. It does so if:
103729   **
103730   **   1. The index is itself UNIQUE, and
103731   **
103732   **   2. All of the columns in the index are either part of the pDistinct
103733   **      list, or else the WHERE clause contains a term of the form "col=X",
103734   **      where X is a constant value. The collation sequences of the
103735   **      comparison and select-list expressions must match those of the index.
103736   */
103737   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103738     if( pIdx->onError==OE_None ) continue;
103739     for(i=0; i<pIdx->nColumn; i++){
103740       int iCol = pIdx->aiColumn[i];
103741       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) 
103742        && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
103743       ){
103744         break;
103745       }
103746     }
103747     if( i==pIdx->nColumn ){
103748       /* This index implies that the DISTINCT qualifier is redundant. */
103749       return 1;
103750     }
103751   }
103752
103753   return 0;
103754 }
103755
103756 /*
103757 ** This routine decides if pIdx can be used to satisfy the ORDER BY
103758 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
103759 ** ORDER BY clause, this routine returns 0.
103760 **
103761 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
103762 ** left-most table in the FROM clause of that same SELECT statement and
103763 ** the table has a cursor number of "base".  pIdx is an index on pTab.
103764 **
103765 ** nEqCol is the number of columns of pIdx that are used as equality
103766 ** constraints.  Any of these columns may be missing from the ORDER BY
103767 ** clause and the match can still be a success.
103768 **
103769 ** All terms of the ORDER BY that match against the index must be either
103770 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
103771 ** index do not need to satisfy this constraint.)  The *pbRev value is
103772 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
103773 ** the ORDER BY clause is all ASC.
103774 */
103775 static int isSortingIndex(
103776   Parse *pParse,          /* Parsing context */
103777   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
103778   Index *pIdx,            /* The index we are testing */
103779   int base,               /* Cursor number for the table to be sorted */
103780   ExprList *pOrderBy,     /* The ORDER BY clause */
103781   int nEqCol,             /* Number of index columns with == constraints */
103782   int wsFlags,            /* Index usages flags */
103783   int *pbRev              /* Set to 1 if ORDER BY is DESC */
103784 ){
103785   int i, j;                       /* Loop counters */
103786   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
103787   int nTerm;                      /* Number of ORDER BY terms */
103788   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
103789   sqlcipher3 *db = pParse->db;
103790
103791   if( !pOrderBy ) return 0;
103792   if( wsFlags & WHERE_COLUMN_IN ) return 0;
103793   if( pIdx->bUnordered ) return 0;
103794
103795   nTerm = pOrderBy->nExpr;
103796   assert( nTerm>0 );
103797
103798   /* Argument pIdx must either point to a 'real' named index structure, 
103799   ** or an index structure allocated on the stack by bestBtreeIndex() to
103800   ** represent the rowid index that is part of every table.  */
103801   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
103802
103803   /* Match terms of the ORDER BY clause against columns of
103804   ** the index.
103805   **
103806   ** Note that indices have pIdx->nColumn regular columns plus
103807   ** one additional column containing the rowid.  The rowid column
103808   ** of the index is also allowed to match against the ORDER BY
103809   ** clause.
103810   */
103811   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
103812     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
103813     CollSeq *pColl;    /* The collating sequence of pExpr */
103814     int termSortOrder; /* Sort order for this term */
103815     int iColumn;       /* The i-th column of the index.  -1 for rowid */
103816     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
103817     const char *zColl; /* Name of the collating sequence for i-th index term */
103818
103819     pExpr = pTerm->pExpr;
103820     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
103821       /* Can not use an index sort on anything that is not a column in the
103822       ** left-most table of the FROM clause */
103823       break;
103824     }
103825     pColl = sqlcipher3ExprCollSeq(pParse, pExpr);
103826     if( !pColl ){
103827       pColl = db->pDfltColl;
103828     }
103829     if( pIdx->zName && i<pIdx->nColumn ){
103830       iColumn = pIdx->aiColumn[i];
103831       if( iColumn==pIdx->pTable->iPKey ){
103832         iColumn = -1;
103833       }
103834       iSortOrder = pIdx->aSortOrder[i];
103835       zColl = pIdx->azColl[i];
103836     }else{
103837       iColumn = -1;
103838       iSortOrder = 0;
103839       zColl = pColl->zName;
103840     }
103841     if( pExpr->iColumn!=iColumn || sqlcipher3StrICmp(pColl->zName, zColl) ){
103842       /* Term j of the ORDER BY clause does not match column i of the index */
103843       if( i<nEqCol ){
103844         /* If an index column that is constrained by == fails to match an
103845         ** ORDER BY term, that is OK.  Just ignore that column of the index
103846         */
103847         continue;
103848       }else if( i==pIdx->nColumn ){
103849         /* Index column i is the rowid.  All other terms match. */
103850         break;
103851       }else{
103852         /* If an index column fails to match and is not constrained by ==
103853         ** then the index cannot satisfy the ORDER BY constraint.
103854         */
103855         return 0;
103856       }
103857     }
103858     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
103859     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
103860     assert( iSortOrder==0 || iSortOrder==1 );
103861     termSortOrder = iSortOrder ^ pTerm->sortOrder;
103862     if( i>nEqCol ){
103863       if( termSortOrder!=sortOrder ){
103864         /* Indices can only be used if all ORDER BY terms past the
103865         ** equality constraints are all either DESC or ASC. */
103866         return 0;
103867       }
103868     }else{
103869       sortOrder = termSortOrder;
103870     }
103871     j++;
103872     pTerm++;
103873     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
103874       /* If the indexed column is the primary key and everything matches
103875       ** so far and none of the ORDER BY terms to the right reference other
103876       ** tables in the join, then we are assured that the index can be used 
103877       ** to sort because the primary key is unique and so none of the other
103878       ** columns will make any difference
103879       */
103880       j = nTerm;
103881     }
103882   }
103883
103884   *pbRev = sortOrder!=0;
103885   if( j>=nTerm ){
103886     /* All terms of the ORDER BY clause are covered by this index so
103887     ** this index can be used for sorting. */
103888     return 1;
103889   }
103890   if( pIdx->onError!=OE_None && i==pIdx->nColumn
103891       && (wsFlags & WHERE_COLUMN_NULL)==0
103892       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
103893     /* All terms of this index match some prefix of the ORDER BY clause
103894     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
103895     ** clause reference other tables in a join.  If this is all true then
103896     ** the order by clause is superfluous.  Not that if the matching
103897     ** condition is IS NULL then the result is not necessarily unique
103898     ** even on a UNIQUE index, so disallow those cases. */
103899     return 1;
103900   }
103901   return 0;
103902 }
103903
103904 /*
103905 ** Prepare a crude estimate of the logarithm of the input value.
103906 ** The results need not be exact.  This is only used for estimating
103907 ** the total cost of performing operations with O(logN) or O(NlogN)
103908 ** complexity.  Because N is just a guess, it is no great tragedy if
103909 ** logN is a little off.
103910 */
103911 static double estLog(double N){
103912   double logN = 1;
103913   double x = 10;
103914   while( N>x ){
103915     logN += 1;
103916     x *= 10;
103917   }
103918   return logN;
103919 }
103920
103921 /*
103922 ** Two routines for printing the content of an sqlcipher3_index_info
103923 ** structure.  Used for testing and debugging only.  If neither
103924 ** SQLCIPHER_TEST or SQLCIPHER_DEBUG are defined, then these routines
103925 ** are no-ops.
103926 */
103927 #if !defined(SQLCIPHER_OMIT_VIRTUALTABLE) && defined(SQLCIPHER_DEBUG)
103928 static void TRACE_IDX_INPUTS(sqlcipher3_index_info *p){
103929   int i;
103930   if( !sqlcipher3WhereTrace ) return;
103931   for(i=0; i<p->nConstraint; i++){
103932     sqlcipher3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
103933        i,
103934        p->aConstraint[i].iColumn,
103935        p->aConstraint[i].iTermOffset,
103936        p->aConstraint[i].op,
103937        p->aConstraint[i].usable);
103938   }
103939   for(i=0; i<p->nOrderBy; i++){
103940     sqlcipher3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
103941        i,
103942        p->aOrderBy[i].iColumn,
103943        p->aOrderBy[i].desc);
103944   }
103945 }
103946 static void TRACE_IDX_OUTPUTS(sqlcipher3_index_info *p){
103947   int i;
103948   if( !sqlcipher3WhereTrace ) return;
103949   for(i=0; i<p->nConstraint; i++){
103950     sqlcipher3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
103951        i,
103952        p->aConstraintUsage[i].argvIndex,
103953        p->aConstraintUsage[i].omit);
103954   }
103955   sqlcipher3DebugPrintf("  idxNum=%d\n", p->idxNum);
103956   sqlcipher3DebugPrintf("  idxStr=%s\n", p->idxStr);
103957   sqlcipher3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
103958   sqlcipher3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
103959 }
103960 #else
103961 #define TRACE_IDX_INPUTS(A)
103962 #define TRACE_IDX_OUTPUTS(A)
103963 #endif
103964
103965 /* 
103966 ** Required because bestIndex() is called by bestOrClauseIndex() 
103967 */
103968 static void bestIndex(
103969     Parse*, WhereClause*, struct SrcList_item*,
103970     Bitmask, Bitmask, ExprList*, WhereCost*);
103971
103972 /*
103973 ** This routine attempts to find an scanning strategy that can be used 
103974 ** to optimize an 'OR' expression that is part of a WHERE clause. 
103975 **
103976 ** The table associated with FROM clause term pSrc may be either a
103977 ** regular B-Tree table or a virtual table.
103978 */
103979 static void bestOrClauseIndex(
103980   Parse *pParse,              /* The parsing context */
103981   WhereClause *pWC,           /* The WHERE clause */
103982   struct SrcList_item *pSrc,  /* The FROM clause term to search */
103983   Bitmask notReady,           /* Mask of cursors not available for indexing */
103984   Bitmask notValid,           /* Cursors not available for any purpose */
103985   ExprList *pOrderBy,         /* The ORDER BY clause */
103986   WhereCost *pCost            /* Lowest cost query plan */
103987 ){
103988 #ifndef SQLCIPHER_OMIT_OR_OPTIMIZATION
103989   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
103990   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
103991   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
103992   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
103993
103994   /* The OR-clause optimization is disallowed if the INDEXED BY or
103995   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
103996   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
103997     return;
103998   }
103999   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
104000     return;
104001   }
104002
104003   /* Search the WHERE clause terms for a usable WO_OR term. */
104004   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104005     if( pTerm->eOperator==WO_OR 
104006      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
104007      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
104008     ){
104009       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
104010       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
104011       WhereTerm *pOrTerm;
104012       int flags = WHERE_MULTI_OR;
104013       double rTotal = 0;
104014       double nRow = 0;
104015       Bitmask used = 0;
104016
104017       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
104018         WhereCost sTermCost;
104019         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
104020           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
104021         ));
104022         if( pOrTerm->eOperator==WO_AND ){
104023           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
104024           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
104025         }else if( pOrTerm->leftCursor==iCur ){
104026           WhereClause tempWC;
104027           tempWC.pParse = pWC->pParse;
104028           tempWC.pMaskSet = pWC->pMaskSet;
104029           tempWC.pOuter = pWC;
104030           tempWC.op = TK_AND;
104031           tempWC.a = pOrTerm;
104032           tempWC.wctrlFlags = 0;
104033           tempWC.nTerm = 1;
104034           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
104035         }else{
104036           continue;
104037         }
104038         rTotal += sTermCost.rCost;
104039         nRow += sTermCost.plan.nRow;
104040         used |= sTermCost.used;
104041         if( rTotal>=pCost->rCost ) break;
104042       }
104043
104044       /* If there is an ORDER BY clause, increase the scan cost to account 
104045       ** for the cost of the sort. */
104046       if( pOrderBy!=0 ){
104047         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104048                     rTotal, rTotal+nRow*estLog(nRow)));
104049         rTotal += nRow*estLog(nRow);
104050       }
104051
104052       /* If the cost of scanning using this OR term for optimization is
104053       ** less than the current cost stored in pCost, replace the contents
104054       ** of pCost. */
104055       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104056       if( rTotal<pCost->rCost ){
104057         pCost->rCost = rTotal;
104058         pCost->used = used;
104059         pCost->plan.nRow = nRow;
104060         pCost->plan.wsFlags = flags;
104061         pCost->plan.u.pTerm = pTerm;
104062       }
104063     }
104064   }
104065 #endif /* SQLCIPHER_OMIT_OR_OPTIMIZATION */
104066 }
104067
104068 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
104069 /*
104070 ** Return TRUE if the WHERE clause term pTerm is of a form where it
104071 ** could be used with an index to access pSrc, assuming an appropriate
104072 ** index existed.
104073 */
104074 static int termCanDriveIndex(
104075   WhereTerm *pTerm,              /* WHERE clause term to check */
104076   struct SrcList_item *pSrc,     /* Table we are trying to access */
104077   Bitmask notReady               /* Tables in outer loops of the join */
104078 ){
104079   char aff;
104080   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104081   if( pTerm->eOperator!=WO_EQ ) return 0;
104082   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104083   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104084   if( !sqlcipher3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104085   return 1;
104086 }
104087 #endif
104088
104089 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
104090 /*
104091 ** If the query plan for pSrc specified in pCost is a full table scan
104092 ** and indexing is allows (if there is no NOT INDEXED clause) and it
104093 ** possible to construct a transient index that would perform better
104094 ** than a full table scan even when the cost of constructing the index
104095 ** is taken into account, then alter the query plan to use the
104096 ** transient index.
104097 */
104098 static void bestAutomaticIndex(
104099   Parse *pParse,              /* The parsing context */
104100   WhereClause *pWC,           /* The WHERE clause */
104101   struct SrcList_item *pSrc,  /* The FROM clause term to search */
104102   Bitmask notReady,           /* Mask of cursors that are not available */
104103   WhereCost *pCost            /* Lowest cost query plan */
104104 ){
104105   double nTableRow;           /* Rows in the input table */
104106   double logN;                /* log(nTableRow) */
104107   double costTempIdx;         /* per-query cost of the transient index */
104108   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104109   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104110   Table *pTable;              /* Table tht might be indexed */
104111
104112   if( pParse->nQueryLoop<=(double)1 ){
104113     /* There is no point in building an automatic index for a single scan */
104114     return;
104115   }
104116   if( (pParse->db->flags & SQLCIPHER_AutoIndex)==0 ){
104117     /* Automatic indices are disabled at run-time */
104118     return;
104119   }
104120   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
104121     /* We already have some kind of index in use for this query. */
104122     return;
104123   }
104124   if( pSrc->notIndexed ){
104125     /* The NOT INDEXED clause appears in the SQL. */
104126     return;
104127   }
104128   if( pSrc->isCorrelated ){
104129     /* The source is a correlated sub-query. No point in indexing it. */
104130     return;
104131   }
104132
104133   assert( pParse->nQueryLoop >= (double)1 );
104134   pTable = pSrc->pTab;
104135   nTableRow = pTable->nRowEst;
104136   logN = estLog(nTableRow);
104137   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104138   if( costTempIdx>=pCost->rCost ){
104139     /* The cost of creating the transient table would be greater than
104140     ** doing the full table scan */
104141     return;
104142   }
104143
104144   /* Search for any equality comparison term */
104145   pWCEnd = &pWC->a[pWC->nTerm];
104146   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104147     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104148       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104149                     pCost->rCost, costTempIdx));
104150       pCost->rCost = costTempIdx;
104151       pCost->plan.nRow = logN + 1;
104152       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
104153       pCost->used = pTerm->prereqRight;
104154       break;
104155     }
104156   }
104157 }
104158 #else
104159 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
104160 #endif /* SQLCIPHER_OMIT_AUTOMATIC_INDEX */
104161
104162
104163 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
104164 /*
104165 ** Generate code to construct the Index object for an automatic index
104166 ** and to set up the WhereLevel object pLevel so that the code generator
104167 ** makes use of the automatic index.
104168 */
104169 static void constructAutomaticIndex(
104170   Parse *pParse,              /* The parsing context */
104171   WhereClause *pWC,           /* The WHERE clause */
104172   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104173   Bitmask notReady,           /* Mask of cursors that are not available */
104174   WhereLevel *pLevel          /* Write new index here */
104175 ){
104176   int nColumn;                /* Number of columns in the constructed index */
104177   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104178   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104179   int nByte;                  /* Byte of memory needed for pIdx */
104180   Index *pIdx;                /* Object describing the transient index */
104181   Vdbe *v;                    /* Prepared statement under construction */
104182   int regIsInit;              /* Register set by initialization */
104183   int addrInit;               /* Address of the initialization bypass jump */
104184   Table *pTable;              /* The table being indexed */
104185   KeyInfo *pKeyinfo;          /* Key information for the index */   
104186   int addrTop;                /* Top of the index fill loop */
104187   int regRecord;              /* Register holding an index record */
104188   int n;                      /* Column counter */
104189   int i;                      /* Loop counter */
104190   int mxBitCol;               /* Maximum column in pSrc->colUsed */
104191   CollSeq *pColl;             /* Collating sequence to on a column */
104192   Bitmask idxCols;            /* Bitmap of columns used for indexing */
104193   Bitmask extraCols;          /* Bitmap of additional columns */
104194
104195   /* Generate code to skip over the creation and initialization of the
104196   ** transient index on 2nd and subsequent iterations of the loop. */
104197   v = pParse->pVdbe;
104198   assert( v!=0 );
104199   regIsInit = ++pParse->nMem;
104200   addrInit = sqlcipher3VdbeAddOp1(v, OP_Once, regIsInit);
104201
104202   /* Count the number of columns that will be added to the index
104203   ** and used to match WHERE clause constraints */
104204   nColumn = 0;
104205   pTable = pSrc->pTab;
104206   pWCEnd = &pWC->a[pWC->nTerm];
104207   idxCols = 0;
104208   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104209     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104210       int iCol = pTerm->u.leftColumn;
104211       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104212       testcase( iCol==BMS );
104213       testcase( iCol==BMS-1 );
104214       if( (idxCols & cMask)==0 ){
104215         nColumn++;
104216         idxCols |= cMask;
104217       }
104218     }
104219   }
104220   assert( nColumn>0 );
104221   pLevel->plan.nEq = nColumn;
104222
104223   /* Count the number of additional columns needed to create a
104224   ** covering index.  A "covering index" is an index that contains all
104225   ** columns that are needed by the query.  With a covering index, the
104226   ** original table never needs to be accessed.  Automatic indices must
104227   ** be a covering index because the index will not be updated if the
104228   ** original table changes and the index and table cannot both be used
104229   ** if they go out of sync.
104230   */
104231   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104232   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104233   testcase( pTable->nCol==BMS-1 );
104234   testcase( pTable->nCol==BMS-2 );
104235   for(i=0; i<mxBitCol; i++){
104236     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104237   }
104238   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104239     nColumn += pTable->nCol - BMS + 1;
104240   }
104241   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104242
104243   /* Construct the Index object to describe this index */
104244   nByte = sizeof(Index);
104245   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104246   nByte += nColumn*sizeof(char*);   /* Index.azColl */
104247   nByte += nColumn;                 /* Index.aSortOrder */
104248   pIdx = sqlcipher3DbMallocZero(pParse->db, nByte);
104249   if( pIdx==0 ) return;
104250   pLevel->plan.u.pIdx = pIdx;
104251   pIdx->azColl = (char**)&pIdx[1];
104252   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104253   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104254   pIdx->zName = "auto-index";
104255   pIdx->nColumn = nColumn;
104256   pIdx->pTable = pTable;
104257   n = 0;
104258   idxCols = 0;
104259   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104260     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104261       int iCol = pTerm->u.leftColumn;
104262       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104263       if( (idxCols & cMask)==0 ){
104264         Expr *pX = pTerm->pExpr;
104265         idxCols |= cMask;
104266         pIdx->aiColumn[n] = pTerm->u.leftColumn;
104267         pColl = sqlcipher3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104268         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104269         n++;
104270       }
104271     }
104272   }
104273   assert( (u32)n==pLevel->plan.nEq );
104274
104275   /* Add additional columns needed to make the automatic index into
104276   ** a covering index */
104277   for(i=0; i<mxBitCol; i++){
104278     if( extraCols & (((Bitmask)1)<<i) ){
104279       pIdx->aiColumn[n] = i;
104280       pIdx->azColl[n] = "BINARY";
104281       n++;
104282     }
104283   }
104284   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104285     for(i=BMS-1; i<pTable->nCol; i++){
104286       pIdx->aiColumn[n] = i;
104287       pIdx->azColl[n] = "BINARY";
104288       n++;
104289     }
104290   }
104291   assert( n==nColumn );
104292
104293   /* Create the automatic index */
104294   pKeyinfo = sqlcipher3IndexKeyinfo(pParse, pIdx);
104295   assert( pLevel->iIdxCur>=0 );
104296   sqlcipher3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
104297                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
104298   VdbeComment((v, "for %s", pTable->zName));
104299
104300   /* Fill the automatic index with content */
104301   addrTop = sqlcipher3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
104302   regRecord = sqlcipher3GetTempReg(pParse);
104303   sqlcipher3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
104304   sqlcipher3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
104305   sqlcipher3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
104306   sqlcipher3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
104307   sqlcipher3VdbeChangeP5(v, SQLCIPHER_STMTSTATUS_AUTOINDEX);
104308   sqlcipher3VdbeJumpHere(v, addrTop);
104309   sqlcipher3ReleaseTempReg(pParse, regRecord);
104310   
104311   /* Jump here when skipping the initialization */
104312   sqlcipher3VdbeJumpHere(v, addrInit);
104313 }
104314 #endif /* SQLCIPHER_OMIT_AUTOMATIC_INDEX */
104315
104316 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
104317 /*
104318 ** Allocate and populate an sqlcipher3_index_info structure. It is the 
104319 ** responsibility of the caller to eventually release the structure
104320 ** by passing the pointer returned by this function to sqlcipher3_free().
104321 */
104322 static sqlcipher3_index_info *allocateIndexInfo(
104323   Parse *pParse, 
104324   WhereClause *pWC,
104325   struct SrcList_item *pSrc,
104326   ExprList *pOrderBy
104327 ){
104328   int i, j;
104329   int nTerm;
104330   struct sqlcipher3_index_constraint *pIdxCons;
104331   struct sqlcipher3_index_orderby *pIdxOrderBy;
104332   struct sqlcipher3_index_constraint_usage *pUsage;
104333   WhereTerm *pTerm;
104334   int nOrderBy;
104335   sqlcipher3_index_info *pIdxInfo;
104336
104337   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
104338
104339   /* Count the number of possible WHERE clause constraints referring
104340   ** to this virtual table */
104341   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104342     if( pTerm->leftCursor != pSrc->iCursor ) continue;
104343     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104344     testcase( pTerm->eOperator==WO_IN );
104345     testcase( pTerm->eOperator==WO_ISNULL );
104346     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104347     if( pTerm->wtFlags & TERM_VNULL ) continue;
104348     nTerm++;
104349   }
104350
104351   /* If the ORDER BY clause contains only columns in the current 
104352   ** virtual table then allocate space for the aOrderBy part of
104353   ** the sqlcipher3_index_info structure.
104354   */
104355   nOrderBy = 0;
104356   if( pOrderBy ){
104357     for(i=0; i<pOrderBy->nExpr; i++){
104358       Expr *pExpr = pOrderBy->a[i].pExpr;
104359       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
104360     }
104361     if( i==pOrderBy->nExpr ){
104362       nOrderBy = pOrderBy->nExpr;
104363     }
104364   }
104365
104366   /* Allocate the sqlcipher3_index_info structure
104367   */
104368   pIdxInfo = sqlcipher3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
104369                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
104370                            + sizeof(*pIdxOrderBy)*nOrderBy );
104371   if( pIdxInfo==0 ){
104372     sqlcipher3ErrorMsg(pParse, "out of memory");
104373     /* (double)0 In case of SQLCIPHER_OMIT_FLOATING_POINT... */
104374     return 0;
104375   }
104376
104377   /* Initialize the structure.  The sqlcipher3_index_info structure contains
104378   ** many fields that are declared "const" to prevent xBestIndex from
104379   ** changing them.  We have to do some funky casting in order to
104380   ** initialize those fields.
104381   */
104382   pIdxCons = (struct sqlcipher3_index_constraint*)&pIdxInfo[1];
104383   pIdxOrderBy = (struct sqlcipher3_index_orderby*)&pIdxCons[nTerm];
104384   pUsage = (struct sqlcipher3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
104385   *(int*)&pIdxInfo->nConstraint = nTerm;
104386   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
104387   *(struct sqlcipher3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
104388   *(struct sqlcipher3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
104389   *(struct sqlcipher3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
104390                                                                    pUsage;
104391
104392   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104393     if( pTerm->leftCursor != pSrc->iCursor ) continue;
104394     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104395     testcase( pTerm->eOperator==WO_IN );
104396     testcase( pTerm->eOperator==WO_ISNULL );
104397     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104398     if( pTerm->wtFlags & TERM_VNULL ) continue;
104399     pIdxCons[j].iColumn = pTerm->u.leftColumn;
104400     pIdxCons[j].iTermOffset = i;
104401     pIdxCons[j].op = (u8)pTerm->eOperator;
104402     /* The direct assignment in the previous line is possible only because
104403     ** the WO_ and SQLCIPHER_INDEX_CONSTRAINT_ codes are identical.  The
104404     ** following asserts verify this fact. */
104405     assert( WO_EQ==SQLCIPHER_INDEX_CONSTRAINT_EQ );
104406     assert( WO_LT==SQLCIPHER_INDEX_CONSTRAINT_LT );
104407     assert( WO_LE==SQLCIPHER_INDEX_CONSTRAINT_LE );
104408     assert( WO_GT==SQLCIPHER_INDEX_CONSTRAINT_GT );
104409     assert( WO_GE==SQLCIPHER_INDEX_CONSTRAINT_GE );
104410     assert( WO_MATCH==SQLCIPHER_INDEX_CONSTRAINT_MATCH );
104411     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
104412     j++;
104413   }
104414   for(i=0; i<nOrderBy; i++){
104415     Expr *pExpr = pOrderBy->a[i].pExpr;
104416     pIdxOrderBy[i].iColumn = pExpr->iColumn;
104417     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
104418   }
104419
104420   return pIdxInfo;
104421 }
104422
104423 /*
104424 ** The table object reference passed as the second argument to this function
104425 ** must represent a virtual table. This function invokes the xBestIndex()
104426 ** method of the virtual table with the sqlcipher3_index_info pointer passed
104427 ** as the argument.
104428 **
104429 ** If an error occurs, pParse is populated with an error message and a
104430 ** non-zero value is returned. Otherwise, 0 is returned and the output
104431 ** part of the sqlcipher3_index_info structure is left populated.
104432 **
104433 ** Whether or not an error is returned, it is the responsibility of the
104434 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
104435 ** that this is required.
104436 */
104437 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlcipher3_index_info *p){
104438   sqlcipher3_vtab *pVtab = sqlcipher3GetVTable(pParse->db, pTab)->pVtab;
104439   int i;
104440   int rc;
104441
104442   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
104443   TRACE_IDX_INPUTS(p);
104444   rc = pVtab->pModule->xBestIndex(pVtab, p);
104445   TRACE_IDX_OUTPUTS(p);
104446
104447   if( rc!=SQLCIPHER_OK ){
104448     if( rc==SQLCIPHER_NOMEM ){
104449       pParse->db->mallocFailed = 1;
104450     }else if( !pVtab->zErrMsg ){
104451       sqlcipher3ErrorMsg(pParse, "%s", sqlcipher3ErrStr(rc));
104452     }else{
104453       sqlcipher3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
104454     }
104455   }
104456   sqlcipher3_free(pVtab->zErrMsg);
104457   pVtab->zErrMsg = 0;
104458
104459   for(i=0; i<p->nConstraint; i++){
104460     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
104461       sqlcipher3ErrorMsg(pParse, 
104462           "table %s: xBestIndex returned an invalid plan", pTab->zName);
104463     }
104464   }
104465
104466   return pParse->nErr;
104467 }
104468
104469
104470 /*
104471 ** Compute the best index for a virtual table.
104472 **
104473 ** The best index is computed by the xBestIndex method of the virtual
104474 ** table module.  This routine is really just a wrapper that sets up
104475 ** the sqlcipher3_index_info structure that is used to communicate with
104476 ** xBestIndex.
104477 **
104478 ** In a join, this routine might be called multiple times for the
104479 ** same virtual table.  The sqlcipher3_index_info structure is created
104480 ** and initialized on the first invocation and reused on all subsequent
104481 ** invocations.  The sqlcipher3_index_info structure is also used when
104482 ** code is generated to access the virtual table.  The whereInfoDelete() 
104483 ** routine takes care of freeing the sqlcipher3_index_info structure after
104484 ** everybody has finished with it.
104485 */
104486 static void bestVirtualIndex(
104487   Parse *pParse,                  /* The parsing context */
104488   WhereClause *pWC,               /* The WHERE clause */
104489   struct SrcList_item *pSrc,      /* The FROM clause term to search */
104490   Bitmask notReady,               /* Mask of cursors not available for index */
104491   Bitmask notValid,               /* Cursors not valid for any purpose */
104492   ExprList *pOrderBy,             /* The order by clause */
104493   WhereCost *pCost,               /* Lowest cost query plan */
104494   sqlcipher3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
104495 ){
104496   Table *pTab = pSrc->pTab;
104497   sqlcipher3_index_info *pIdxInfo;
104498   struct sqlcipher3_index_constraint *pIdxCons;
104499   struct sqlcipher3_index_constraint_usage *pUsage;
104500   WhereTerm *pTerm;
104501   int i, j;
104502   int nOrderBy;
104503   double rCost;
104504
104505   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
104506   ** malloc in allocateIndexInfo() fails and this function returns leaving
104507   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
104508   */
104509   memset(pCost, 0, sizeof(*pCost));
104510   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
104511
104512   /* If the sqlcipher3_index_info structure has not been previously
104513   ** allocated and initialized, then allocate and initialize it now.
104514   */
104515   pIdxInfo = *ppIdxInfo;
104516   if( pIdxInfo==0 ){
104517     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
104518   }
104519   if( pIdxInfo==0 ){
104520     return;
104521   }
104522
104523   /* At this point, the sqlcipher3_index_info structure that pIdxInfo points
104524   ** to will have been initialized, either during the current invocation or
104525   ** during some prior invocation.  Now we just have to customize the
104526   ** details of pIdxInfo for the current invocation and pass it to
104527   ** xBestIndex.
104528   */
104529
104530   /* The module name must be defined. Also, by this point there must
104531   ** be a pointer to an sqlcipher3_vtab structure. Otherwise
104532   ** sqlcipher3ViewGetColumnNames() would have picked up the error. 
104533   */
104534   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
104535   assert( sqlcipher3GetVTable(pParse->db, pTab) );
104536
104537   /* Set the aConstraint[].usable fields and initialize all 
104538   ** output variables to zero.
104539   **
104540   ** aConstraint[].usable is true for constraints where the right-hand
104541   ** side contains only references to tables to the left of the current
104542   ** table.  In other words, if the constraint is of the form:
104543   **
104544   **           column = expr
104545   **
104546   ** and we are evaluating a join, then the constraint on column is 
104547   ** only valid if all tables referenced in expr occur to the left
104548   ** of the table containing column.
104549   **
104550   ** The aConstraints[] array contains entries for all constraints
104551   ** on the current table.  That way we only have to compute it once
104552   ** even though we might try to pick the best index multiple times.
104553   ** For each attempt at picking an index, the order of tables in the
104554   ** join might be different so we have to recompute the usable flag
104555   ** each time.
104556   */
104557   pIdxCons = *(struct sqlcipher3_index_constraint**)&pIdxInfo->aConstraint;
104558   pUsage = pIdxInfo->aConstraintUsage;
104559   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
104560     j = pIdxCons->iTermOffset;
104561     pTerm = &pWC->a[j];
104562     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
104563   }
104564   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
104565   if( pIdxInfo->needToFreeIdxStr ){
104566     sqlcipher3_free(pIdxInfo->idxStr);
104567   }
104568   pIdxInfo->idxStr = 0;
104569   pIdxInfo->idxNum = 0;
104570   pIdxInfo->needToFreeIdxStr = 0;
104571   pIdxInfo->orderByConsumed = 0;
104572   /* ((double)2) In case of SQLCIPHER_OMIT_FLOATING_POINT... */
104573   pIdxInfo->estimatedCost = SQLCIPHER_BIG_DBL / ((double)2);
104574   nOrderBy = pIdxInfo->nOrderBy;
104575   if( !pOrderBy ){
104576     pIdxInfo->nOrderBy = 0;
104577   }
104578
104579   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
104580     return;
104581   }
104582
104583   pIdxCons = *(struct sqlcipher3_index_constraint**)&pIdxInfo->aConstraint;
104584   for(i=0; i<pIdxInfo->nConstraint; i++){
104585     if( pUsage[i].argvIndex>0 ){
104586       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
104587     }
104588   }
104589
104590   /* If there is an ORDER BY clause, and the selected virtual table index
104591   ** does not satisfy it, increase the cost of the scan accordingly. This
104592   ** matches the processing for non-virtual tables in bestBtreeIndex().
104593   */
104594   rCost = pIdxInfo->estimatedCost;
104595   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
104596     rCost += estLog(rCost)*rCost;
104597   }
104598
104599   /* The cost is not allowed to be larger than SQLCIPHER_BIG_DBL (the
104600   ** inital value of lowestCost in this loop. If it is, then the
104601   ** (cost<lowestCost) test below will never be true.
104602   ** 
104603   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
104604   ** is defined.
104605   */
104606   if( (SQLCIPHER_BIG_DBL/((double)2))<rCost ){
104607     pCost->rCost = (SQLCIPHER_BIG_DBL/((double)2));
104608   }else{
104609     pCost->rCost = rCost;
104610   }
104611   pCost->plan.u.pVtabIdx = pIdxInfo;
104612   if( pIdxInfo->orderByConsumed ){
104613     pCost->plan.wsFlags |= WHERE_ORDERBY;
104614   }
104615   pCost->plan.nEq = 0;
104616   pIdxInfo->nOrderBy = nOrderBy;
104617
104618   /* Try to find a more efficient access pattern by using multiple indexes
104619   ** to optimize an OR expression within the WHERE clause. 
104620   */
104621   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
104622 }
104623 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
104624
104625 #ifdef SQLCIPHER_ENABLE_STAT3
104626 /*
104627 ** Estimate the location of a particular key among all keys in an
104628 ** index.  Store the results in aStat as follows:
104629 **
104630 **    aStat[0]      Est. number of rows less than pVal
104631 **    aStat[1]      Est. number of rows equal to pVal
104632 **
104633 ** Return SQLCIPHER_OK on success.
104634 */
104635 static int whereKeyStats(
104636   Parse *pParse,              /* Database connection */
104637   Index *pIdx,                /* Index to consider domain of */
104638   sqlcipher3_value *pVal,        /* Value to consider */
104639   int roundUp,                /* Round up if true.  Round down if false */
104640   tRowcnt *aStat              /* OUT: stats written here */
104641 ){
104642   tRowcnt n;
104643   IndexSample *aSample;
104644   int i, eType;
104645   int isEq = 0;
104646   i64 v;
104647   double r, rS;
104648
104649   assert( roundUp==0 || roundUp==1 );
104650   assert( pIdx->nSample>0 );
104651   if( pVal==0 ) return SQLCIPHER_ERROR;
104652   n = pIdx->aiRowEst[0];
104653   aSample = pIdx->aSample;
104654   eType = sqlcipher3_value_type(pVal);
104655
104656   if( eType==SQLCIPHER_INTEGER ){
104657     v = sqlcipher3_value_int64(pVal);
104658     r = (i64)v;
104659     for(i=0; i<pIdx->nSample; i++){
104660       if( aSample[i].eType==SQLCIPHER_NULL ) continue;
104661       if( aSample[i].eType>=SQLCIPHER_TEXT ) break;
104662       if( aSample[i].eType==SQLCIPHER_INTEGER ){
104663         if( aSample[i].u.i>=v ){
104664           isEq = aSample[i].u.i==v;
104665           break;
104666         }
104667       }else{
104668         assert( aSample[i].eType==SQLCIPHER_FLOAT );
104669         if( aSample[i].u.r>=r ){
104670           isEq = aSample[i].u.r==r;
104671           break;
104672         }
104673       }
104674     }
104675   }else if( eType==SQLCIPHER_FLOAT ){
104676     r = sqlcipher3_value_double(pVal);
104677     for(i=0; i<pIdx->nSample; i++){
104678       if( aSample[i].eType==SQLCIPHER_NULL ) continue;
104679       if( aSample[i].eType>=SQLCIPHER_TEXT ) break;
104680       if( aSample[i].eType==SQLCIPHER_FLOAT ){
104681         rS = aSample[i].u.r;
104682       }else{
104683         rS = aSample[i].u.i;
104684       }
104685       if( rS>=r ){
104686         isEq = rS==r;
104687         break;
104688       }
104689     }
104690   }else if( eType==SQLCIPHER_NULL ){
104691     i = 0;
104692     if( aSample[0].eType==SQLCIPHER_NULL ) isEq = 1;
104693   }else{
104694     assert( eType==SQLCIPHER_TEXT || eType==SQLCIPHER_BLOB );
104695     for(i=0; i<pIdx->nSample; i++){
104696       if( aSample[i].eType==SQLCIPHER_TEXT || aSample[i].eType==SQLCIPHER_BLOB ){
104697         break;
104698       }
104699     }
104700     if( i<pIdx->nSample ){      
104701       sqlcipher3 *db = pParse->db;
104702       CollSeq *pColl;
104703       const u8 *z;
104704       if( eType==SQLCIPHER_BLOB ){
104705         z = (const u8 *)sqlcipher3_value_blob(pVal);
104706         pColl = db->pDfltColl;
104707         assert( pColl->enc==SQLCIPHER_UTF8 );
104708       }else{
104709         pColl = sqlcipher3GetCollSeq(db, SQLCIPHER_UTF8, 0, *pIdx->azColl);
104710         if( pColl==0 ){
104711           sqlcipher3ErrorMsg(pParse, "no such collation sequence: %s",
104712                           *pIdx->azColl);
104713           return SQLCIPHER_ERROR;
104714         }
104715         z = (const u8 *)sqlcipher3ValueText(pVal, pColl->enc);
104716         if( !z ){
104717           return SQLCIPHER_NOMEM;
104718         }
104719         assert( z && pColl && pColl->xCmp );
104720       }
104721       n = sqlcipher3ValueBytes(pVal, pColl->enc);
104722   
104723       for(; i<pIdx->nSample; i++){
104724         int c;
104725         int eSampletype = aSample[i].eType;
104726         if( eSampletype<eType ) continue;
104727         if( eSampletype!=eType ) break;
104728 #ifndef SQLCIPHER_OMIT_UTF16
104729         if( pColl->enc!=SQLCIPHER_UTF8 ){
104730           int nSample;
104731           char *zSample = sqlcipher3Utf8to16(
104732               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
104733           );
104734           if( !zSample ){
104735             assert( db->mallocFailed );
104736             return SQLCIPHER_NOMEM;
104737           }
104738           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
104739           sqlcipher3DbFree(db, zSample);
104740         }else
104741 #endif
104742         {
104743           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
104744         }
104745         if( c>=0 ){
104746           if( c==0 ) isEq = 1;
104747           break;
104748         }
104749       }
104750     }
104751   }
104752
104753   /* At this point, aSample[i] is the first sample that is greater than
104754   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
104755   ** than pVal.  If aSample[i]==pVal, then isEq==1.
104756   */
104757   if( isEq ){
104758     assert( i<pIdx->nSample );
104759     aStat[0] = aSample[i].nLt;
104760     aStat[1] = aSample[i].nEq;
104761   }else{
104762     tRowcnt iLower, iUpper, iGap;
104763     if( i==0 ){
104764       iLower = 0;
104765       iUpper = aSample[0].nLt;
104766     }else{
104767       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
104768       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
104769     }
104770     aStat[1] = pIdx->avgEq;
104771     if( iLower>=iUpper ){
104772       iGap = 0;
104773     }else{
104774       iGap = iUpper - iLower;
104775     }
104776     if( roundUp ){
104777       iGap = (iGap*2)/3;
104778     }else{
104779       iGap = iGap/3;
104780     }
104781     aStat[0] = iLower + iGap;
104782   }
104783   return SQLCIPHER_OK;
104784 }
104785 #endif /* SQLCIPHER_ENABLE_STAT3 */
104786
104787 /*
104788 ** If expression pExpr represents a literal value, set *pp to point to
104789 ** an sqlcipher3_value structure containing the same value, with affinity
104790 ** aff applied to it, before returning. It is the responsibility of the 
104791 ** caller to eventually release this structure by passing it to 
104792 ** sqlcipher3ValueFree().
104793 **
104794 ** If the current parse is a recompile (sqlcipher3Reprepare()) and pExpr
104795 ** is an SQL variable that currently has a non-NULL value bound to it,
104796 ** create an sqlcipher3_value structure containing this value, again with
104797 ** affinity aff applied to it, instead.
104798 **
104799 ** If neither of the above apply, set *pp to NULL.
104800 **
104801 ** If an error occurs, return an error code. Otherwise, SQLCIPHER_OK.
104802 */
104803 #ifdef SQLCIPHER_ENABLE_STAT3
104804 static int valueFromExpr(
104805   Parse *pParse, 
104806   Expr *pExpr, 
104807   u8 aff, 
104808   sqlcipher3_value **pp
104809 ){
104810   if( pExpr->op==TK_VARIABLE
104811    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
104812   ){
104813     int iVar = pExpr->iColumn;
104814     sqlcipher3VdbeSetVarmask(pParse->pVdbe, iVar);
104815     *pp = sqlcipher3VdbeGetValue(pParse->pReprepare, iVar, aff);
104816     return SQLCIPHER_OK;
104817   }
104818   return sqlcipher3ValueFromExpr(pParse->db, pExpr, SQLCIPHER_UTF8, aff, pp);
104819 }
104820 #endif
104821
104822 /*
104823 ** This function is used to estimate the number of rows that will be visited
104824 ** by scanning an index for a range of values. The range may have an upper
104825 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
104826 ** and lower bounds are represented by pLower and pUpper respectively. For
104827 ** example, assuming that index p is on t1(a):
104828 **
104829 **   ... FROM t1 WHERE a > ? AND a < ? ...
104830 **                    |_____|   |_____|
104831 **                       |         |
104832 **                     pLower    pUpper
104833 **
104834 ** If either of the upper or lower bound is not present, then NULL is passed in
104835 ** place of the corresponding WhereTerm.
104836 **
104837 ** The nEq parameter is passed the index of the index column subject to the
104838 ** range constraint. Or, equivalently, the number of equality constraints
104839 ** optimized by the proposed index scan. For example, assuming index p is
104840 ** on t1(a, b), and the SQL query is:
104841 **
104842 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
104843 **
104844 ** then nEq should be passed the value 1 (as the range restricted column,
104845 ** b, is the second left-most column of the index). Or, if the query is:
104846 **
104847 **   ... FROM t1 WHERE a > ? AND a < ? ...
104848 **
104849 ** then nEq should be passed 0.
104850 **
104851 ** The returned value is an integer divisor to reduce the estimated
104852 ** search space.  A return value of 1 means that range constraints are
104853 ** no help at all.  A return value of 2 means range constraints are
104854 ** expected to reduce the search space by half.  And so forth...
104855 **
104856 ** In the absence of sqlcipher_stat3 ANALYZE data, each range inequality
104857 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
104858 ** results in a return of 4 and a range constraint (x>? AND x<?) results
104859 ** in a return of 16.
104860 */
104861 static int whereRangeScanEst(
104862   Parse *pParse,       /* Parsing & code generating context */
104863   Index *p,            /* The index containing the range-compared column; "x" */
104864   int nEq,             /* index into p->aCol[] of the range-compared column */
104865   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
104866   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
104867   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
104868 ){
104869   int rc = SQLCIPHER_OK;
104870
104871 #ifdef SQLCIPHER_ENABLE_STAT3
104872
104873   if( nEq==0 && p->nSample ){
104874     sqlcipher3_value *pRangeVal;
104875     tRowcnt iLower = 0;
104876     tRowcnt iUpper = p->aiRowEst[0];
104877     tRowcnt a[2];
104878     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
104879
104880     if( pLower ){
104881       Expr *pExpr = pLower->pExpr->pRight;
104882       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
104883       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
104884       if( rc==SQLCIPHER_OK
104885        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLCIPHER_OK
104886       ){
104887         iLower = a[0];
104888         if( pLower->eOperator==WO_GT ) iLower += a[1];
104889       }
104890       sqlcipher3ValueFree(pRangeVal);
104891     }
104892     if( rc==SQLCIPHER_OK && pUpper ){
104893       Expr *pExpr = pUpper->pExpr->pRight;
104894       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
104895       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
104896       if( rc==SQLCIPHER_OK
104897        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLCIPHER_OK
104898       ){
104899         iUpper = a[0];
104900         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
104901       }
104902       sqlcipher3ValueFree(pRangeVal);
104903     }
104904     if( rc==SQLCIPHER_OK ){
104905       if( iUpper<=iLower ){
104906         *pRangeDiv = (double)p->aiRowEst[0];
104907       }else{
104908         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
104909       }
104910       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
104911                   (u32)iLower, (u32)iUpper, *pRangeDiv));
104912       return SQLCIPHER_OK;
104913     }
104914   }
104915 #else
104916   UNUSED_PARAMETER(pParse);
104917   UNUSED_PARAMETER(p);
104918   UNUSED_PARAMETER(nEq);
104919 #endif
104920   assert( pLower || pUpper );
104921   *pRangeDiv = (double)1;
104922   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
104923   if( pUpper ) *pRangeDiv *= (double)4;
104924   return rc;
104925 }
104926
104927 #ifdef SQLCIPHER_ENABLE_STAT3
104928 /*
104929 ** Estimate the number of rows that will be returned based on
104930 ** an equality constraint x=VALUE and where that VALUE occurs in
104931 ** the histogram data.  This only works when x is the left-most
104932 ** column of an index and sqlcipher_stat3 histogram data is available
104933 ** for that index.  When pExpr==NULL that means the constraint is
104934 ** "x IS NULL" instead of "x=VALUE".
104935 **
104936 ** Write the estimated row count into *pnRow and return SQLCIPHER_OK. 
104937 ** If unable to make an estimate, leave *pnRow unchanged and return
104938 ** non-zero.
104939 **
104940 ** This routine can fail if it is unable to load a collating sequence
104941 ** required for string comparison, or if unable to allocate memory
104942 ** for a UTF conversion required for comparison.  The error is stored
104943 ** in the pParse structure.
104944 */
104945 static int whereEqualScanEst(
104946   Parse *pParse,       /* Parsing & code generating context */
104947   Index *p,            /* The index whose left-most column is pTerm */
104948   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
104949   double *pnRow        /* Write the revised row estimate here */
104950 ){
104951   sqlcipher3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
104952   u8 aff;                   /* Column affinity */
104953   int rc;                   /* Subfunction return code */
104954   tRowcnt a[2];             /* Statistics */
104955
104956   assert( p->aSample!=0 );
104957   assert( p->nSample>0 );
104958   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
104959   if( pExpr ){
104960     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
104961     if( rc ) goto whereEqualScanEst_cancel;
104962   }else{
104963     pRhs = sqlcipher3ValueNew(pParse->db);
104964   }
104965   if( pRhs==0 ) return SQLCIPHER_NOTFOUND;
104966   rc = whereKeyStats(pParse, p, pRhs, 0, a);
104967   if( rc==SQLCIPHER_OK ){
104968     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
104969     *pnRow = a[1];
104970   }
104971 whereEqualScanEst_cancel:
104972   sqlcipher3ValueFree(pRhs);
104973   return rc;
104974 }
104975 #endif /* defined(SQLCIPHER_ENABLE_STAT3) */
104976
104977 #ifdef SQLCIPHER_ENABLE_STAT3
104978 /*
104979 ** Estimate the number of rows that will be returned based on
104980 ** an IN constraint where the right-hand side of the IN operator
104981 ** is a list of values.  Example:
104982 **
104983 **        WHERE x IN (1,2,3,4)
104984 **
104985 ** Write the estimated row count into *pnRow and return SQLCIPHER_OK. 
104986 ** If unable to make an estimate, leave *pnRow unchanged and return
104987 ** non-zero.
104988 **
104989 ** This routine can fail if it is unable to load a collating sequence
104990 ** required for string comparison, or if unable to allocate memory
104991 ** for a UTF conversion required for comparison.  The error is stored
104992 ** in the pParse structure.
104993 */
104994 static int whereInScanEst(
104995   Parse *pParse,       /* Parsing & code generating context */
104996   Index *p,            /* The index whose left-most column is pTerm */
104997   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
104998   double *pnRow        /* Write the revised row estimate here */
104999 ){
105000   int rc = SQLCIPHER_OK;         /* Subfunction return code */
105001   double nEst;                /* Number of rows for a single term */
105002   double nRowEst = (double)0; /* New estimate of the number of rows */
105003   int i;                      /* Loop counter */
105004
105005   assert( p->aSample!=0 );
105006   for(i=0; rc==SQLCIPHER_OK && i<pList->nExpr; i++){
105007     nEst = p->aiRowEst[0];
105008     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
105009     nRowEst += nEst;
105010   }
105011   if( rc==SQLCIPHER_OK ){
105012     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
105013     *pnRow = nRowEst;
105014     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
105015   }
105016   return rc;
105017 }
105018 #endif /* defined(SQLCIPHER_ENABLE_STAT3) */
105019
105020
105021 /*
105022 ** Find the best query plan for accessing a particular table.  Write the
105023 ** best query plan and its cost into the WhereCost object supplied as the
105024 ** last parameter.
105025 **
105026 ** The lowest cost plan wins.  The cost is an estimate of the amount of
105027 ** CPU and disk I/O needed to process the requested result.
105028 ** Factors that influence cost include:
105029 **
105030 **    *  The estimated number of rows that will be retrieved.  (The
105031 **       fewer the better.)
105032 **
105033 **    *  Whether or not sorting must occur.
105034 **
105035 **    *  Whether or not there must be separate lookups in the
105036 **       index and in the main table.
105037 **
105038 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
105039 ** the SQL statement, then this function only considers plans using the 
105040 ** named index. If no such plan is found, then the returned cost is
105041 ** SQLCIPHER_BIG_DBL. If a plan is found that uses the named index, 
105042 ** then the cost is calculated in the usual way.
105043 **
105044 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
105045 ** in the SELECT statement, then no indexes are considered. However, the 
105046 ** selected plan may still take advantage of the built-in rowid primary key
105047 ** index.
105048 */
105049 static void bestBtreeIndex(
105050   Parse *pParse,              /* The parsing context */
105051   WhereClause *pWC,           /* The WHERE clause */
105052   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105053   Bitmask notReady,           /* Mask of cursors not available for indexing */
105054   Bitmask notValid,           /* Cursors not available for any purpose */
105055   ExprList *pOrderBy,         /* The ORDER BY clause */
105056   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
105057   WhereCost *pCost            /* Lowest cost query plan */
105058 ){
105059   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
105060   Index *pProbe;              /* An index we are evaluating */
105061   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
105062   int eqTermMask;             /* Current mask of valid equality operators */
105063   int idxEqTermMask;          /* Index mask of valid equality operators */
105064   Index sPk;                  /* A fake index object for the primary key */
105065   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
105066   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
105067   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
105068
105069   /* Initialize the cost to a worst-case value */
105070   memset(pCost, 0, sizeof(*pCost));
105071   pCost->rCost = SQLCIPHER_BIG_DBL;
105072
105073   /* If the pSrc table is the right table of a LEFT JOIN then we may not
105074   ** use an index to satisfy IS NULL constraints on that table.  This is
105075   ** because columns might end up being NULL if the table does not match -
105076   ** a circumstance which the index cannot help us discover.  Ticket #2177.
105077   */
105078   if( pSrc->jointype & JT_LEFT ){
105079     idxEqTermMask = WO_EQ|WO_IN;
105080   }else{
105081     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
105082   }
105083
105084   if( pSrc->pIndex ){
105085     /* An INDEXED BY clause specifies a particular index to use */
105086     pIdx = pProbe = pSrc->pIndex;
105087     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105088     eqTermMask = idxEqTermMask;
105089   }else{
105090     /* There is no INDEXED BY clause.  Create a fake Index object in local
105091     ** variable sPk to represent the rowid primary key index.  Make this
105092     ** fake index the first in a chain of Index objects with all of the real
105093     ** indices to follow */
105094     Index *pFirst;                  /* First of real indices on the table */
105095     memset(&sPk, 0, sizeof(Index));
105096     sPk.nColumn = 1;
105097     sPk.aiColumn = &aiColumnPk;
105098     sPk.aiRowEst = aiRowEstPk;
105099     sPk.onError = OE_Replace;
105100     sPk.pTable = pSrc->pTab;
105101     aiRowEstPk[0] = pSrc->pTab->nRowEst;
105102     aiRowEstPk[1] = 1;
105103     pFirst = pSrc->pTab->pIndex;
105104     if( pSrc->notIndexed==0 ){
105105       /* The real indices of the table are only considered if the
105106       ** NOT INDEXED qualifier is omitted from the FROM clause */
105107       sPk.pNext = pFirst;
105108     }
105109     pProbe = &sPk;
105110     wsFlagMask = ~(
105111         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
105112     );
105113     eqTermMask = WO_EQ|WO_IN;
105114     pIdx = 0;
105115   }
105116
105117   /* Loop over all indices looking for the best one to use
105118   */
105119   for(; pProbe; pIdx=pProbe=pProbe->pNext){
105120     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
105121     double cost;                /* Cost of using pProbe */
105122     double nRow;                /* Estimated number of rows in result set */
105123     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
105124     int rev;                    /* True to scan in reverse order */
105125     int wsFlags = 0;
105126     Bitmask used = 0;
105127
105128     /* The following variables are populated based on the properties of
105129     ** index being evaluated. They are then used to determine the expected
105130     ** cost and number of rows returned.
105131     **
105132     **  nEq: 
105133     **    Number of equality terms that can be implemented using the index.
105134     **    In other words, the number of initial fields in the index that
105135     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
105136     **
105137     **  nInMul:  
105138     **    The "in-multiplier". This is an estimate of how many seek operations 
105139     **    SQLite must perform on the index in question. For example, if the 
105140     **    WHERE clause is:
105141     **
105142     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
105143     **
105144     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
105145     **    set to 9. Given the same schema and either of the following WHERE 
105146     **    clauses:
105147     **
105148     **      WHERE a =  1
105149     **      WHERE a >= 2
105150     **
105151     **    nInMul is set to 1.
105152     **
105153     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
105154     **    the sub-select is assumed to return 25 rows for the purposes of 
105155     **    determining nInMul.
105156     **
105157     **  bInEst:  
105158     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
105159     **    in determining the value of nInMul.  Note that the RHS of the
105160     **    IN operator must be a SELECT, not a value list, for this variable
105161     **    to be true.
105162     **
105163     **  rangeDiv:
105164     **    An estimate of a divisor by which to reduce the search space due
105165     **    to inequality constraints.  In the absence of sqlcipher_stat3 ANALYZE
105166     **    data, a single inequality reduces the search space to 1/4rd its
105167     **    original size (rangeDiv==4).  Two inequalities reduce the search
105168     **    space to 1/16th of its original size (rangeDiv==16).
105169     **
105170     **  bSort:   
105171     **    Boolean. True if there is an ORDER BY clause that will require an 
105172     **    external sort (i.e. scanning the index being evaluated will not 
105173     **    correctly order records).
105174     **
105175     **  bLookup: 
105176     **    Boolean. True if a table lookup is required for each index entry
105177     **    visited.  In other words, true if this is not a covering index.
105178     **    This is always false for the rowid primary key index of a table.
105179     **    For other indexes, it is true unless all the columns of the table
105180     **    used by the SELECT statement are present in the index (such an
105181     **    index is sometimes described as a covering index).
105182     **    For example, given the index on (a, b), the second of the following 
105183     **    two queries requires table b-tree lookups in order to find the value
105184     **    of column c, but the first does not because columns a and b are
105185     **    both available in the index.
105186     **
105187     **             SELECT a, b    FROM tbl WHERE a = 1;
105188     **             SELECT a, b, c FROM tbl WHERE a = 1;
105189     */
105190     int nEq;                      /* Number of == or IN terms matching index */
105191     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
105192     int nInMul = 1;               /* Number of distinct equalities to lookup */
105193     double rangeDiv = (double)1;  /* Estimated reduction in search space */
105194     int nBound = 0;               /* Number of range constraints seen */
105195     int bSort = !!pOrderBy;       /* True if external sort required */
105196     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
105197     int bLookup = 0;              /* True if not a covering index */
105198     WhereTerm *pTerm;             /* A single term of the WHERE clause */
105199 #ifdef SQLCIPHER_ENABLE_STAT3
105200     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
105201 #endif
105202
105203     /* Determine the values of nEq and nInMul */
105204     for(nEq=0; nEq<pProbe->nColumn; nEq++){
105205       int j = pProbe->aiColumn[nEq];
105206       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
105207       if( pTerm==0 ) break;
105208       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
105209       testcase( pTerm->pWC!=pWC );
105210       if( pTerm->eOperator & WO_IN ){
105211         Expr *pExpr = pTerm->pExpr;
105212         wsFlags |= WHERE_COLUMN_IN;
105213         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105214           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
105215           nInMul *= 25;
105216           bInEst = 1;
105217         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
105218           /* "x IN (value, value, ...)" */
105219           nInMul *= pExpr->x.pList->nExpr;
105220         }
105221       }else if( pTerm->eOperator & WO_ISNULL ){
105222         wsFlags |= WHERE_COLUMN_NULL;
105223       }
105224 #ifdef SQLCIPHER_ENABLE_STAT3
105225       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
105226 #endif
105227       used |= pTerm->prereqRight;
105228     }
105229
105230     /* Determine the value of rangeDiv */
105231     if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
105232       int j = pProbe->aiColumn[nEq];
105233       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
105234         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
105235         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
105236         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
105237         if( pTop ){
105238           nBound = 1;
105239           wsFlags |= WHERE_TOP_LIMIT;
105240           used |= pTop->prereqRight;
105241           testcase( pTop->pWC!=pWC );
105242         }
105243         if( pBtm ){
105244           nBound++;
105245           wsFlags |= WHERE_BTM_LIMIT;
105246           used |= pBtm->prereqRight;
105247           testcase( pBtm->pWC!=pWC );
105248         }
105249         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
105250       }
105251     }else if( pProbe->onError!=OE_None ){
105252       testcase( wsFlags & WHERE_COLUMN_IN );
105253       testcase( wsFlags & WHERE_COLUMN_NULL );
105254       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
105255         wsFlags |= WHERE_UNIQUE;
105256       }
105257     }
105258
105259     /* If there is an ORDER BY clause and the index being considered will
105260     ** naturally scan rows in the required order, set the appropriate flags
105261     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
105262     ** will scan rows in a different order, set the bSort variable.  */
105263     if( isSortingIndex(
105264           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
105265     ){
105266       bSort = 0;
105267       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
105268       wsFlags |= (rev ? WHERE_REVERSE : 0);
105269     }
105270
105271     /* If there is a DISTINCT qualifier and this index will scan rows in
105272     ** order of the DISTINCT expressions, clear bDist and set the appropriate
105273     ** flags in wsFlags. */
105274     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq) ){
105275       bDist = 0;
105276       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
105277     }
105278
105279     /* If currently calculating the cost of using an index (not the IPK
105280     ** index), determine if all required column data may be obtained without 
105281     ** using the main table (i.e. if the index is a covering
105282     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
105283     ** wsFlags. Otherwise, set the bLookup variable to true.  */
105284     if( pIdx && wsFlags ){
105285       Bitmask m = pSrc->colUsed;
105286       int j;
105287       for(j=0; j<pIdx->nColumn; j++){
105288         int x = pIdx->aiColumn[j];
105289         if( x<BMS-1 ){
105290           m &= ~(((Bitmask)1)<<x);
105291         }
105292       }
105293       if( m==0 ){
105294         wsFlags |= WHERE_IDX_ONLY;
105295       }else{
105296         bLookup = 1;
105297       }
105298     }
105299
105300     /*
105301     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
105302     ** constraint, do not let the estimate exceed half the rows in the table.
105303     */
105304     nRow = (double)(aiRowEst[nEq] * nInMul);
105305     if( bInEst && nRow*2>aiRowEst[0] ){
105306       nRow = aiRowEst[0]/2;
105307       nInMul = (int)(nRow / aiRowEst[nEq]);
105308     }
105309
105310 #ifdef SQLCIPHER_ENABLE_STAT3
105311     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
105312     ** and we do not think that values of x are unique and if histogram
105313     ** data is available for column x, then it might be possible
105314     ** to get a better estimate on the number of rows based on
105315     ** VALUE and how common that value is according to the histogram.
105316     */
105317     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
105318       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
105319       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
105320         testcase( pFirstTerm->eOperator==WO_EQ );
105321         testcase( pFirstTerm->eOperator==WO_ISNULL );
105322         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
105323       }else if( bInEst==0 ){
105324         assert( pFirstTerm->eOperator==WO_IN );
105325         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
105326       }
105327     }
105328 #endif /* SQLCIPHER_ENABLE_STAT3 */
105329
105330     /* Adjust the number of output rows and downward to reflect rows
105331     ** that are excluded by range constraints.
105332     */
105333     nRow = nRow/rangeDiv;
105334     if( nRow<1 ) nRow = 1;
105335
105336     /* Experiments run on real SQLite databases show that the time needed
105337     ** to do a binary search to locate a row in a table or index is roughly
105338     ** log10(N) times the time to move from one row to the next row within
105339     ** a table or index.  The actual times can vary, with the size of
105340     ** records being an important factor.  Both moves and searches are
105341     ** slower with larger records, presumably because fewer records fit
105342     ** on one page and hence more pages have to be fetched.
105343     **
105344     ** The ANALYZE command and the sqlcipher_stat1 and sqlcipher_stat3 tables do
105345     ** not give us data on the relative sizes of table and index records.
105346     ** So this computation assumes table records are about twice as big
105347     ** as index records
105348     */
105349     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105350       /* The cost of a full table scan is a number of move operations equal
105351       ** to the number of rows in the table.
105352       **
105353       ** We add an additional 4x penalty to full table scans.  This causes
105354       ** the cost function to err on the side of choosing an index over
105355       ** choosing a full scan.  This 4x full-scan penalty is an arguable
105356       ** decision and one which we expect to revisit in the future.  But
105357       ** it seems to be working well enough at the moment.
105358       */
105359       cost = aiRowEst[0]*4;
105360     }else{
105361       log10N = estLog(aiRowEst[0]);
105362       cost = nRow;
105363       if( pIdx ){
105364         if( bLookup ){
105365           /* For an index lookup followed by a table lookup:
105366           **    nInMul index searches to find the start of each index range
105367           **  + nRow steps through the index
105368           **  + nRow table searches to lookup the table entry using the rowid
105369           */
105370           cost += (nInMul + nRow)*log10N;
105371         }else{
105372           /* For a covering index:
105373           **     nInMul index searches to find the initial entry 
105374           **   + nRow steps through the index
105375           */
105376           cost += nInMul*log10N;
105377         }
105378       }else{
105379         /* For a rowid primary key lookup:
105380         **    nInMult table searches to find the initial entry for each range
105381         **  + nRow steps through the table
105382         */
105383         cost += nInMul*log10N;
105384       }
105385     }
105386
105387     /* Add in the estimated cost of sorting the result.  Actual experimental
105388     ** measurements of sorting performance in SQLite show that sorting time
105389     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
105390     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
105391     ** difference and select C of 3.0.
105392     */
105393     if( bSort ){
105394       cost += nRow*estLog(nRow)*3;
105395     }
105396     if( bDist ){
105397       cost += nRow*estLog(nRow)*3;
105398     }
105399
105400     /**** Cost of using this index has now been computed ****/
105401
105402     /* If there are additional constraints on this table that cannot
105403     ** be used with the current index, but which might lower the number
105404     ** of output rows, adjust the nRow value accordingly.  This only 
105405     ** matters if the current index is the least costly, so do not bother
105406     ** with this step if we already know this index will not be chosen.
105407     ** Also, never reduce the output row count below 2 using this step.
105408     **
105409     ** It is critical that the notValid mask be used here instead of
105410     ** the notReady mask.  When computing an "optimal" index, the notReady
105411     ** mask will only have one bit set - the bit for the current table.
105412     ** The notValid mask, on the other hand, always has all bits set for
105413     ** tables that are not in outer loops.  If notReady is used here instead
105414     ** of notValid, then a optimal index that depends on inner joins loops
105415     ** might be selected even when there exists an optimal index that has
105416     ** no such dependency.
105417     */
105418     if( nRow>2 && cost<=pCost->rCost ){
105419       int k;                       /* Loop counter */
105420       int nSkipEq = nEq;           /* Number of == constraints to skip */
105421       int nSkipRange = nBound;     /* Number of < constraints to skip */
105422       Bitmask thisTab;             /* Bitmap for pSrc */
105423
105424       thisTab = getMask(pWC->pMaskSet, iCur);
105425       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
105426         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
105427         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
105428         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
105429           if( nSkipEq ){
105430             /* Ignore the first nEq equality matches since the index
105431             ** has already accounted for these */
105432             nSkipEq--;
105433           }else{
105434             /* Assume each additional equality match reduces the result
105435             ** set size by a factor of 10 */
105436             nRow /= 10;
105437           }
105438         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
105439           if( nSkipRange ){
105440             /* Ignore the first nSkipRange range constraints since the index
105441             ** has already accounted for these */
105442             nSkipRange--;
105443           }else{
105444             /* Assume each additional range constraint reduces the result
105445             ** set size by a factor of 3.  Indexed range constraints reduce
105446             ** the search space by a larger factor: 4.  We make indexed range
105447             ** more selective intentionally because of the subjective 
105448             ** observation that indexed range constraints really are more
105449             ** selective in practice, on average. */
105450             nRow /= 3;
105451           }
105452         }else if( pTerm->eOperator!=WO_NOOP ){
105453           /* Any other expression lowers the output row count by half */
105454           nRow /= 2;
105455         }
105456       }
105457       if( nRow<2 ) nRow = 2;
105458     }
105459
105460
105461     WHERETRACE((
105462       "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
105463       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
105464       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
105465       nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
105466       notReady, log10N, nRow, cost, used
105467     ));
105468
105469     /* If this index is the best we have seen so far, then record this
105470     ** index and its cost in the pCost structure.
105471     */
105472     if( (!pIdx || wsFlags)
105473      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
105474     ){
105475       pCost->rCost = cost;
105476       pCost->used = used;
105477       pCost->plan.nRow = nRow;
105478       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
105479       pCost->plan.nEq = nEq;
105480       pCost->plan.u.pIdx = pIdx;
105481     }
105482
105483     /* If there was an INDEXED BY clause, then only that one index is
105484     ** considered. */
105485     if( pSrc->pIndex ) break;
105486
105487     /* Reset masks for the next index in the loop */
105488     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105489     eqTermMask = idxEqTermMask;
105490   }
105491
105492   /* If there is no ORDER BY clause and the SQLCIPHER_ReverseOrder flag
105493   ** is set, then reverse the order that the index will be scanned
105494   ** in. This is used for application testing, to help find cases
105495   ** where application behaviour depends on the (undefined) order that
105496   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
105497   if( !pOrderBy && pParse->db->flags & SQLCIPHER_ReverseOrder ){
105498     pCost->plan.wsFlags |= WHERE_REVERSE;
105499   }
105500
105501   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
105502   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
105503   assert( pSrc->pIndex==0 
105504        || pCost->plan.u.pIdx==0 
105505        || pCost->plan.u.pIdx==pSrc->pIndex 
105506   );
105507
105508   WHERETRACE(("best index is: %s\n", 
105509     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
105510          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
105511   ));
105512   
105513   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
105514   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
105515   pCost->plan.wsFlags |= eqTermMask;
105516 }
105517
105518 /*
105519 ** Find the query plan for accessing table pSrc->pTab. Write the
105520 ** best query plan and its cost into the WhereCost object supplied 
105521 ** as the last parameter. This function may calculate the cost of
105522 ** both real and virtual table scans.
105523 */
105524 static void bestIndex(
105525   Parse *pParse,              /* The parsing context */
105526   WhereClause *pWC,           /* The WHERE clause */
105527   struct SrcList_item *pSrc,  /* The FROM clause term to search */
105528   Bitmask notReady,           /* Mask of cursors not available for indexing */
105529   Bitmask notValid,           /* Cursors not available for any purpose */
105530   ExprList *pOrderBy,         /* The ORDER BY clause */
105531   WhereCost *pCost            /* Lowest cost query plan */
105532 ){
105533 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
105534   if( IsVirtual(pSrc->pTab) ){
105535     sqlcipher3_index_info *p = 0;
105536     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
105537     if( p->needToFreeIdxStr ){
105538       sqlcipher3_free(p->idxStr);
105539     }
105540     sqlcipher3DbFree(pParse->db, p);
105541   }else
105542 #endif
105543   {
105544     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
105545   }
105546 }
105547
105548 /*
105549 ** Disable a term in the WHERE clause.  Except, do not disable the term
105550 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
105551 ** or USING clause of that join.
105552 **
105553 ** Consider the term t2.z='ok' in the following queries:
105554 **
105555 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
105556 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
105557 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
105558 **
105559 ** The t2.z='ok' is disabled in the in (2) because it originates
105560 ** in the ON clause.  The term is disabled in (3) because it is not part
105561 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
105562 **
105563 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
105564 ** completely satisfied by indices.
105565 **
105566 ** Disabling a term causes that term to not be tested in the inner loop
105567 ** of the join.  Disabling is an optimization.  When terms are satisfied
105568 ** by indices, we disable them to prevent redundant tests in the inner
105569 ** loop.  We would get the correct results if nothing were ever disabled,
105570 ** but joins might run a little slower.  The trick is to disable as much
105571 ** as we can without disabling too much.  If we disabled in (1), we'd get
105572 ** the wrong answer.  See ticket #813.
105573 */
105574 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
105575   if( pTerm
105576       && (pTerm->wtFlags & TERM_CODED)==0
105577       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
105578   ){
105579     pTerm->wtFlags |= TERM_CODED;
105580     if( pTerm->iParent>=0 ){
105581       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
105582       if( (--pOther->nChild)==0 ){
105583         disableTerm(pLevel, pOther);
105584       }
105585     }
105586   }
105587 }
105588
105589 /*
105590 ** Code an OP_Affinity opcode to apply the column affinity string zAff
105591 ** to the n registers starting at base. 
105592 **
105593 ** As an optimization, SQLCIPHER_AFF_NONE entries (which are no-ops) at the
105594 ** beginning and end of zAff are ignored.  If all entries in zAff are
105595 ** SQLCIPHER_AFF_NONE, then no code gets generated.
105596 **
105597 ** This routine makes its own copy of zAff so that the caller is free
105598 ** to modify zAff after this routine returns.
105599 */
105600 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
105601   Vdbe *v = pParse->pVdbe;
105602   if( zAff==0 ){
105603     assert( pParse->db->mallocFailed );
105604     return;
105605   }
105606   assert( v!=0 );
105607
105608   /* Adjust base and n to skip over SQLCIPHER_AFF_NONE entries at the beginning
105609   ** and end of the affinity string.
105610   */
105611   while( n>0 && zAff[0]==SQLCIPHER_AFF_NONE ){
105612     n--;
105613     base++;
105614     zAff++;
105615   }
105616   while( n>1 && zAff[n-1]==SQLCIPHER_AFF_NONE ){
105617     n--;
105618   }
105619
105620   /* Code the OP_Affinity opcode if there is anything left to do. */
105621   if( n>0 ){
105622     sqlcipher3VdbeAddOp2(v, OP_Affinity, base, n);
105623     sqlcipher3VdbeChangeP4(v, -1, zAff, n);
105624     sqlcipher3ExprCacheAffinityChange(pParse, base, n);
105625   }
105626 }
105627
105628
105629 /*
105630 ** Generate code for a single equality term of the WHERE clause.  An equality
105631 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
105632 ** coded.
105633 **
105634 ** The current value for the constraint is left in register iReg.
105635 **
105636 ** For a constraint of the form X=expr, the expression is evaluated and its
105637 ** result is left on the stack.  For constraints of the form X IN (...)
105638 ** this routine sets up a loop that will iterate over all values of X.
105639 */
105640 static int codeEqualityTerm(
105641   Parse *pParse,      /* The parsing context */
105642   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
105643   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
105644   int iTarget         /* Attempt to leave results in this register */
105645 ){
105646   Expr *pX = pTerm->pExpr;
105647   Vdbe *v = pParse->pVdbe;
105648   int iReg;                  /* Register holding results */
105649
105650   assert( iTarget>0 );
105651   if( pX->op==TK_EQ ){
105652     iReg = sqlcipher3ExprCodeTarget(pParse, pX->pRight, iTarget);
105653   }else if( pX->op==TK_ISNULL ){
105654     iReg = iTarget;
105655     sqlcipher3VdbeAddOp2(v, OP_Null, 0, iReg);
105656 #ifndef SQLCIPHER_OMIT_SUBQUERY
105657   }else{
105658     int eType;
105659     int iTab;
105660     struct InLoop *pIn;
105661
105662     assert( pX->op==TK_IN );
105663     iReg = iTarget;
105664     eType = sqlcipher3FindInIndex(pParse, pX, 0);
105665     iTab = pX->iTable;
105666     sqlcipher3VdbeAddOp2(v, OP_Rewind, iTab, 0);
105667     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
105668     if( pLevel->u.in.nIn==0 ){
105669       pLevel->addrNxt = sqlcipher3VdbeMakeLabel(v);
105670     }
105671     pLevel->u.in.nIn++;
105672     pLevel->u.in.aInLoop =
105673        sqlcipher3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
105674                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
105675     pIn = pLevel->u.in.aInLoop;
105676     if( pIn ){
105677       pIn += pLevel->u.in.nIn - 1;
105678       pIn->iCur = iTab;
105679       if( eType==IN_INDEX_ROWID ){
105680         pIn->addrInTop = sqlcipher3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
105681       }else{
105682         pIn->addrInTop = sqlcipher3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
105683       }
105684       sqlcipher3VdbeAddOp1(v, OP_IsNull, iReg);
105685     }else{
105686       pLevel->u.in.nIn = 0;
105687     }
105688 #endif
105689   }
105690   disableTerm(pLevel, pTerm);
105691   return iReg;
105692 }
105693
105694 /*
105695 ** Generate code that will evaluate all == and IN constraints for an
105696 ** index.
105697 **
105698 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
105699 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
105700 ** The index has as many as three equality constraints, but in this
105701 ** example, the third "c" value is an inequality.  So only two 
105702 ** constraints are coded.  This routine will generate code to evaluate
105703 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
105704 ** in consecutive registers and the index of the first register is returned.
105705 **
105706 ** In the example above nEq==2.  But this subroutine works for any value
105707 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
105708 ** The only thing it does is allocate the pLevel->iMem memory cell and
105709 ** compute the affinity string.
105710 **
105711 ** This routine always allocates at least one memory cell and returns
105712 ** the index of that memory cell. The code that
105713 ** calls this routine will use that memory cell to store the termination
105714 ** key value of the loop.  If one or more IN operators appear, then
105715 ** this routine allocates an additional nEq memory cells for internal
105716 ** use.
105717 **
105718 ** Before returning, *pzAff is set to point to a buffer containing a
105719 ** copy of the column affinity string of the index allocated using
105720 ** sqlcipher3DbMalloc(). Except, entries in the copy of the string associated
105721 ** with equality constraints that use NONE affinity are set to
105722 ** SQLCIPHER_AFF_NONE. This is to deal with SQL such as the following:
105723 **
105724 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
105725 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
105726 **
105727 ** In the example above, the index on t1(a) has TEXT affinity. But since
105728 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
105729 ** no conversion should be attempted before using a t2.b value as part of
105730 ** a key to search the index. Hence the first byte in the returned affinity
105731 ** string in this example would be set to SQLCIPHER_AFF_NONE.
105732 */
105733 static int codeAllEqualityTerms(
105734   Parse *pParse,        /* Parsing context */
105735   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
105736   WhereClause *pWC,     /* The WHERE clause */
105737   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
105738   int nExtraReg,        /* Number of extra registers to allocate */
105739   char **pzAff          /* OUT: Set to point to affinity string */
105740 ){
105741   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
105742   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
105743   Index *pIdx;                  /* The index being used for this loop */
105744   int iCur = pLevel->iTabCur;   /* The cursor of the table */
105745   WhereTerm *pTerm;             /* A single constraint term */
105746   int j;                        /* Loop counter */
105747   int regBase;                  /* Base register */
105748   int nReg;                     /* Number of registers to allocate */
105749   char *zAff;                   /* Affinity string to return */
105750
105751   /* This module is only called on query plans that use an index. */
105752   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
105753   pIdx = pLevel->plan.u.pIdx;
105754
105755   /* Figure out how many memory cells we will need then allocate them.
105756   */
105757   regBase = pParse->nMem + 1;
105758   nReg = pLevel->plan.nEq + nExtraReg;
105759   pParse->nMem += nReg;
105760
105761   zAff = sqlcipher3DbStrDup(pParse->db, sqlcipher3IndexAffinityStr(v, pIdx));
105762   if( !zAff ){
105763     pParse->db->mallocFailed = 1;
105764   }
105765
105766   /* Evaluate the equality constraints
105767   */
105768   assert( pIdx->nColumn>=nEq );
105769   for(j=0; j<nEq; j++){
105770     int r1;
105771     int k = pIdx->aiColumn[j];
105772     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
105773     if( NEVER(pTerm==0) ) break;
105774     /* The following true for indices with redundant columns. 
105775     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
105776     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
105777     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
105778     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
105779     if( r1!=regBase+j ){
105780       if( nReg==1 ){
105781         sqlcipher3ReleaseTempReg(pParse, regBase);
105782         regBase = r1;
105783       }else{
105784         sqlcipher3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
105785       }
105786     }
105787     testcase( pTerm->eOperator & WO_ISNULL );
105788     testcase( pTerm->eOperator & WO_IN );
105789     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
105790       Expr *pRight = pTerm->pExpr->pRight;
105791       sqlcipher3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
105792       if( zAff ){
105793         if( sqlcipher3CompareAffinity(pRight, zAff[j])==SQLCIPHER_AFF_NONE ){
105794           zAff[j] = SQLCIPHER_AFF_NONE;
105795         }
105796         if( sqlcipher3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
105797           zAff[j] = SQLCIPHER_AFF_NONE;
105798         }
105799       }
105800     }
105801   }
105802   *pzAff = zAff;
105803   return regBase;
105804 }
105805
105806 #ifndef SQLCIPHER_OMIT_EXPLAIN
105807 /*
105808 ** This routine is a helper for explainIndexRange() below
105809 **
105810 ** pStr holds the text of an expression that we are building up one term
105811 ** at a time.  This routine adds a new term to the end of the expression.
105812 ** Terms are separated by AND so add the "AND" text for second and subsequent
105813 ** terms only.
105814 */
105815 static void explainAppendTerm(
105816   StrAccum *pStr,             /* The text expression being built */
105817   int iTerm,                  /* Index of this term.  First is zero */
105818   const char *zColumn,        /* Name of the column */
105819   const char *zOp             /* Name of the operator */
105820 ){
105821   if( iTerm ) sqlcipher3StrAccumAppend(pStr, " AND ", 5);
105822   sqlcipher3StrAccumAppend(pStr, zColumn, -1);
105823   sqlcipher3StrAccumAppend(pStr, zOp, 1);
105824   sqlcipher3StrAccumAppend(pStr, "?", 1);
105825 }
105826
105827 /*
105828 ** Argument pLevel describes a strategy for scanning table pTab. This 
105829 ** function returns a pointer to a string buffer containing a description
105830 ** of the subset of table rows scanned by the strategy in the form of an
105831 ** SQL expression. Or, if all rows are scanned, NULL is returned.
105832 **
105833 ** For example, if the query:
105834 **
105835 **   SELECT * FROM t1 WHERE a=1 AND b>2;
105836 **
105837 ** is run and there is an index on (a, b), then this function returns a
105838 ** string similar to:
105839 **
105840 **   "a=? AND b>?"
105841 **
105842 ** The returned pointer points to memory obtained from sqlcipher3DbMalloc().
105843 ** It is the responsibility of the caller to free the buffer when it is
105844 ** no longer required.
105845 */
105846 static char *explainIndexRange(sqlcipher3 *db, WhereLevel *pLevel, Table *pTab){
105847   WherePlan *pPlan = &pLevel->plan;
105848   Index *pIndex = pPlan->u.pIdx;
105849   int nEq = pPlan->nEq;
105850   int i, j;
105851   Column *aCol = pTab->aCol;
105852   int *aiColumn = pIndex->aiColumn;
105853   StrAccum txt;
105854
105855   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
105856     return 0;
105857   }
105858   sqlcipher3StrAccumInit(&txt, 0, 0, SQLCIPHER_MAX_LENGTH);
105859   txt.db = db;
105860   sqlcipher3StrAccumAppend(&txt, " (", 2);
105861   for(i=0; i<nEq; i++){
105862     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
105863   }
105864
105865   j = i;
105866   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
105867     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
105868   }
105869   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
105870     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
105871   }
105872   sqlcipher3StrAccumAppend(&txt, ")", 1);
105873   return sqlcipher3StrAccumFinish(&txt);
105874 }
105875
105876 /*
105877 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
105878 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
105879 ** record is added to the output to describe the table scan strategy in 
105880 ** pLevel.
105881 */
105882 static void explainOneScan(
105883   Parse *pParse,                  /* Parse context */
105884   SrcList *pTabList,              /* Table list this loop refers to */
105885   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
105886   int iLevel,                     /* Value for "level" column of output */
105887   int iFrom,                      /* Value for "from" column of output */
105888   u16 wctrlFlags                  /* Flags passed to sqlcipher3WhereBegin() */
105889 ){
105890   if( pParse->explain==2 ){
105891     u32 flags = pLevel->plan.wsFlags;
105892     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
105893     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
105894     sqlcipher3 *db = pParse->db;     /* Database handle */
105895     char *zMsg;                   /* Text to add to EQP output */
105896     sqlcipher3_int64 nRow;           /* Expected number of rows visited by scan */
105897     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
105898     int isSearch;                 /* True for a SEARCH. False for SCAN. */
105899
105900     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
105901
105902     isSearch = (pLevel->plan.nEq>0)
105903              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
105904              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
105905
105906     zMsg = sqlcipher3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
105907     if( pItem->pSelect ){
105908       zMsg = sqlcipher3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
105909     }else{
105910       zMsg = sqlcipher3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
105911     }
105912
105913     if( pItem->zAlias ){
105914       zMsg = sqlcipher3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
105915     }
105916     if( (flags & WHERE_INDEXED)!=0 ){
105917       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
105918       zMsg = sqlcipher3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
105919           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
105920           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
105921           ((flags & WHERE_TEMP_INDEX)?"":" "),
105922           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
105923           zWhere
105924       );
105925       sqlcipher3DbFree(db, zWhere);
105926     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
105927       zMsg = sqlcipher3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
105928
105929       if( flags&WHERE_ROWID_EQ ){
105930         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
105931       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
105932         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
105933       }else if( flags&WHERE_BTM_LIMIT ){
105934         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
105935       }else if( flags&WHERE_TOP_LIMIT ){
105936         zMsg = sqlcipher3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
105937       }
105938     }
105939 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
105940     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
105941       sqlcipher3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
105942       zMsg = sqlcipher3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
105943                   pVtabIdx->idxNum, pVtabIdx->idxStr);
105944     }
105945 #endif
105946     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
105947       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
105948       nRow = 1;
105949     }else{
105950       nRow = (sqlcipher3_int64)pLevel->plan.nRow;
105951     }
105952     zMsg = sqlcipher3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
105953     sqlcipher3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
105954   }
105955 }
105956 #else
105957 # define explainOneScan(u,v,w,x,y,z)
105958 #endif /* SQLCIPHER_OMIT_EXPLAIN */
105959
105960
105961 /*
105962 ** Generate code for the start of the iLevel-th loop in the WHERE clause
105963 ** implementation described by pWInfo.
105964 */
105965 static Bitmask codeOneLoopStart(
105966   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
105967   int iLevel,          /* Which level of pWInfo->a[] should be coded */
105968   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqlcipherInt.h */
105969   Bitmask notReady,    /* Which tables are currently available */
105970   Expr *pWhere         /* Complete WHERE clause */
105971 ){
105972   int j, k;            /* Loop counters */
105973   int iCur;            /* The VDBE cursor for the table */
105974   int addrNxt;         /* Where to jump to continue with the next IN case */
105975   int omitTable;       /* True if we use the index only */
105976   int bRev;            /* True if we need to scan in reverse order */
105977   WhereLevel *pLevel;  /* The where level to be coded */
105978   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
105979   WhereTerm *pTerm;               /* A WHERE clause term */
105980   Parse *pParse;                  /* Parsing context */
105981   Vdbe *v;                        /* The prepared stmt under constructions */
105982   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
105983   int addrBrk;                    /* Jump here to break out of the loop */
105984   int addrCont;                   /* Jump here to continue with next cycle */
105985   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
105986   int iReleaseReg = 0;      /* Temp register to free before returning */
105987
105988   pParse = pWInfo->pParse;
105989   v = pParse->pVdbe;
105990   pWC = pWInfo->pWC;
105991   pLevel = &pWInfo->a[iLevel];
105992   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
105993   iCur = pTabItem->iCursor;
105994   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
105995   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
105996            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
105997
105998   /* Create labels for the "break" and "continue" instructions
105999   ** for the current loop.  Jump to addrBrk to break out of a loop.
106000   ** Jump to cont to go immediately to the next iteration of the
106001   ** loop.
106002   **
106003   ** When there is an IN operator, we also have a "addrNxt" label that
106004   ** means to continue with the next IN value combination.  When
106005   ** there are no IN operators in the constraints, the "addrNxt" label
106006   ** is the same as "addrBrk".
106007   */
106008   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlcipher3VdbeMakeLabel(v);
106009   addrCont = pLevel->addrCont = sqlcipher3VdbeMakeLabel(v);
106010
106011   /* If this is the right table of a LEFT OUTER JOIN, allocate and
106012   ** initialize a memory cell that records if this table matches any
106013   ** row of the left table of the join.
106014   */
106015   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
106016     pLevel->iLeftJoin = ++pParse->nMem;
106017     sqlcipher3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
106018     VdbeComment((v, "init LEFT JOIN no-match flag"));
106019   }
106020
106021 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
106022   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
106023     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
106024     **          to access the data.
106025     */
106026     int iReg;   /* P3 Value for OP_VFilter */
106027     sqlcipher3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106028     int nConstraint = pVtabIdx->nConstraint;
106029     struct sqlcipher3_index_constraint_usage *aUsage =
106030                                                 pVtabIdx->aConstraintUsage;
106031     const struct sqlcipher3_index_constraint *aConstraint =
106032                                                 pVtabIdx->aConstraint;
106033
106034     sqlcipher3ExprCachePush(pParse);
106035     iReg = sqlcipher3GetTempRange(pParse, nConstraint+2);
106036     for(j=1; j<=nConstraint; j++){
106037       for(k=0; k<nConstraint; k++){
106038         if( aUsage[k].argvIndex==j ){
106039           int iTerm = aConstraint[k].iTermOffset;
106040           sqlcipher3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
106041           break;
106042         }
106043       }
106044       if( k==nConstraint ) break;
106045     }
106046     sqlcipher3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
106047     sqlcipher3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
106048     sqlcipher3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
106049                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
106050     pVtabIdx->needToFreeIdxStr = 0;
106051     for(j=0; j<nConstraint; j++){
106052       if( aUsage[j].omit ){
106053         int iTerm = aConstraint[j].iTermOffset;
106054         disableTerm(pLevel, &pWC->a[iTerm]);
106055       }
106056     }
106057     pLevel->op = OP_VNext;
106058     pLevel->p1 = iCur;
106059     pLevel->p2 = sqlcipher3VdbeCurrentAddr(v);
106060     sqlcipher3ReleaseTempRange(pParse, iReg, nConstraint+2);
106061     sqlcipher3ExprCachePop(pParse, 1);
106062   }else
106063 #endif /* SQLCIPHER_OMIT_VIRTUALTABLE */
106064
106065   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
106066     /* Case 1:  We can directly reference a single row using an
106067     **          equality comparison against the ROWID field.  Or
106068     **          we reference multiple rows using a "rowid IN (...)"
106069     **          construct.
106070     */
106071     iReleaseReg = sqlcipher3GetTempReg(pParse);
106072     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
106073     assert( pTerm!=0 );
106074     assert( pTerm->pExpr!=0 );
106075     assert( pTerm->leftCursor==iCur );
106076     assert( omitTable==0 );
106077     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106078     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
106079     addrNxt = pLevel->addrNxt;
106080     sqlcipher3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
106081     sqlcipher3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
106082     sqlcipher3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106083     VdbeComment((v, "pk"));
106084     pLevel->op = OP_Noop;
106085   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
106086     /* Case 2:  We have an inequality comparison against the ROWID field.
106087     */
106088     int testOp = OP_Noop;
106089     int start;
106090     int memEndValue = 0;
106091     WhereTerm *pStart, *pEnd;
106092
106093     assert( omitTable==0 );
106094     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
106095     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
106096     if( bRev ){
106097       pTerm = pStart;
106098       pStart = pEnd;
106099       pEnd = pTerm;
106100     }
106101     if( pStart ){
106102       Expr *pX;             /* The expression that defines the start bound */
106103       int r1, rTemp;        /* Registers for holding the start boundary */
106104
106105       /* The following constant maps TK_xx codes into corresponding 
106106       ** seek opcodes.  It depends on a particular ordering of TK_xx
106107       */
106108       const u8 aMoveOp[] = {
106109            /* TK_GT */  OP_SeekGt,
106110            /* TK_LE */  OP_SeekLe,
106111            /* TK_LT */  OP_SeekLt,
106112            /* TK_GE */  OP_SeekGe
106113       };
106114       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
106115       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
106116       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
106117
106118       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106119       pX = pStart->pExpr;
106120       assert( pX!=0 );
106121       assert( pStart->leftCursor==iCur );
106122       r1 = sqlcipher3ExprCodeTemp(pParse, pX->pRight, &rTemp);
106123       sqlcipher3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
106124       VdbeComment((v, "pk"));
106125       sqlcipher3ExprCacheAffinityChange(pParse, r1, 1);
106126       sqlcipher3ReleaseTempReg(pParse, rTemp);
106127       disableTerm(pLevel, pStart);
106128     }else{
106129       sqlcipher3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
106130     }
106131     if( pEnd ){
106132       Expr *pX;
106133       pX = pEnd->pExpr;
106134       assert( pX!=0 );
106135       assert( pEnd->leftCursor==iCur );
106136       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106137       memEndValue = ++pParse->nMem;
106138       sqlcipher3ExprCode(pParse, pX->pRight, memEndValue);
106139       if( pX->op==TK_LT || pX->op==TK_GT ){
106140         testOp = bRev ? OP_Le : OP_Ge;
106141       }else{
106142         testOp = bRev ? OP_Lt : OP_Gt;
106143       }
106144       disableTerm(pLevel, pEnd);
106145     }
106146     start = sqlcipher3VdbeCurrentAddr(v);
106147     pLevel->op = bRev ? OP_Prev : OP_Next;
106148     pLevel->p1 = iCur;
106149     pLevel->p2 = start;
106150     if( pStart==0 && pEnd==0 ){
106151       pLevel->p5 = SQLCIPHER_STMTSTATUS_FULLSCAN_STEP;
106152     }else{
106153       assert( pLevel->p5==0 );
106154     }
106155     if( testOp!=OP_Noop ){
106156       iRowidReg = iReleaseReg = sqlcipher3GetTempReg(pParse);
106157       sqlcipher3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
106158       sqlcipher3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106159       sqlcipher3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
106160       sqlcipher3VdbeChangeP5(v, SQLCIPHER_AFF_NUMERIC | SQLCIPHER_JUMPIFNULL);
106161     }
106162   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
106163     /* Case 3: A scan using an index.
106164     **
106165     **         The WHERE clause may contain zero or more equality 
106166     **         terms ("==" or "IN" operators) that refer to the N
106167     **         left-most columns of the index. It may also contain
106168     **         inequality constraints (>, <, >= or <=) on the indexed
106169     **         column that immediately follows the N equalities. Only 
106170     **         the right-most column can be an inequality - the rest must
106171     **         use the "==" and "IN" operators. For example, if the 
106172     **         index is on (x,y,z), then the following clauses are all 
106173     **         optimized:
106174     **
106175     **            x=5
106176     **            x=5 AND y=10
106177     **            x=5 AND y<10
106178     **            x=5 AND y>5 AND y<10
106179     **            x=5 AND y=5 AND z<=10
106180     **
106181     **         The z<10 term of the following cannot be used, only
106182     **         the x=5 term:
106183     **
106184     **            x=5 AND z<10
106185     **
106186     **         N may be zero if there are inequality constraints.
106187     **         If there are no inequality constraints, then N is at
106188     **         least one.
106189     **
106190     **         This case is also used when there are no WHERE clause
106191     **         constraints but an index is selected anyway, in order
106192     **         to force the output order to conform to an ORDER BY.
106193     */  
106194     static const u8 aStartOp[] = {
106195       0,
106196       0,
106197       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
106198       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
106199       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
106200       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
106201       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
106202       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
106203     };
106204     static const u8 aEndOp[] = {
106205       OP_Noop,             /* 0: (!end_constraints) */
106206       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
106207       OP_IdxLT             /* 2: (end_constraints && bRev) */
106208     };
106209     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
106210     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
106211     int regBase;                 /* Base register holding constraint values */
106212     int r1;                      /* Temp register */
106213     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
106214     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
106215     int startEq;                 /* True if range start uses ==, >= or <= */
106216     int endEq;                   /* True if range end uses ==, >= or <= */
106217     int start_constraints;       /* Start of range is constrained */
106218     int nConstraint;             /* Number of constraint terms */
106219     Index *pIdx;                 /* The index we will be using */
106220     int iIdxCur;                 /* The VDBE cursor for the index */
106221     int nExtraReg = 0;           /* Number of extra registers needed */
106222     int op;                      /* Instruction opcode */
106223     char *zStartAff;             /* Affinity for start of range constraint */
106224     char *zEndAff;               /* Affinity for end of range constraint */
106225
106226     pIdx = pLevel->plan.u.pIdx;
106227     iIdxCur = pLevel->iIdxCur;
106228     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
106229
106230     /* If this loop satisfies a sort order (pOrderBy) request that 
106231     ** was passed to this function to implement a "SELECT min(x) ..." 
106232     ** query, then the caller will only allow the loop to run for
106233     ** a single iteration. This means that the first row returned
106234     ** should not have a NULL value stored in 'x'. If column 'x' is
106235     ** the first one after the nEq equality constraints in the index,
106236     ** this requires some special handling.
106237     */
106238     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
106239      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
106240      && (pIdx->nColumn>nEq)
106241     ){
106242       /* assert( pOrderBy->nExpr==1 ); */
106243       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
106244       isMinQuery = 1;
106245       nExtraReg = 1;
106246     }
106247
106248     /* Find any inequality constraint terms for the start and end 
106249     ** of the range. 
106250     */
106251     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
106252       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
106253       nExtraReg = 1;
106254     }
106255     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
106256       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
106257       nExtraReg = 1;
106258     }
106259
106260     /* Generate code to evaluate all constraint terms using == or IN
106261     ** and store the values of those terms in an array of registers
106262     ** starting at regBase.
106263     */
106264     regBase = codeAllEqualityTerms(
106265         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
106266     );
106267     zEndAff = sqlcipher3DbStrDup(pParse->db, zStartAff);
106268     addrNxt = pLevel->addrNxt;
106269
106270     /* If we are doing a reverse order scan on an ascending index, or
106271     ** a forward order scan on a descending index, interchange the 
106272     ** start and end terms (pRangeStart and pRangeEnd).
106273     */
106274     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLCIPHER_SO_ASC) ){
106275       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
106276     }
106277
106278     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
106279     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
106280     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
106281     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
106282     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
106283     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
106284     start_constraints = pRangeStart || nEq>0;
106285
106286     /* Seek the index cursor to the start of the range. */
106287     nConstraint = nEq;
106288     if( pRangeStart ){
106289       Expr *pRight = pRangeStart->pExpr->pRight;
106290       sqlcipher3ExprCode(pParse, pRight, regBase+nEq);
106291       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
106292         sqlcipher3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106293       }
106294       if( zStartAff ){
106295         if( sqlcipher3CompareAffinity(pRight, zStartAff[nEq])==SQLCIPHER_AFF_NONE){
106296           /* Since the comparison is to be performed with no conversions
106297           ** applied to the operands, set the affinity to apply to pRight to 
106298           ** SQLCIPHER_AFF_NONE.  */
106299           zStartAff[nEq] = SQLCIPHER_AFF_NONE;
106300         }
106301         if( sqlcipher3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
106302           zStartAff[nEq] = SQLCIPHER_AFF_NONE;
106303         }
106304       }  
106305       nConstraint++;
106306       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106307     }else if( isMinQuery ){
106308       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
106309       nConstraint++;
106310       startEq = 0;
106311       start_constraints = 1;
106312     }
106313     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
106314     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
106315     assert( op!=0 );
106316     testcase( op==OP_Rewind );
106317     testcase( op==OP_Last );
106318     testcase( op==OP_SeekGt );
106319     testcase( op==OP_SeekGe );
106320     testcase( op==OP_SeekLe );
106321     testcase( op==OP_SeekLt );
106322     sqlcipher3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106323
106324     /* Load the value for the inequality constraint at the end of the
106325     ** range (if any).
106326     */
106327     nConstraint = nEq;
106328     if( pRangeEnd ){
106329       Expr *pRight = pRangeEnd->pExpr->pRight;
106330       sqlcipher3ExprCacheRemove(pParse, regBase+nEq, 1);
106331       sqlcipher3ExprCode(pParse, pRight, regBase+nEq);
106332       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
106333         sqlcipher3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106334       }
106335       if( zEndAff ){
106336         if( sqlcipher3CompareAffinity(pRight, zEndAff[nEq])==SQLCIPHER_AFF_NONE){
106337           /* Since the comparison is to be performed with no conversions
106338           ** applied to the operands, set the affinity to apply to pRight to 
106339           ** SQLCIPHER_AFF_NONE.  */
106340           zEndAff[nEq] = SQLCIPHER_AFF_NONE;
106341         }
106342         if( sqlcipher3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
106343           zEndAff[nEq] = SQLCIPHER_AFF_NONE;
106344         }
106345       }  
106346       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
106347       nConstraint++;
106348       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106349     }
106350     sqlcipher3DbFree(pParse->db, zStartAff);
106351     sqlcipher3DbFree(pParse->db, zEndAff);
106352
106353     /* Top of the loop body */
106354     pLevel->p2 = sqlcipher3VdbeCurrentAddr(v);
106355
106356     /* Check if the index cursor is past the end of the range. */
106357     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
106358     testcase( op==OP_Noop );
106359     testcase( op==OP_IdxGE );
106360     testcase( op==OP_IdxLT );
106361     if( op!=OP_Noop ){
106362       sqlcipher3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106363       sqlcipher3VdbeChangeP5(v, endEq!=bRev ?1:0);
106364     }
106365
106366     /* If there are inequality constraints, check that the value
106367     ** of the table column that the inequality contrains is not NULL.
106368     ** If it is, jump to the next iteration of the loop.
106369     */
106370     r1 = sqlcipher3GetTempReg(pParse);
106371     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
106372     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
106373     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
106374       sqlcipher3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
106375       sqlcipher3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
106376     }
106377     sqlcipher3ReleaseTempReg(pParse, r1);
106378
106379     /* Seek the table cursor, if required */
106380     disableTerm(pLevel, pRangeStart);
106381     disableTerm(pLevel, pRangeEnd);
106382     if( !omitTable ){
106383       iRowidReg = iReleaseReg = sqlcipher3GetTempReg(pParse);
106384       sqlcipher3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
106385       sqlcipher3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106386       sqlcipher3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
106387     }
106388
106389     /* Record the instruction used to terminate the loop. Disable 
106390     ** WHERE clause terms made redundant by the index range scan.
106391     */
106392     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
106393       pLevel->op = OP_Noop;
106394     }else if( bRev ){
106395       pLevel->op = OP_Prev;
106396     }else{
106397       pLevel->op = OP_Next;
106398     }
106399     pLevel->p1 = iIdxCur;
106400   }else
106401
106402 #ifndef SQLCIPHER_OMIT_OR_OPTIMIZATION
106403   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
106404     /* Case 4:  Two or more separately indexed terms connected by OR
106405     **
106406     ** Example:
106407     **
106408     **   CREATE TABLE t1(a,b,c,d);
106409     **   CREATE INDEX i1 ON t1(a);
106410     **   CREATE INDEX i2 ON t1(b);
106411     **   CREATE INDEX i3 ON t1(c);
106412     **
106413     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
106414     **
106415     ** In the example, there are three indexed terms connected by OR.
106416     ** The top of the loop looks like this:
106417     **
106418     **          Null       1                # Zero the rowset in reg 1
106419     **
106420     ** Then, for each indexed term, the following. The arguments to
106421     ** RowSetTest are such that the rowid of the current row is inserted
106422     ** into the RowSet. If it is already present, control skips the
106423     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
106424     **
106425     **        sqlcipher3WhereBegin(<term>)
106426     **          RowSetTest                  # Insert rowid into rowset
106427     **          Gosub      2 A
106428     **        sqlcipher3WhereEnd()
106429     **
106430     ** Following the above, code to terminate the loop. Label A, the target
106431     ** of the Gosub above, jumps to the instruction right after the Goto.
106432     **
106433     **          Null       1                # Zero the rowset in reg 1
106434     **          Goto       B                # The loop is finished.
106435     **
106436     **       A: <loop body>                 # Return data, whatever.
106437     **
106438     **          Return     2                # Jump back to the Gosub
106439     **
106440     **       B: <after the loop>
106441     **
106442     */
106443     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
106444     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
106445
106446     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
106447     int regRowset = 0;                        /* Register for RowSet object */
106448     int regRowid = 0;                         /* Register holding rowid */
106449     int iLoopBody = sqlcipher3VdbeMakeLabel(v);  /* Start of loop body */
106450     int iRetInit;                             /* Address of regReturn init */
106451     int untestedTerms = 0;             /* Some terms not completely tested */
106452     int ii;                            /* Loop counter */
106453     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
106454    
106455     pTerm = pLevel->plan.u.pTerm;
106456     assert( pTerm!=0 );
106457     assert( pTerm->eOperator==WO_OR );
106458     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
106459     pOrWc = &pTerm->u.pOrInfo->wc;
106460     pLevel->op = OP_Return;
106461     pLevel->p1 = regReturn;
106462
106463     /* Set up a new SrcList ni pOrTab containing the table being scanned
106464     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
106465     ** This becomes the SrcList in the recursive call to sqlcipher3WhereBegin().
106466     */
106467     if( pWInfo->nLevel>1 ){
106468       int nNotReady;                 /* The number of notReady tables */
106469       struct SrcList_item *origSrc;     /* Original list of tables */
106470       nNotReady = pWInfo->nLevel - iLevel - 1;
106471       pOrTab = sqlcipher3StackAllocRaw(pParse->db,
106472                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
106473       if( pOrTab==0 ) return notReady;
106474       pOrTab->nAlloc = (i16)(nNotReady + 1);
106475       pOrTab->nSrc = pOrTab->nAlloc;
106476       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
106477       origSrc = pWInfo->pTabList->a;
106478       for(k=1; k<=nNotReady; k++){
106479         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
106480       }
106481     }else{
106482       pOrTab = pWInfo->pTabList;
106483     }
106484
106485     /* Initialize the rowset register to contain NULL. An SQL NULL is 
106486     ** equivalent to an empty rowset.
106487     **
106488     ** Also initialize regReturn to contain the address of the instruction 
106489     ** immediately following the OP_Return at the bottom of the loop. This
106490     ** is required in a few obscure LEFT JOIN cases where control jumps
106491     ** over the top of the loop into the body of it. In this case the 
106492     ** correct response for the end-of-loop code (the OP_Return) is to 
106493     ** fall through to the next instruction, just as an OP_Next does if
106494     ** called on an uninitialized cursor.
106495     */
106496     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106497       regRowset = ++pParse->nMem;
106498       regRowid = ++pParse->nMem;
106499       sqlcipher3VdbeAddOp2(v, OP_Null, 0, regRowset);
106500     }
106501     iRetInit = sqlcipher3VdbeAddOp2(v, OP_Integer, 0, regReturn);
106502
106503     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
106504     ** Then for every term xN, evaluate as the subexpression: xN AND z
106505     ** That way, terms in y that are factored into the disjunction will
106506     ** be picked up by the recursive calls to sqlcipher3WhereBegin() below.
106507     */
106508     if( pWC->nTerm>1 ){
106509       pAndExpr = sqlcipher3ExprAlloc(pParse->db, TK_AND, 0, 0);
106510       pAndExpr->pRight = pWhere;
106511     }
106512
106513     for(ii=0; ii<pOrWc->nTerm; ii++){
106514       WhereTerm *pOrTerm = &pOrWc->a[ii];
106515       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
106516         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
106517         Expr *pOrExpr = pOrTerm->pExpr;
106518         if( pAndExpr ){
106519           pAndExpr->pLeft = pOrExpr;
106520           pOrExpr = pAndExpr;
106521         }
106522         /* Loop through table entries that match term pOrTerm. */
106523         pSubWInfo = sqlcipher3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
106524                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
106525                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
106526         if( pSubWInfo ){
106527           explainOneScan(
106528               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
106529           );
106530           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106531             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
106532             int r;
106533             r = sqlcipher3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
106534                                          regRowid);
106535             sqlcipher3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
106536                                  sqlcipher3VdbeCurrentAddr(v)+2, r, iSet);
106537           }
106538           sqlcipher3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
106539
106540           /* The pSubWInfo->untestedTerms flag means that this OR term
106541           ** contained one or more AND term from a notReady table.  The
106542           ** terms from the notReady table could not be tested and will
106543           ** need to be tested later.
106544           */
106545           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
106546
106547           /* Finish the loop through table entries that match term pOrTerm. */
106548           sqlcipher3WhereEnd(pSubWInfo);
106549         }
106550       }
106551     }
106552     sqlcipher3DbFree(pParse->db, pAndExpr);
106553     sqlcipher3VdbeChangeP1(v, iRetInit, sqlcipher3VdbeCurrentAddr(v));
106554     sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
106555     sqlcipher3VdbeResolveLabel(v, iLoopBody);
106556
106557     if( pWInfo->nLevel>1 ) sqlcipher3StackFree(pParse->db, pOrTab);
106558     if( !untestedTerms ) disableTerm(pLevel, pTerm);
106559   }else
106560 #endif /* SQLCIPHER_OMIT_OR_OPTIMIZATION */
106561
106562   {
106563     /* Case 5:  There is no usable index.  We must do a complete
106564     **          scan of the entire table.
106565     */
106566     static const u8 aStep[] = { OP_Next, OP_Prev };
106567     static const u8 aStart[] = { OP_Rewind, OP_Last };
106568     assert( bRev==0 || bRev==1 );
106569     assert( omitTable==0 );
106570     pLevel->op = aStep[bRev];
106571     pLevel->p1 = iCur;
106572     pLevel->p2 = 1 + sqlcipher3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
106573     pLevel->p5 = SQLCIPHER_STMTSTATUS_FULLSCAN_STEP;
106574   }
106575   notReady &= ~getMask(pWC->pMaskSet, iCur);
106576
106577   /* Insert code to test every subexpression that can be completely
106578   ** computed using the current set of tables.
106579   **
106580   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
106581   ** the use of indices become tests that are evaluated against each row of
106582   ** the relevant input tables.
106583   */
106584   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
106585     Expr *pE;
106586     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
106587     testcase( pTerm->wtFlags & TERM_CODED );
106588     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106589     if( (pTerm->prereqAll & notReady)!=0 ){
106590       testcase( pWInfo->untestedTerms==0
106591                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
106592       pWInfo->untestedTerms = 1;
106593       continue;
106594     }
106595     pE = pTerm->pExpr;
106596     assert( pE!=0 );
106597     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
106598       continue;
106599     }
106600     sqlcipher3ExprIfFalse(pParse, pE, addrCont, SQLCIPHER_JUMPIFNULL);
106601     pTerm->wtFlags |= TERM_CODED;
106602   }
106603
106604   /* For a LEFT OUTER JOIN, generate code that will record the fact that
106605   ** at least one row of the right table has matched the left table.  
106606   */
106607   if( pLevel->iLeftJoin ){
106608     pLevel->addrFirst = sqlcipher3VdbeCurrentAddr(v);
106609     sqlcipher3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
106610     VdbeComment((v, "record LEFT JOIN hit"));
106611     sqlcipher3ExprCacheClear(pParse);
106612     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
106613       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
106614       testcase( pTerm->wtFlags & TERM_CODED );
106615       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106616       if( (pTerm->prereqAll & notReady)!=0 ){
106617         assert( pWInfo->untestedTerms );
106618         continue;
106619       }
106620       assert( pTerm->pExpr );
106621       sqlcipher3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLCIPHER_JUMPIFNULL);
106622       pTerm->wtFlags |= TERM_CODED;
106623     }
106624   }
106625   sqlcipher3ReleaseTempReg(pParse, iReleaseReg);
106626
106627   return notReady;
106628 }
106629
106630 #if defined(SQLCIPHER_TEST)
106631 /*
106632 ** The following variable holds a text description of query plan generated
106633 ** by the most recent call to sqlcipher3WhereBegin().  Each call to WhereBegin
106634 ** overwrites the previous.  This information is used for testing and
106635 ** analysis only.
106636 */
106637 SQLCIPHER_API char sqlcipher3_query_plan[BMS*2*40];  /* Text of the join */
106638 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
106639
106640 #endif /* SQLCIPHER_TEST */
106641
106642
106643 /*
106644 ** Free a WhereInfo structure
106645 */
106646 static void whereInfoFree(sqlcipher3 *db, WhereInfo *pWInfo){
106647   if( ALWAYS(pWInfo) ){
106648     int i;
106649     for(i=0; i<pWInfo->nLevel; i++){
106650       sqlcipher3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
106651       if( pInfo ){
106652         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
106653         if( pInfo->needToFreeIdxStr ){
106654           sqlcipher3_free(pInfo->idxStr);
106655         }
106656         sqlcipher3DbFree(db, pInfo);
106657       }
106658       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
106659         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
106660         if( pIdx ){
106661           sqlcipher3DbFree(db, pIdx->zColAff);
106662           sqlcipher3DbFree(db, pIdx);
106663         }
106664       }
106665     }
106666     whereClauseClear(pWInfo->pWC);
106667     sqlcipher3DbFree(db, pWInfo);
106668   }
106669 }
106670
106671
106672 /*
106673 ** Generate the beginning of the loop used for WHERE clause processing.
106674 ** The return value is a pointer to an opaque structure that contains
106675 ** information needed to terminate the loop.  Later, the calling routine
106676 ** should invoke sqlcipher3WhereEnd() with the return value of this function
106677 ** in order to complete the WHERE clause processing.
106678 **
106679 ** If an error occurs, this routine returns NULL.
106680 **
106681 ** The basic idea is to do a nested loop, one loop for each table in
106682 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
106683 ** same as a SELECT with only a single table in the FROM clause.)  For
106684 ** example, if the SQL is this:
106685 **
106686 **       SELECT * FROM t1, t2, t3 WHERE ...;
106687 **
106688 ** Then the code generated is conceptually like the following:
106689 **
106690 **      foreach row1 in t1 do       \    Code generated
106691 **        foreach row2 in t2 do      |-- by sqlcipher3WhereBegin()
106692 **          foreach row3 in t3 do   /
106693 **            ...
106694 **          end                     \    Code generated
106695 **        end                        |-- by sqlcipher3WhereEnd()
106696 **      end                         /
106697 **
106698 ** Note that the loops might not be nested in the order in which they
106699 ** appear in the FROM clause if a different order is better able to make
106700 ** use of indices.  Note also that when the IN operator appears in
106701 ** the WHERE clause, it might result in additional nested loops for
106702 ** scanning through all values on the right-hand side of the IN.
106703 **
106704 ** There are Btree cursors associated with each table.  t1 uses cursor
106705 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
106706 ** And so forth.  This routine generates code to open those VDBE cursors
106707 ** and sqlcipher3WhereEnd() generates the code to close them.
106708 **
106709 ** The code that sqlcipher3WhereBegin() generates leaves the cursors named
106710 ** in pTabList pointing at their appropriate entries.  The [...] code
106711 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
106712 ** data from the various tables of the loop.
106713 **
106714 ** If the WHERE clause is empty, the foreach loops must each scan their
106715 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
106716 ** the tables have indices and there are terms in the WHERE clause that
106717 ** refer to those indices, a complete table scan can be avoided and the
106718 ** code will run much faster.  Most of the work of this routine is checking
106719 ** to see if there are indices that can be used to speed up the loop.
106720 **
106721 ** Terms of the WHERE clause are also used to limit which rows actually
106722 ** make it to the "..." in the middle of the loop.  After each "foreach",
106723 ** terms of the WHERE clause that use only terms in that loop and outer
106724 ** loops are evaluated and if false a jump is made around all subsequent
106725 ** inner loops (or around the "..." if the test occurs within the inner-
106726 ** most loop)
106727 **
106728 ** OUTER JOINS
106729 **
106730 ** An outer join of tables t1 and t2 is conceptally coded as follows:
106731 **
106732 **    foreach row1 in t1 do
106733 **      flag = 0
106734 **      foreach row2 in t2 do
106735 **        start:
106736 **          ...
106737 **          flag = 1
106738 **      end
106739 **      if flag==0 then
106740 **        move the row2 cursor to a null row
106741 **        goto start
106742 **      fi
106743 **    end
106744 **
106745 ** ORDER BY CLAUSE PROCESSING
106746 **
106747 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
106748 ** if there is one.  If there is no ORDER BY clause or if this routine
106749 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
106750 **
106751 ** If an index can be used so that the natural output order of the table
106752 ** scan is correct for the ORDER BY clause, then that index is used and
106753 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
106754 ** unnecessary sort of the result set if an index appropriate for the
106755 ** ORDER BY clause already exists.
106756 **
106757 ** If the where clause loops cannot be arranged to provide the correct
106758 ** output order, then the *ppOrderBy is unchanged.
106759 */
106760 SQLCIPHER_PRIVATE WhereInfo *sqlcipher3WhereBegin(
106761   Parse *pParse,        /* The parser context */
106762   SrcList *pTabList,    /* A list of all tables to be scanned */
106763   Expr *pWhere,         /* The WHERE clause */
106764   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
106765   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
106766   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqlcipherInt.h */
106767 ){
106768   int i;                     /* Loop counter */
106769   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
106770   int nTabList;              /* Number of elements in pTabList */
106771   WhereInfo *pWInfo;         /* Will become the return value of this function */
106772   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
106773   Bitmask notReady;          /* Cursors that are not yet positioned */
106774   WhereMaskSet *pMaskSet;    /* The expression mask set */
106775   WhereClause *pWC;               /* Decomposition of the WHERE clause */
106776   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
106777   WhereLevel *pLevel;             /* A single level in the pWInfo list */
106778   int iFrom;                      /* First unused FROM clause element */
106779   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
106780   sqlcipher3 *db;               /* Database connection */
106781
106782   /* The number of tables in the FROM clause is limited by the number of
106783   ** bits in a Bitmask 
106784   */
106785   testcase( pTabList->nSrc==BMS );
106786   if( pTabList->nSrc>BMS ){
106787     sqlcipher3ErrorMsg(pParse, "at most %d tables in a join", BMS);
106788     return 0;
106789   }
106790
106791   /* This function normally generates a nested loop for all tables in 
106792   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
106793   ** only generate code for the first table in pTabList and assume that
106794   ** any cursors associated with subsequent tables are uninitialized.
106795   */
106796   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
106797
106798   /* Allocate and initialize the WhereInfo structure that will become the
106799   ** return value. A single allocation is used to store the WhereInfo
106800   ** struct, the contents of WhereInfo.a[], the WhereClause structure
106801   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
106802   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
106803   ** some architectures. Hence the ROUND8() below.
106804   */
106805   db = pParse->db;
106806   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
106807   pWInfo = sqlcipher3DbMallocZero(db, 
106808       nByteWInfo + 
106809       sizeof(WhereClause) +
106810       sizeof(WhereMaskSet)
106811   );
106812   if( db->mallocFailed ){
106813     sqlcipher3DbFree(db, pWInfo);
106814     pWInfo = 0;
106815     goto whereBeginError;
106816   }
106817   pWInfo->nLevel = nTabList;
106818   pWInfo->pParse = pParse;
106819   pWInfo->pTabList = pTabList;
106820   pWInfo->iBreak = sqlcipher3VdbeMakeLabel(v);
106821   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
106822   pWInfo->wctrlFlags = wctrlFlags;
106823   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
106824   pMaskSet = (WhereMaskSet*)&pWC[1];
106825
106826   /* Disable the DISTINCT optimization if SQLCIPHER_DistinctOpt is set via
106827   ** sqlcipher3_test_ctrl(SQLCIPHER_TESTCTRL_OPTIMIZATIONS,...) */
106828   if( db->flags & SQLCIPHER_DistinctOpt ) pDistinct = 0;
106829
106830   /* Split the WHERE clause into separate subexpressions where each
106831   ** subexpression is separated by an AND operator.
106832   */
106833   initMaskSet(pMaskSet);
106834   whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
106835   sqlcipher3ExprCodeConstants(pParse, pWhere);
106836   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
106837     
106838   /* Special case: a WHERE clause that is constant.  Evaluate the
106839   ** expression and either jump over all of the code or fall thru.
106840   */
106841   if( pWhere && (nTabList==0 || sqlcipher3ExprIsConstantNotJoin(pWhere)) ){
106842     sqlcipher3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLCIPHER_JUMPIFNULL);
106843     pWhere = 0;
106844   }
106845
106846   /* Assign a bit from the bitmask to every term in the FROM clause.
106847   **
106848   ** When assigning bitmask values to FROM clause cursors, it must be
106849   ** the case that if X is the bitmask for the N-th FROM clause term then
106850   ** the bitmask for all FROM clause terms to the left of the N-th term
106851   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
106852   ** its Expr.iRightJoinTable value to find the bitmask of the right table
106853   ** of the join.  Subtracting one from the right table bitmask gives a
106854   ** bitmask for all tables to the left of the join.  Knowing the bitmask
106855   ** for all tables to the left of a left join is important.  Ticket #3015.
106856   **
106857   ** Configure the WhereClause.vmask variable so that bits that correspond
106858   ** to virtual table cursors are set. This is used to selectively disable 
106859   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
106860   ** with virtual tables.
106861   **
106862   ** Note that bitmasks are created for all pTabList->nSrc tables in
106863   ** pTabList, not just the first nTabList tables.  nTabList is normally
106864   ** equal to pTabList->nSrc but might be shortened to 1 if the
106865   ** WHERE_ONETABLE_ONLY flag is set.
106866   */
106867   assert( pWC->vmask==0 && pMaskSet->n==0 );
106868   for(i=0; i<pTabList->nSrc; i++){
106869     createMask(pMaskSet, pTabList->a[i].iCursor);
106870 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
106871     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
106872       pWC->vmask |= ((Bitmask)1 << i);
106873     }
106874 #endif
106875   }
106876 #ifndef NDEBUG
106877   {
106878     Bitmask toTheLeft = 0;
106879     for(i=0; i<pTabList->nSrc; i++){
106880       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
106881       assert( (m-1)==toTheLeft );
106882       toTheLeft |= m;
106883     }
106884   }
106885 #endif
106886
106887   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
106888   ** add new virtual terms onto the end of the WHERE clause.  We do not
106889   ** want to analyze these virtual terms, so start analyzing at the end
106890   ** and work forward so that the added virtual terms are never processed.
106891   */
106892   exprAnalyzeAll(pTabList, pWC);
106893   if( db->mallocFailed ){
106894     goto whereBeginError;
106895   }
106896
106897   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
106898   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
106899   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
106900   */
106901   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
106902     pDistinct = 0;
106903     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
106904   }
106905
106906   /* Chose the best index to use for each table in the FROM clause.
106907   **
106908   ** This loop fills in the following fields:
106909   **
106910   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
106911   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
106912   **   pWInfo->a[].nEq       The number of == and IN constraints
106913   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
106914   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
106915   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
106916   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
106917   **
106918   ** This loop also figures out the nesting order of tables in the FROM
106919   ** clause.
106920   */
106921   notReady = ~(Bitmask)0;
106922   andFlags = ~0;
106923   WHERETRACE(("*** Optimizer Start ***\n"));
106924   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
106925     WhereCost bestPlan;         /* Most efficient plan seen so far */
106926     Index *pIdx;                /* Index for FROM table at pTabItem */
106927     int j;                      /* For looping over FROM tables */
106928     int bestJ = -1;             /* The value of j */
106929     Bitmask m;                  /* Bitmask value for j or bestJ */
106930     int isOptimal;              /* Iterator for optimal/non-optimal search */
106931     int nUnconstrained;         /* Number tables without INDEXED BY */
106932     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
106933
106934     memset(&bestPlan, 0, sizeof(bestPlan));
106935     bestPlan.rCost = SQLCIPHER_BIG_DBL;
106936     WHERETRACE(("*** Begin search for loop %d ***\n", i));
106937
106938     /* Loop through the remaining entries in the FROM clause to find the
106939     ** next nested loop. The loop tests all FROM clause entries
106940     ** either once or twice. 
106941     **
106942     ** The first test is always performed if there are two or more entries
106943     ** remaining and never performed if there is only one FROM clause entry
106944     ** to choose from.  The first test looks for an "optimal" scan.  In
106945     ** this context an optimal scan is one that uses the same strategy
106946     ** for the given FROM clause entry as would be selected if the entry
106947     ** were used as the innermost nested loop.  In other words, a table
106948     ** is chosen such that the cost of running that table cannot be reduced
106949     ** by waiting for other tables to run first.  This "optimal" test works
106950     ** by first assuming that the FROM clause is on the inner loop and finding
106951     ** its query plan, then checking to see if that query plan uses any
106952     ** other FROM clause terms that are notReady.  If no notReady terms are
106953     ** used then the "optimal" query plan works.
106954     **
106955     ** Note that the WhereCost.nRow parameter for an optimal scan might
106956     ** not be as small as it would be if the table really were the innermost
106957     ** join.  The nRow value can be reduced by WHERE clause constraints
106958     ** that do not use indices.  But this nRow reduction only happens if the
106959     ** table really is the innermost join.  
106960     **
106961     ** The second loop iteration is only performed if no optimal scan
106962     ** strategies were found by the first iteration. This second iteration
106963     ** is used to search for the lowest cost scan overall.
106964     **
106965     ** Previous versions of SQLite performed only the second iteration -
106966     ** the next outermost loop was always that with the lowest overall
106967     ** cost. However, this meant that SQLite could select the wrong plan
106968     ** for scripts such as the following:
106969     **   
106970     **   CREATE TABLE t1(a, b); 
106971     **   CREATE TABLE t2(c, d);
106972     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
106973     **
106974     ** The best strategy is to iterate through table t1 first. However it
106975     ** is not possible to determine this with a simple greedy algorithm.
106976     ** Since the cost of a linear scan through table t2 is the same 
106977     ** as the cost of a linear scan through table t1, a simple greedy 
106978     ** algorithm may choose to use t2 for the outer loop, which is a much
106979     ** costlier approach.
106980     */
106981     nUnconstrained = 0;
106982     notIndexed = 0;
106983     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
106984       Bitmask mask;             /* Mask of tables not yet ready */
106985       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
106986         int doNotReorder;    /* True if this table should not be reordered */
106987         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
106988         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
106989         ExprList *pDist;     /* DISTINCT clause for index to optimize */
106990   
106991         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
106992         if( j!=iFrom && doNotReorder ) break;
106993         m = getMask(pMaskSet, pTabItem->iCursor);
106994         if( (m & notReady)==0 ){
106995           if( j==iFrom ) iFrom++;
106996           continue;
106997         }
106998         mask = (isOptimal ? m : notReady);
106999         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
107000         pDist = (i==0 ? pDistinct : 0);
107001         if( pTabItem->pIndex==0 ) nUnconstrained++;
107002   
107003         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
107004                     j, isOptimal));
107005         assert( pTabItem->pTab );
107006 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
107007         if( IsVirtual(pTabItem->pTab) ){
107008           sqlcipher3_index_info **pp = &pWInfo->a[j].pIdxInfo;
107009           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
107010                            &sCost, pp);
107011         }else 
107012 #endif
107013         {
107014           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
107015               pDist, &sCost);
107016         }
107017         assert( isOptimal || (sCost.used&notReady)==0 );
107018
107019         /* If an INDEXED BY clause is present, then the plan must use that
107020         ** index if it uses any index at all */
107021         assert( pTabItem->pIndex==0 
107022                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107023                   || sCost.plan.u.pIdx==pTabItem->pIndex );
107024
107025         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107026           notIndexed |= m;
107027         }
107028
107029         /* Conditions under which this table becomes the best so far:
107030         **
107031         **   (1) The table must not depend on other tables that have not
107032         **       yet run.
107033         **
107034         **   (2) A full-table-scan plan cannot supercede indexed plan unless
107035         **       the full-table-scan is an "optimal" plan as defined above.
107036         **
107037         **   (3) All tables have an INDEXED BY clause or this table lacks an
107038         **       INDEXED BY clause or this table uses the specific
107039         **       index specified by its INDEXED BY clause.  This rule ensures
107040         **       that a best-so-far is always selected even if an impossible
107041         **       combination of INDEXED BY clauses are given.  The error
107042         **       will be detected and relayed back to the application later.
107043         **       The NEVER() comes about because rule (2) above prevents
107044         **       An indexable full-table-scan from reaching rule (3).
107045         **
107046         **   (4) The plan cost must be lower than prior plans or else the
107047         **       cost must be the same and the number of rows must be lower.
107048         */
107049         if( (sCost.used&notReady)==0                       /* (1) */
107050             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
107051                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107052                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
107053             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
107054                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
107055             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
107056                 || (sCost.rCost<=bestPlan.rCost 
107057                  && sCost.plan.nRow<bestPlan.plan.nRow))
107058         ){
107059           WHERETRACE(("=== table %d is best so far"
107060                       " with cost=%g and nRow=%g\n",
107061                       j, sCost.rCost, sCost.plan.nRow));
107062           bestPlan = sCost;
107063           bestJ = j;
107064         }
107065         if( doNotReorder ) break;
107066       }
107067     }
107068     assert( bestJ>=0 );
107069     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
107070     WHERETRACE(("*** Optimizer selects table %d for loop %d"
107071                 " with cost=%g and nRow=%g\n",
107072                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
107073     /* The ALWAYS() that follows was added to hush up clang scan-build */
107074     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
107075       *ppOrderBy = 0;
107076     }
107077     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
107078       assert( pWInfo->eDistinct==0 );
107079       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
107080     }
107081     andFlags &= bestPlan.plan.wsFlags;
107082     pLevel->plan = bestPlan.plan;
107083     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
107084     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
107085     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
107086       pLevel->iIdxCur = pParse->nTab++;
107087     }else{
107088       pLevel->iIdxCur = -1;
107089     }
107090     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
107091     pLevel->iFrom = (u8)bestJ;
107092     if( bestPlan.plan.nRow>=(double)1 ){
107093       pParse->nQueryLoop *= bestPlan.plan.nRow;
107094     }
107095
107096     /* Check that if the table scanned by this loop iteration had an
107097     ** INDEXED BY clause attached to it, that the named index is being
107098     ** used for the scan. If not, then query compilation has failed.
107099     ** Return an error.
107100     */
107101     pIdx = pTabList->a[bestJ].pIndex;
107102     if( pIdx ){
107103       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
107104         sqlcipher3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
107105         goto whereBeginError;
107106       }else{
107107         /* If an INDEXED BY clause is used, the bestIndex() function is
107108         ** guaranteed to find the index specified in the INDEXED BY clause
107109         ** if it find an index at all. */
107110         assert( bestPlan.plan.u.pIdx==pIdx );
107111       }
107112     }
107113   }
107114   WHERETRACE(("*** Optimizer Finished ***\n"));
107115   if( pParse->nErr || db->mallocFailed ){
107116     goto whereBeginError;
107117   }
107118
107119   /* If the total query only selects a single row, then the ORDER BY
107120   ** clause is irrelevant.
107121   */
107122   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
107123     *ppOrderBy = 0;
107124   }
107125
107126   /* If the caller is an UPDATE or DELETE statement that is requesting
107127   ** to use a one-pass algorithm, determine if this is appropriate.
107128   ** The one-pass algorithm only works if the WHERE clause constraints
107129   ** the statement to update a single row.
107130   */
107131   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
107132   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
107133     pWInfo->okOnePass = 1;
107134     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
107135   }
107136
107137   /* Open all tables in the pTabList and any indices selected for
107138   ** searching those tables.
107139   */
107140   sqlcipher3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
107141   notReady = ~(Bitmask)0;
107142   pWInfo->nRowOut = (double)1;
107143   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
107144     Table *pTab;     /* Table to open */
107145     int iDb;         /* Index of database containing table/index */
107146
107147     pTabItem = &pTabList->a[pLevel->iFrom];
107148     pTab = pTabItem->pTab;
107149     pLevel->iTabCur = pTabItem->iCursor;
107150     pWInfo->nRowOut *= pLevel->plan.nRow;
107151     iDb = sqlcipher3SchemaToIndex(db, pTab->pSchema);
107152     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
107153       /* Do nothing */
107154     }else
107155 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
107156     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107157       const char *pVTab = (const char *)sqlcipher3GetVTable(db, pTab);
107158       int iCur = pTabItem->iCursor;
107159       sqlcipher3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
107160     }else
107161 #endif
107162     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107163          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
107164       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
107165       sqlcipher3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
107166       testcase( pTab->nCol==BMS-1 );
107167       testcase( pTab->nCol==BMS );
107168       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
107169         Bitmask b = pTabItem->colUsed;
107170         int n = 0;
107171         for(; b; b=b>>1, n++){}
107172         sqlcipher3VdbeChangeP4(v, sqlcipher3VdbeCurrentAddr(v)-1, 
107173                             SQLCIPHER_INT_TO_PTR(n), P4_INT32);
107174         assert( n<=pTab->nCol );
107175       }
107176     }else{
107177       sqlcipher3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107178     }
107179 #ifndef SQLCIPHER_OMIT_AUTOMATIC_INDEX
107180     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
107181       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
107182     }else
107183 #endif
107184     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107185       Index *pIx = pLevel->plan.u.pIdx;
107186       KeyInfo *pKey = sqlcipher3IndexKeyinfo(pParse, pIx);
107187       int iIdxCur = pLevel->iIdxCur;
107188       assert( pIx->pSchema==pTab->pSchema );
107189       assert( iIdxCur>=0 );
107190       sqlcipher3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
107191                         (char*)pKey, P4_KEYINFO_HANDOFF);
107192       VdbeComment((v, "%s", pIx->zName));
107193     }
107194     sqlcipher3CodeVerifySchema(pParse, iDb);
107195     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
107196   }
107197   pWInfo->iTop = sqlcipher3VdbeCurrentAddr(v);
107198   if( db->mallocFailed ) goto whereBeginError;
107199
107200   /* Generate the code to do the search.  Each iteration of the for
107201   ** loop below generates code for a single nested loop of the VM
107202   ** program.
107203   */
107204   notReady = ~(Bitmask)0;
107205   for(i=0; i<nTabList; i++){
107206     pLevel = &pWInfo->a[i];
107207     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
107208     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady, pWhere);
107209     pWInfo->iContinue = pLevel->addrCont;
107210   }
107211
107212 #ifdef SQLCIPHER_TEST  /* For testing and debugging use only */
107213   /* Record in the query plan information about the current table
107214   ** and the index used to access it (if any).  If the table itself
107215   ** is not used, its name is just '{}'.  If no index is used
107216   ** the index is listed as "{}".  If the primary key is used the
107217   ** index name is '*'.
107218   */
107219   for(i=0; i<nTabList; i++){
107220     char *z;
107221     int n;
107222     pLevel = &pWInfo->a[i];
107223     pTabItem = &pTabList->a[pLevel->iFrom];
107224     z = pTabItem->zAlias;
107225     if( z==0 ) z = pTabItem->pTab->zName;
107226     n = sqlcipher3Strlen30(z);
107227     if( n+nQPlan < sizeof(sqlcipher3_query_plan)-10 ){
107228       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
107229         memcpy(&sqlcipher3_query_plan[nQPlan], "{}", 2);
107230         nQPlan += 2;
107231       }else{
107232         memcpy(&sqlcipher3_query_plan[nQPlan], z, n);
107233         nQPlan += n;
107234       }
107235       sqlcipher3_query_plan[nQPlan++] = ' ';
107236     }
107237     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
107238     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
107239     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107240       memcpy(&sqlcipher3_query_plan[nQPlan], "* ", 2);
107241       nQPlan += 2;
107242     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107243       n = sqlcipher3Strlen30(pLevel->plan.u.pIdx->zName);
107244       if( n+nQPlan < sizeof(sqlcipher3_query_plan)-2 ){
107245         memcpy(&sqlcipher3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
107246         nQPlan += n;
107247         sqlcipher3_query_plan[nQPlan++] = ' ';
107248       }
107249     }else{
107250       memcpy(&sqlcipher3_query_plan[nQPlan], "{} ", 3);
107251       nQPlan += 3;
107252     }
107253   }
107254   while( nQPlan>0 && sqlcipher3_query_plan[nQPlan-1]==' ' ){
107255     sqlcipher3_query_plan[--nQPlan] = 0;
107256   }
107257   sqlcipher3_query_plan[nQPlan] = 0;
107258   nQPlan = 0;
107259 #endif /* SQLCIPHER_TEST // Testing and debugging use only */
107260
107261   /* Record the continuation address in the WhereInfo structure.  Then
107262   ** clean up and return.
107263   */
107264   return pWInfo;
107265
107266   /* Jump here if malloc fails */
107267 whereBeginError:
107268   if( pWInfo ){
107269     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107270     whereInfoFree(db, pWInfo);
107271   }
107272   return 0;
107273 }
107274
107275 /*
107276 ** Generate the end of the WHERE loop.  See comments on 
107277 ** sqlcipher3WhereBegin() for additional information.
107278 */
107279 SQLCIPHER_PRIVATE void sqlcipher3WhereEnd(WhereInfo *pWInfo){
107280   Parse *pParse = pWInfo->pParse;
107281   Vdbe *v = pParse->pVdbe;
107282   int i;
107283   WhereLevel *pLevel;
107284   SrcList *pTabList = pWInfo->pTabList;
107285   sqlcipher3 *db = pParse->db;
107286
107287   /* Generate loop termination code.
107288   */
107289   sqlcipher3ExprCacheClear(pParse);
107290   for(i=pWInfo->nLevel-1; i>=0; i--){
107291     pLevel = &pWInfo->a[i];
107292     sqlcipher3VdbeResolveLabel(v, pLevel->addrCont);
107293     if( pLevel->op!=OP_Noop ){
107294       sqlcipher3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
107295       sqlcipher3VdbeChangeP5(v, pLevel->p5);
107296     }
107297     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
107298       struct InLoop *pIn;
107299       int j;
107300       sqlcipher3VdbeResolveLabel(v, pLevel->addrNxt);
107301       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
107302         sqlcipher3VdbeJumpHere(v, pIn->addrInTop+1);
107303         sqlcipher3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
107304         sqlcipher3VdbeJumpHere(v, pIn->addrInTop-1);
107305       }
107306       sqlcipher3DbFree(db, pLevel->u.in.aInLoop);
107307     }
107308     sqlcipher3VdbeResolveLabel(v, pLevel->addrBrk);
107309     if( pLevel->iLeftJoin ){
107310       int addr;
107311       addr = sqlcipher3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
107312       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107313            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
107314       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
107315         sqlcipher3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
107316       }
107317       if( pLevel->iIdxCur>=0 ){
107318         sqlcipher3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
107319       }
107320       if( pLevel->op==OP_Return ){
107321         sqlcipher3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
107322       }else{
107323         sqlcipher3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
107324       }
107325       sqlcipher3VdbeJumpHere(v, addr);
107326     }
107327   }
107328
107329   /* The "break" point is here, just past the end of the outer loop.
107330   ** Set it.
107331   */
107332   sqlcipher3VdbeResolveLabel(v, pWInfo->iBreak);
107333
107334   /* Close all of the cursors that were opened by sqlcipher3WhereBegin.
107335   */
107336   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
107337   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
107338     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
107339     Table *pTab = pTabItem->pTab;
107340     assert( pTab!=0 );
107341     if( (pTab->tabFlags & TF_Ephemeral)==0
107342      && pTab->pSelect==0
107343      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
107344     ){
107345       int ws = pLevel->plan.wsFlags;
107346       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
107347         sqlcipher3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
107348       }
107349       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
107350         sqlcipher3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
107351       }
107352     }
107353
107354     /* If this scan uses an index, make code substitutions to read data
107355     ** from the index in preference to the table. Sometimes, this means
107356     ** the table need never be read from. This is a performance boost,
107357     ** as the vdbe level waits until the table is read before actually
107358     ** seeking the table cursor to the record corresponding to the current
107359     ** position in the index.
107360     ** 
107361     ** Calls to the code generator in between sqlcipher3WhereBegin and
107362     ** sqlcipher3WhereEnd will have created code that references the table
107363     ** directly.  This loop scans all that code looking for opcodes
107364     ** that reference the table and converts them into opcodes that
107365     ** reference the index.
107366     */
107367     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
107368       int k, j, last;
107369       VdbeOp *pOp;
107370       Index *pIdx = pLevel->plan.u.pIdx;
107371
107372       assert( pIdx!=0 );
107373       pOp = sqlcipher3VdbeGetOp(v, pWInfo->iTop);
107374       last = sqlcipher3VdbeCurrentAddr(v);
107375       for(k=pWInfo->iTop; k<last; k++, pOp++){
107376         if( pOp->p1!=pLevel->iTabCur ) continue;
107377         if( pOp->opcode==OP_Column ){
107378           for(j=0; j<pIdx->nColumn; j++){
107379             if( pOp->p2==pIdx->aiColumn[j] ){
107380               pOp->p2 = j;
107381               pOp->p1 = pLevel->iIdxCur;
107382               break;
107383             }
107384           }
107385           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107386                || j<pIdx->nColumn );
107387         }else if( pOp->opcode==OP_Rowid ){
107388           pOp->p1 = pLevel->iIdxCur;
107389           pOp->opcode = OP_IdxRowid;
107390         }
107391       }
107392     }
107393   }
107394
107395   /* Final cleanup
107396   */
107397   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107398   whereInfoFree(db, pWInfo);
107399   return;
107400 }
107401
107402 /************** End of where.c ***********************************************/
107403 /************** Begin file parse.c *******************************************/
107404 /* Driver template for the LEMON parser generator.
107405 ** The author disclaims copyright to this source code.
107406 **
107407 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
107408 ** The only modifications are the addition of a couple of NEVER()
107409 ** macros to disable tests that are needed in the case of a general
107410 ** LALR(1) grammar but which are always false in the
107411 ** specific grammar used by SQLite.
107412 */
107413 /* First off, code is included that follows the "include" declaration
107414 ** in the input grammar file. */
107415 /* #include <stdio.h> */
107416
107417
107418 /*
107419 ** Disable all error recovery processing in the parser push-down
107420 ** automaton.
107421 */
107422 #define YYNOERRORRECOVERY 1
107423
107424 /*
107425 ** Make yytestcase() the same as testcase()
107426 */
107427 #define yytestcase(X) testcase(X)
107428
107429 /*
107430 ** An instance of this structure holds information about the
107431 ** LIMIT clause of a SELECT statement.
107432 */
107433 struct LimitVal {
107434   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
107435   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
107436 };
107437
107438 /*
107439 ** An instance of this structure is used to store the LIKE,
107440 ** GLOB, NOT LIKE, and NOT GLOB operators.
107441 */
107442 struct LikeOp {
107443   Token eOperator;  /* "like" or "glob" or "regexp" */
107444   int not;         /* True if the NOT keyword is present */
107445 };
107446
107447 /*
107448 ** An instance of the following structure describes the event of a
107449 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
107450 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
107451 **
107452 **      UPDATE ON (a,b,c)
107453 **
107454 ** Then the "b" IdList records the list "a,b,c".
107455 */
107456 struct TrigEvent { int a; IdList * b; };
107457
107458 /*
107459 ** An instance of this structure holds the ATTACH key and the key type.
107460 */
107461 struct AttachKey { int type;  Token key; };
107462
107463
107464   /* This is a utility routine used to set the ExprSpan.zStart and
107465   ** ExprSpan.zEnd values of pOut so that the span covers the complete
107466   ** range of text beginning with pStart and going to the end of pEnd.
107467   */
107468   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
107469     pOut->zStart = pStart->z;
107470     pOut->zEnd = &pEnd->z[pEnd->n];
107471   }
107472
107473   /* Construct a new Expr object from a single identifier.  Use the
107474   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
107475   ** that created the expression.
107476   */
107477   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
107478     pOut->pExpr = sqlcipher3PExpr(pParse, op, 0, 0, pValue);
107479     pOut->zStart = pValue->z;
107480     pOut->zEnd = &pValue->z[pValue->n];
107481   }
107482
107483   /* This routine constructs a binary expression node out of two ExprSpan
107484   ** objects and uses the result to populate a new ExprSpan object.
107485   */
107486   static void spanBinaryExpr(
107487     ExprSpan *pOut,     /* Write the result here */
107488     Parse *pParse,      /* The parsing context.  Errors accumulate here */
107489     int op,             /* The binary operation */
107490     ExprSpan *pLeft,    /* The left operand */
107491     ExprSpan *pRight    /* The right operand */
107492   ){
107493     pOut->pExpr = sqlcipher3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
107494     pOut->zStart = pLeft->zStart;
107495     pOut->zEnd = pRight->zEnd;
107496   }
107497
107498   /* Construct an expression node for a unary postfix operator
107499   */
107500   static void spanUnaryPostfix(
107501     ExprSpan *pOut,        /* Write the new expression node here */
107502     Parse *pParse,         /* Parsing context to record errors */
107503     int op,                /* The operator */
107504     ExprSpan *pOperand,    /* The operand */
107505     Token *pPostOp         /* The operand token for setting the span */
107506   ){
107507     pOut->pExpr = sqlcipher3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107508     pOut->zStart = pOperand->zStart;
107509     pOut->zEnd = &pPostOp->z[pPostOp->n];
107510   }                           
107511
107512   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
107513   ** unary TK_ISNULL or TK_NOTNULL expression. */
107514   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
107515     sqlcipher3 *db = pParse->db;
107516     if( db->mallocFailed==0 && pY->op==TK_NULL ){
107517       pA->op = (u8)op;
107518       sqlcipher3ExprDelete(db, pA->pRight);
107519       pA->pRight = 0;
107520     }
107521   }
107522
107523   /* Construct an expression node for a unary prefix operator
107524   */
107525   static void spanUnaryPrefix(
107526     ExprSpan *pOut,        /* Write the new expression node here */
107527     Parse *pParse,         /* Parsing context to record errors */
107528     int op,                /* The operator */
107529     ExprSpan *pOperand,    /* The operand */
107530     Token *pPreOp         /* The operand token for setting the span */
107531   ){
107532     pOut->pExpr = sqlcipher3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107533     pOut->zStart = pPreOp->z;
107534     pOut->zEnd = pOperand->zEnd;
107535   }
107536 /* Next is all token values, in a form suitable for use by makeheaders.
107537 ** This section will be null unless lemon is run with the -m switch.
107538 */
107539 /* 
107540 ** These constants (all generated automatically by the parser generator)
107541 ** specify the various kinds of tokens (terminals) that the parser
107542 ** understands. 
107543 **
107544 ** Each symbol here is a terminal symbol in the grammar.
107545 */
107546 /* Make sure the INTERFACE macro is defined.
107547 */
107548 #ifndef INTERFACE
107549 # define INTERFACE 1
107550 #endif
107551 /* The next thing included is series of defines which control
107552 ** various aspects of the generated parser.
107553 **    YYCODETYPE         is the data type used for storing terminal
107554 **                       and nonterminal numbers.  "unsigned char" is
107555 **                       used if there are fewer than 250 terminals
107556 **                       and nonterminals.  "int" is used otherwise.
107557 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
107558 **                       to no legal terminal or nonterminal number.  This
107559 **                       number is used to fill in empty slots of the hash 
107560 **                       table.
107561 **    YYFALLBACK         If defined, this indicates that one or more tokens
107562 **                       have fall-back values which should be used if the
107563 **                       original value of the token will not parse.
107564 **    YYACTIONTYPE       is the data type used for storing terminal
107565 **                       and nonterminal numbers.  "unsigned char" is
107566 **                       used if there are fewer than 250 rules and
107567 **                       states combined.  "int" is used otherwise.
107568 **    sqlcipher3ParserTOKENTYPE     is the data type used for minor tokens given 
107569 **                       directly to the parser from the tokenizer.
107570 **    YYMINORTYPE        is the data type used for all minor tokens.
107571 **                       This is typically a union of many types, one of
107572 **                       which is sqlcipher3ParserTOKENTYPE.  The entry in the union
107573 **                       for base tokens is called "yy0".
107574 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
107575 **                       zero the stack is dynamically sized using realloc()
107576 **    sqlcipher3ParserARG_SDECL     A static variable declaration for the %extra_argument
107577 **    sqlcipher3ParserARG_PDECL     A parameter declaration for the %extra_argument
107578 **    sqlcipher3ParserARG_STORE     Code to store %extra_argument into yypParser
107579 **    sqlcipher3ParserARG_FETCH     Code to extract %extra_argument from yypParser
107580 **    YYNSTATE           the combined number of states.
107581 **    YYNRULE            the number of rules in the grammar
107582 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
107583 **                       defined, then do no error processing.
107584 */
107585 #define YYCODETYPE unsigned char
107586 #define YYNOCODE 253
107587 #define YYACTIONTYPE unsigned short int
107588 #define YYWILDCARD 67
107589 #define sqlcipher3ParserTOKENTYPE Token
107590 typedef union {
107591   int yyinit;
107592   sqlcipher3ParserTOKENTYPE yy0;
107593   int yy4;
107594   struct TrigEvent yy90;
107595   ExprSpan yy118;
107596   TriggerStep* yy203;
107597   u8 yy210;
107598   struct {int value; int mask;} yy215;
107599   SrcList* yy259;
107600   struct LimitVal yy292;
107601   Expr* yy314;
107602   ExprList* yy322;
107603   struct LikeOp yy342;
107604   IdList* yy384;
107605   Select* yy387;
107606 } YYMINORTYPE;
107607 #ifndef YYSTACKDEPTH
107608 #define YYSTACKDEPTH 100
107609 #endif
107610 #define sqlcipher3ParserARG_SDECL Parse *pParse;
107611 #define sqlcipher3ParserARG_PDECL ,Parse *pParse
107612 #define sqlcipher3ParserARG_FETCH Parse *pParse = yypParser->pParse
107613 #define sqlcipher3ParserARG_STORE yypParser->pParse = pParse
107614 #define YYNSTATE 630
107615 #define YYNRULE 329
107616 #define YYFALLBACK 1
107617 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
107618 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
107619 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
107620
107621 /* The yyzerominor constant is used to initialize instances of
107622 ** YYMINORTYPE objects to zero. */
107623 static const YYMINORTYPE yyzerominor = { 0 };
107624
107625 /* Define the yytestcase() macro to be a no-op if is not already defined
107626 ** otherwise.
107627 **
107628 ** Applications can choose to define yytestcase() in the %include section
107629 ** to a macro that can assist in verifying code coverage.  For production
107630 ** code the yytestcase() macro should be turned off.  But it is useful
107631 ** for testing.
107632 */
107633 #ifndef yytestcase
107634 # define yytestcase(X)
107635 #endif
107636
107637
107638 /* Next are the tables used to determine what action to take based on the
107639 ** current state and lookahead token.  These tables are used to implement
107640 ** functions that take a state number and lookahead value and return an
107641 ** action integer.  
107642 **
107643 ** Suppose the action integer is N.  Then the action is determined as
107644 ** follows
107645 **
107646 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
107647 **                                      token onto the stack and goto state N.
107648 **
107649 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
107650 **
107651 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
107652 **
107653 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
107654 **
107655 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
107656 **                                      slots in the yy_action[] table.
107657 **
107658 ** The action table is constructed as a single large table named yy_action[].
107659 ** Given state S and lookahead X, the action is computed as
107660 **
107661 **      yy_action[ yy_shift_ofst[S] + X ]
107662 **
107663 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
107664 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
107665 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
107666 ** and that yy_default[S] should be used instead.  
107667 **
107668 ** The formula above is for computing the action when the lookahead is
107669 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
107670 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
107671 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
107672 ** YY_SHIFT_USE_DFLT.
107673 **
107674 ** The following are the tables generated in this section:
107675 **
107676 **  yy_action[]        A single table containing all actions.
107677 **  yy_lookahead[]     A table containing the lookahead for each entry in
107678 **                     yy_action.  Used to detect hash collisions.
107679 **  yy_shift_ofst[]    For each state, the offset into yy_action for
107680 **                     shifting terminals.
107681 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
107682 **                     shifting non-terminals after a reduce.
107683 **  yy_default[]       Default action for each state.
107684 */
107685 #define YY_ACTTAB_COUNT (1557)
107686 static const YYACTIONTYPE yy_action[] = {
107687  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
107688  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
107689  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
107690  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
107691  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
107692  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
107693  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
107694  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
107695  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107696  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
107697  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
107698  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
107699  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
107700  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
107701  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
107702  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
107703  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
107704  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
107705  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
107706  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
107707  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
107708  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107709  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
107710  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
107711  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
107712  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
107713  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
107714  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
107715  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
107716  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
107717  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
107718  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
107719  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
107720  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
107721  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
107722  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
107723  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
107724  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
107725  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
107726  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
107727  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
107728  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
107729  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
107730  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
107731  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
107732  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
107733  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
107734  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
107735  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
107736  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
107737  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
107738  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
107739  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
107740  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
107741  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
107742  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
107743  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
107744  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
107745  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107746  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
107747  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
107748  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
107749  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
107750  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
107751  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
107752  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
107753  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
107754  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
107755  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
107756  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
107757  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
107758  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
107759  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
107760  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
107761  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
107762  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
107763  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
107764  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
107765  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
107766  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
107767  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
107768  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
107769  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
107770  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
107771  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
107772  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
107773  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
107774  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
107775  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
107776  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
107777  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
107778  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
107779  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
107780  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
107781  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
107782  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
107783  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
107784  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
107785  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
107786  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
107787  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
107788  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
107789  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
107790  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
107791  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
107792  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
107793  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
107794  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
107795  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
107796  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
107797  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
107798  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
107799  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
107800  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
107801  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
107802  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
107803  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
107804  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
107805  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
107806  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
107807  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
107808  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
107809  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
107810  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
107811  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
107812  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
107813  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
107814  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
107815  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
107816  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
107817  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
107818  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
107819  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
107820  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
107821  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
107822  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
107823  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
107824  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
107825  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
107826  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
107827  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
107828  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
107829  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
107830  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
107831  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
107832  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
107833  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
107834  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
107835  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
107836  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
107837  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
107838  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
107839  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
107840  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
107841  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
107842  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
107843 };
107844 static const YYCODETYPE yy_lookahead[] = {
107845  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
107846  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
107847  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
107848  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
107849  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
107850  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107851  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
107852  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
107853  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107854  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
107855  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
107856  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
107857  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
107858  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
107859  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
107860  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
107861  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
107862  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
107863  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
107864  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
107865  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107866  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107867  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
107868  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
107869  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
107870  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
107871  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
107872  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107873  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
107874  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
107875  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
107876  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
107877  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
107878  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
107879  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
107880  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
107881  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107882  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
107883  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
107884  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
107885  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
107886  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
107887  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107888  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
107889  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
107890  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
107891  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
107892  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
107893  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
107894  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
107895  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
107896  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
107897  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
107898  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
107899  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
107900  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
107901  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
107902  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107903  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107904  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
107905  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
107906  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
107907  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
107908  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
107909  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
107910  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
107911  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
107912  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
107913  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
107914  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
107915  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
107916  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
107917  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
107918  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107919  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
107920  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
107921  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
107922  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
107923  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
107924  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
107925  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
107926  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
107927  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
107928  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
107929  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
107930  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
107931  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
107932  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
107933  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
107934  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
107935  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
107936  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
107937  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
107938  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
107939  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
107940  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
107941  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
107942  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
107943  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
107944  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
107945  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
107946  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
107947  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
107948  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
107949  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
107950  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
107951  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
107952  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
107953  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
107954  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
107955  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
107956  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
107957  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
107958  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
107959  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
107960  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
107961  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
107962  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
107963  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
107964  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
107965  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
107966  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
107967  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
107968  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
107969  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
107970  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
107971  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
107972  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
107973  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
107974  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
107975  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
107976  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
107977  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
107978  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
107979  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
107980  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
107981  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
107982  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
107983  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
107984  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
107985  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
107986  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
107987  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
107988  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
107989  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
107990  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
107991  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
107992  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
107993  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
107994  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
107995  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
107996  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
107997  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
107998  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
107999  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
108000  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
108001 };
108002 #define YY_SHIFT_USE_DFLT (-74)
108003 #define YY_SHIFT_COUNT (418)
108004 #define YY_SHIFT_MIN   (-73)
108005 #define YY_SHIFT_MAX   (1468)
108006 static const short yy_shift_ofst[] = {
108007  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
108008  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
108009  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
108010  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
108011  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
108012  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
108013  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
108014  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
108015  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
108016  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
108017  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
108018  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
108019  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
108020  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
108021  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
108022  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
108023  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
108024  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
108025  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
108026  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
108027  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
108028  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
108029  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
108030  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
108031  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
108032  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
108033  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
108034  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
108035  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
108036  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
108037  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
108038  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
108039  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
108040  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
108041  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
108042  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
108043  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
108044  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
108045  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
108046  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
108047  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
108048  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
108049 };
108050 #define YY_REDUCE_USE_DFLT (-142)
108051 #define YY_REDUCE_COUNT (312)
108052 #define YY_REDUCE_MIN   (-141)
108053 #define YY_REDUCE_MAX   (1369)
108054 static const short yy_reduce_ofst[] = {
108055  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
108056  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
108057  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
108058  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
108059  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
108060  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
108061  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
108062  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
108063  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
108064  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
108065  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
108066  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
108067  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
108068  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
108069  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
108070  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
108071  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
108072  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
108073  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
108074  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
108075  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
108076  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
108077  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
108078  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
108079  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
108080  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
108081  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
108082  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
108083  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
108084  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
108085  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
108086  /*   310 */  1031, 1023, 1030,
108087 };
108088 static const YYACTIONTYPE yy_default[] = {
108089  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
108090  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
108091  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108092  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108093  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108094  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108095  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
108096  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
108097  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
108098  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
108099  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
108100  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108101  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
108102  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
108103  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108104  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
108105  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108106  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108107  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
108108  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
108109  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
108110  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
108111  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
108112  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
108113  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
108114  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
108115  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
108116  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
108117  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
108118  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
108119  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
108120  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
108121  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108122  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
108123  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108124  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
108125  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
108126  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108127  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
108128  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
108129  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
108130  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
108131  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
108132  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
108133  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
108134  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
108135  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
108136  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
108137  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
108138  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
108139  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
108140  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
108141  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
108142  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
108143  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
108144  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
108145  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
108146  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
108147  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
108148  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
108149  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
108150  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
108151  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
108152 };
108153
108154 /* The next table maps tokens into fallback tokens.  If a construct
108155 ** like the following:
108156 ** 
108157 **      %fallback ID X Y Z.
108158 **
108159 ** appears in the grammar, then ID becomes a fallback token for X, Y,
108160 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
108161 ** but it does not parse, the type of the token is changed to ID and
108162 ** the parse is retried before an error is thrown.
108163 */
108164 #ifdef YYFALLBACK
108165 static const YYCODETYPE yyFallback[] = {
108166     0,  /*          $ => nothing */
108167     0,  /*       SEMI => nothing */
108168    26,  /*    EXPLAIN => ID */
108169    26,  /*      QUERY => ID */
108170    26,  /*       PLAN => ID */
108171    26,  /*      BEGIN => ID */
108172     0,  /* TRANSACTION => nothing */
108173    26,  /*   DEFERRED => ID */
108174    26,  /*  IMMEDIATE => ID */
108175    26,  /*  EXCLUSIVE => ID */
108176     0,  /*     COMMIT => nothing */
108177    26,  /*        END => ID */
108178    26,  /*   ROLLBACK => ID */
108179    26,  /*  SAVEPOINT => ID */
108180    26,  /*    RELEASE => ID */
108181     0,  /*         TO => nothing */
108182     0,  /*      TABLE => nothing */
108183     0,  /*     CREATE => nothing */
108184    26,  /*         IF => ID */
108185     0,  /*        NOT => nothing */
108186     0,  /*     EXISTS => nothing */
108187    26,  /*       TEMP => ID */
108188     0,  /*         LP => nothing */
108189     0,  /*         RP => nothing */
108190     0,  /*         AS => nothing */
108191     0,  /*      COMMA => nothing */
108192     0,  /*         ID => nothing */
108193     0,  /*    INDEXED => nothing */
108194    26,  /*      ABORT => ID */
108195    26,  /*     ACTION => ID */
108196    26,  /*      AFTER => ID */
108197    26,  /*    ANALYZE => ID */
108198    26,  /*        ASC => ID */
108199    26,  /*     ATTACH => ID */
108200    26,  /*     BEFORE => ID */
108201    26,  /*         BY => ID */
108202    26,  /*    CASCADE => ID */
108203    26,  /*       CAST => ID */
108204    26,  /*   COLUMNKW => ID */
108205    26,  /*   CONFLICT => ID */
108206    26,  /*   DATABASE => ID */
108207    26,  /*       DESC => ID */
108208    26,  /*     DETACH => ID */
108209    26,  /*       EACH => ID */
108210    26,  /*       FAIL => ID */
108211    26,  /*        FOR => ID */
108212    26,  /*     IGNORE => ID */
108213    26,  /*  INITIALLY => ID */
108214    26,  /*    INSTEAD => ID */
108215    26,  /*    LIKE_KW => ID */
108216    26,  /*      MATCH => ID */
108217    26,  /*         NO => ID */
108218    26,  /*        KEY => ID */
108219    26,  /*         OF => ID */
108220    26,  /*     OFFSET => ID */
108221    26,  /*     PRAGMA => ID */
108222    26,  /*      RAISE => ID */
108223    26,  /*    REPLACE => ID */
108224    26,  /*   RESTRICT => ID */
108225    26,  /*        ROW => ID */
108226    26,  /*    TRIGGER => ID */
108227    26,  /*     VACUUM => ID */
108228    26,  /*       VIEW => ID */
108229    26,  /*    VIRTUAL => ID */
108230    26,  /*    REINDEX => ID */
108231    26,  /*     RENAME => ID */
108232    26,  /*   CTIME_KW => ID */
108233 };
108234 #endif /* YYFALLBACK */
108235
108236 /* The following structure represents a single element of the
108237 ** parser's stack.  Information stored includes:
108238 **
108239 **   +  The state number for the parser at this level of the stack.
108240 **
108241 **   +  The value of the token stored at this level of the stack.
108242 **      (In other words, the "major" token.)
108243 **
108244 **   +  The semantic value stored at this level of the stack.  This is
108245 **      the information used by the action routines in the grammar.
108246 **      It is sometimes called the "minor" token.
108247 */
108248 struct yyStackEntry {
108249   YYACTIONTYPE stateno;  /* The state-number */
108250   YYCODETYPE major;      /* The major token value.  This is the code
108251                          ** number for the token at this stack level */
108252   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
108253                          ** is the value of the token  */
108254 };
108255 typedef struct yyStackEntry yyStackEntry;
108256
108257 /* The state of the parser is completely contained in an instance of
108258 ** the following structure */
108259 struct yyParser {
108260   int yyidx;                    /* Index of top element in stack */
108261 #ifdef YYTRACKMAXSTACKDEPTH
108262   int yyidxMax;                 /* Maximum value of yyidx */
108263 #endif
108264   int yyerrcnt;                 /* Shifts left before out of the error */
108265   sqlcipher3ParserARG_SDECL                /* A place to hold %extra_argument */
108266 #if YYSTACKDEPTH<=0
108267   int yystksz;                  /* Current side of the stack */
108268   yyStackEntry *yystack;        /* The parser's stack */
108269 #else
108270   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
108271 #endif
108272 };
108273 typedef struct yyParser yyParser;
108274
108275 #ifndef NDEBUG
108276 /* #include <stdio.h> */
108277 static FILE *yyTraceFILE = 0;
108278 static char *yyTracePrompt = 0;
108279 #endif /* NDEBUG */
108280
108281 #ifndef NDEBUG
108282 /* 
108283 ** Turn parser tracing on by giving a stream to which to write the trace
108284 ** and a prompt to preface each trace message.  Tracing is turned off
108285 ** by making either argument NULL 
108286 **
108287 ** Inputs:
108288 ** <ul>
108289 ** <li> A FILE* to which trace output should be written.
108290 **      If NULL, then tracing is turned off.
108291 ** <li> A prefix string written at the beginning of every
108292 **      line of trace output.  If NULL, then tracing is
108293 **      turned off.
108294 ** </ul>
108295 **
108296 ** Outputs:
108297 ** None.
108298 */
108299 SQLCIPHER_PRIVATE void sqlcipher3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
108300   yyTraceFILE = TraceFILE;
108301   yyTracePrompt = zTracePrompt;
108302   if( yyTraceFILE==0 ) yyTracePrompt = 0;
108303   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
108304 }
108305 #endif /* NDEBUG */
108306
108307 #ifndef NDEBUG
108308 /* For tracing shifts, the names of all terminals and nonterminals
108309 ** are required.  The following table supplies these names */
108310 static const char *const yyTokenName[] = { 
108311   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
108312   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
108313   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
108314   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
108315   "TABLE",         "CREATE",        "IF",            "NOT",         
108316   "EXISTS",        "TEMP",          "LP",            "RP",          
108317   "AS",            "COMMA",         "ID",            "INDEXED",     
108318   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
108319   "ASC",           "ATTACH",        "BEFORE",        "BY",          
108320   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
108321   "DATABASE",      "DESC",          "DETACH",        "EACH",        
108322   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
108323   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
108324   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
108325   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
108326   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
108327   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
108328   "OR",            "AND",           "IS",            "BETWEEN",     
108329   "IN",            "ISNULL",        "NOTNULL",       "NE",          
108330   "EQ",            "GT",            "LE",            "LT",          
108331   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
108332   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
108333   "STAR",          "SLASH",         "REM",           "CONCAT",      
108334   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
108335   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
108336   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
108337   "ON",            "INSERT",        "DELETE",        "UPDATE",      
108338   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
108339   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
108340   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
108341   "JOIN",          "USING",         "ORDER",         "GROUP",       
108342   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
108343   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
108344   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
108345   "THEN",          "ELSE",          "INDEX",         "ALTER",       
108346   "ADD",           "error",         "input",         "cmdlist",     
108347   "ecmd",          "explain",       "cmdx",          "cmd",         
108348   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
108349   "create_table",  "create_table_args",  "createkw",      "temp",        
108350   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
108351   "select",        "column",        "columnid",      "type",        
108352   "carglist",      "id",            "ids",           "typetoken",   
108353   "typename",      "signed",        "plus_num",      "minus_num",   
108354   "carg",          "ccons",         "term",          "expr",        
108355   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
108356   "refargs",       "defer_subclause",  "refarg",        "refact",      
108357   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
108358   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
108359   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
108360   "distinct",      "selcollist",    "from",          "where_opt",   
108361   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
108362   "sclp",          "as",            "seltablist",    "stl_prefix",  
108363   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
108364   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
108365   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
108366   "itemlist",      "exprlist",      "likeop",        "between_op",  
108367   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
108368   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
108369   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
108370   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
108371   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
108372   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
108373   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
108374 };
108375 #endif /* NDEBUG */
108376
108377 #ifndef NDEBUG
108378 /* For tracing reduce actions, the names of all rules are required.
108379 */
108380 static const char *const yyRuleName[] = {
108381  /*   0 */ "input ::= cmdlist",
108382  /*   1 */ "cmdlist ::= cmdlist ecmd",
108383  /*   2 */ "cmdlist ::= ecmd",
108384  /*   3 */ "ecmd ::= SEMI",
108385  /*   4 */ "ecmd ::= explain cmdx SEMI",
108386  /*   5 */ "explain ::=",
108387  /*   6 */ "explain ::= EXPLAIN",
108388  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
108389  /*   8 */ "cmdx ::= cmd",
108390  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
108391  /*  10 */ "trans_opt ::=",
108392  /*  11 */ "trans_opt ::= TRANSACTION",
108393  /*  12 */ "trans_opt ::= TRANSACTION nm",
108394  /*  13 */ "transtype ::=",
108395  /*  14 */ "transtype ::= DEFERRED",
108396  /*  15 */ "transtype ::= IMMEDIATE",
108397  /*  16 */ "transtype ::= EXCLUSIVE",
108398  /*  17 */ "cmd ::= COMMIT trans_opt",
108399  /*  18 */ "cmd ::= END trans_opt",
108400  /*  19 */ "cmd ::= ROLLBACK trans_opt",
108401  /*  20 */ "savepoint_opt ::= SAVEPOINT",
108402  /*  21 */ "savepoint_opt ::=",
108403  /*  22 */ "cmd ::= SAVEPOINT nm",
108404  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
108405  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
108406  /*  25 */ "cmd ::= create_table create_table_args",
108407  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
108408  /*  27 */ "createkw ::= CREATE",
108409  /*  28 */ "ifnotexists ::=",
108410  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
108411  /*  30 */ "temp ::= TEMP",
108412  /*  31 */ "temp ::=",
108413  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
108414  /*  33 */ "create_table_args ::= AS select",
108415  /*  34 */ "columnlist ::= columnlist COMMA column",
108416  /*  35 */ "columnlist ::= column",
108417  /*  36 */ "column ::= columnid type carglist",
108418  /*  37 */ "columnid ::= nm",
108419  /*  38 */ "id ::= ID",
108420  /*  39 */ "id ::= INDEXED",
108421  /*  40 */ "ids ::= ID|STRING",
108422  /*  41 */ "nm ::= id",
108423  /*  42 */ "nm ::= STRING",
108424  /*  43 */ "nm ::= JOIN_KW",
108425  /*  44 */ "type ::=",
108426  /*  45 */ "type ::= typetoken",
108427  /*  46 */ "typetoken ::= typename",
108428  /*  47 */ "typetoken ::= typename LP signed RP",
108429  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
108430  /*  49 */ "typename ::= ids",
108431  /*  50 */ "typename ::= typename ids",
108432  /*  51 */ "signed ::= plus_num",
108433  /*  52 */ "signed ::= minus_num",
108434  /*  53 */ "carglist ::= carglist carg",
108435  /*  54 */ "carglist ::=",
108436  /*  55 */ "carg ::= CONSTRAINT nm ccons",
108437  /*  56 */ "carg ::= ccons",
108438  /*  57 */ "ccons ::= DEFAULT term",
108439  /*  58 */ "ccons ::= DEFAULT LP expr RP",
108440  /*  59 */ "ccons ::= DEFAULT PLUS term",
108441  /*  60 */ "ccons ::= DEFAULT MINUS term",
108442  /*  61 */ "ccons ::= DEFAULT id",
108443  /*  62 */ "ccons ::= NULL onconf",
108444  /*  63 */ "ccons ::= NOT NULL onconf",
108445  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
108446  /*  65 */ "ccons ::= UNIQUE onconf",
108447  /*  66 */ "ccons ::= CHECK LP expr RP",
108448  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
108449  /*  68 */ "ccons ::= defer_subclause",
108450  /*  69 */ "ccons ::= COLLATE ids",
108451  /*  70 */ "autoinc ::=",
108452  /*  71 */ "autoinc ::= AUTOINCR",
108453  /*  72 */ "refargs ::=",
108454  /*  73 */ "refargs ::= refargs refarg",
108455  /*  74 */ "refarg ::= MATCH nm",
108456  /*  75 */ "refarg ::= ON INSERT refact",
108457  /*  76 */ "refarg ::= ON DELETE refact",
108458  /*  77 */ "refarg ::= ON UPDATE refact",
108459  /*  78 */ "refact ::= SET NULL",
108460  /*  79 */ "refact ::= SET DEFAULT",
108461  /*  80 */ "refact ::= CASCADE",
108462  /*  81 */ "refact ::= RESTRICT",
108463  /*  82 */ "refact ::= NO ACTION",
108464  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
108465  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
108466  /*  85 */ "init_deferred_pred_opt ::=",
108467  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
108468  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
108469  /*  88 */ "conslist_opt ::=",
108470  /*  89 */ "conslist_opt ::= COMMA conslist",
108471  /*  90 */ "conslist ::= conslist COMMA tcons",
108472  /*  91 */ "conslist ::= conslist tcons",
108473  /*  92 */ "conslist ::= tcons",
108474  /*  93 */ "tcons ::= CONSTRAINT nm",
108475  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
108476  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
108477  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
108478  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
108479  /*  98 */ "defer_subclause_opt ::=",
108480  /*  99 */ "defer_subclause_opt ::= defer_subclause",
108481  /* 100 */ "onconf ::=",
108482  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
108483  /* 102 */ "orconf ::=",
108484  /* 103 */ "orconf ::= OR resolvetype",
108485  /* 104 */ "resolvetype ::= raisetype",
108486  /* 105 */ "resolvetype ::= IGNORE",
108487  /* 106 */ "resolvetype ::= REPLACE",
108488  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
108489  /* 108 */ "ifexists ::= IF EXISTS",
108490  /* 109 */ "ifexists ::=",
108491  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
108492  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
108493  /* 112 */ "cmd ::= select",
108494  /* 113 */ "select ::= oneselect",
108495  /* 114 */ "select ::= select multiselect_op oneselect",
108496  /* 115 */ "multiselect_op ::= UNION",
108497  /* 116 */ "multiselect_op ::= UNION ALL",
108498  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
108499  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
108500  /* 119 */ "distinct ::= DISTINCT",
108501  /* 120 */ "distinct ::= ALL",
108502  /* 121 */ "distinct ::=",
108503  /* 122 */ "sclp ::= selcollist COMMA",
108504  /* 123 */ "sclp ::=",
108505  /* 124 */ "selcollist ::= sclp expr as",
108506  /* 125 */ "selcollist ::= sclp STAR",
108507  /* 126 */ "selcollist ::= sclp nm DOT STAR",
108508  /* 127 */ "as ::= AS nm",
108509  /* 128 */ "as ::= ids",
108510  /* 129 */ "as ::=",
108511  /* 130 */ "from ::=",
108512  /* 131 */ "from ::= FROM seltablist",
108513  /* 132 */ "stl_prefix ::= seltablist joinop",
108514  /* 133 */ "stl_prefix ::=",
108515  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
108516  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
108517  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
108518  /* 137 */ "dbnm ::=",
108519  /* 138 */ "dbnm ::= DOT nm",
108520  /* 139 */ "fullname ::= nm dbnm",
108521  /* 140 */ "joinop ::= COMMA|JOIN",
108522  /* 141 */ "joinop ::= JOIN_KW JOIN",
108523  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
108524  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
108525  /* 144 */ "on_opt ::= ON expr",
108526  /* 145 */ "on_opt ::=",
108527  /* 146 */ "indexed_opt ::=",
108528  /* 147 */ "indexed_opt ::= INDEXED BY nm",
108529  /* 148 */ "indexed_opt ::= NOT INDEXED",
108530  /* 149 */ "using_opt ::= USING LP inscollist RP",
108531  /* 150 */ "using_opt ::=",
108532  /* 151 */ "orderby_opt ::=",
108533  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
108534  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
108535  /* 154 */ "sortlist ::= sortitem sortorder",
108536  /* 155 */ "sortitem ::= expr",
108537  /* 156 */ "sortorder ::= ASC",
108538  /* 157 */ "sortorder ::= DESC",
108539  /* 158 */ "sortorder ::=",
108540  /* 159 */ "groupby_opt ::=",
108541  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
108542  /* 161 */ "having_opt ::=",
108543  /* 162 */ "having_opt ::= HAVING expr",
108544  /* 163 */ "limit_opt ::=",
108545  /* 164 */ "limit_opt ::= LIMIT expr",
108546  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
108547  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
108548  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
108549  /* 168 */ "where_opt ::=",
108550  /* 169 */ "where_opt ::= WHERE expr",
108551  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
108552  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
108553  /* 172 */ "setlist ::= nm EQ expr",
108554  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
108555  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
108556  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
108557  /* 176 */ "insert_cmd ::= INSERT orconf",
108558  /* 177 */ "insert_cmd ::= REPLACE",
108559  /* 178 */ "itemlist ::= itemlist COMMA expr",
108560  /* 179 */ "itemlist ::= expr",
108561  /* 180 */ "inscollist_opt ::=",
108562  /* 181 */ "inscollist_opt ::= LP inscollist RP",
108563  /* 182 */ "inscollist ::= inscollist COMMA nm",
108564  /* 183 */ "inscollist ::= nm",
108565  /* 184 */ "expr ::= term",
108566  /* 185 */ "expr ::= LP expr RP",
108567  /* 186 */ "term ::= NULL",
108568  /* 187 */ "expr ::= id",
108569  /* 188 */ "expr ::= JOIN_KW",
108570  /* 189 */ "expr ::= nm DOT nm",
108571  /* 190 */ "expr ::= nm DOT nm DOT nm",
108572  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
108573  /* 192 */ "term ::= STRING",
108574  /* 193 */ "expr ::= REGISTER",
108575  /* 194 */ "expr ::= VARIABLE",
108576  /* 195 */ "expr ::= expr COLLATE ids",
108577  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
108578  /* 197 */ "expr ::= ID LP distinct exprlist RP",
108579  /* 198 */ "expr ::= ID LP STAR RP",
108580  /* 199 */ "term ::= CTIME_KW",
108581  /* 200 */ "expr ::= expr AND expr",
108582  /* 201 */ "expr ::= expr OR expr",
108583  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
108584  /* 203 */ "expr ::= expr EQ|NE expr",
108585  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
108586  /* 205 */ "expr ::= expr PLUS|MINUS expr",
108587  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
108588  /* 207 */ "expr ::= expr CONCAT expr",
108589  /* 208 */ "likeop ::= LIKE_KW",
108590  /* 209 */ "likeop ::= NOT LIKE_KW",
108591  /* 210 */ "likeop ::= MATCH",
108592  /* 211 */ "likeop ::= NOT MATCH",
108593  /* 212 */ "expr ::= expr likeop expr",
108594  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
108595  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
108596  /* 215 */ "expr ::= expr NOT NULL",
108597  /* 216 */ "expr ::= expr IS expr",
108598  /* 217 */ "expr ::= expr IS NOT expr",
108599  /* 218 */ "expr ::= NOT expr",
108600  /* 219 */ "expr ::= BITNOT expr",
108601  /* 220 */ "expr ::= MINUS expr",
108602  /* 221 */ "expr ::= PLUS expr",
108603  /* 222 */ "between_op ::= BETWEEN",
108604  /* 223 */ "between_op ::= NOT BETWEEN",
108605  /* 224 */ "expr ::= expr between_op expr AND expr",
108606  /* 225 */ "in_op ::= IN",
108607  /* 226 */ "in_op ::= NOT IN",
108608  /* 227 */ "expr ::= expr in_op LP exprlist RP",
108609  /* 228 */ "expr ::= LP select RP",
108610  /* 229 */ "expr ::= expr in_op LP select RP",
108611  /* 230 */ "expr ::= expr in_op nm dbnm",
108612  /* 231 */ "expr ::= EXISTS LP select RP",
108613  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
108614  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
108615  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
108616  /* 235 */ "case_else ::= ELSE expr",
108617  /* 236 */ "case_else ::=",
108618  /* 237 */ "case_operand ::= expr",
108619  /* 238 */ "case_operand ::=",
108620  /* 239 */ "exprlist ::= nexprlist",
108621  /* 240 */ "exprlist ::=",
108622  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
108623  /* 242 */ "nexprlist ::= expr",
108624  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
108625  /* 244 */ "uniqueflag ::= UNIQUE",
108626  /* 245 */ "uniqueflag ::=",
108627  /* 246 */ "idxlist_opt ::=",
108628  /* 247 */ "idxlist_opt ::= LP idxlist RP",
108629  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
108630  /* 249 */ "idxlist ::= nm collate sortorder",
108631  /* 250 */ "collate ::=",
108632  /* 251 */ "collate ::= COLLATE ids",
108633  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
108634  /* 253 */ "cmd ::= VACUUM",
108635  /* 254 */ "cmd ::= VACUUM nm",
108636  /* 255 */ "cmd ::= PRAGMA nm dbnm",
108637  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
108638  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
108639  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
108640  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
108641  /* 260 */ "nmnum ::= plus_num",
108642  /* 261 */ "nmnum ::= nm",
108643  /* 262 */ "nmnum ::= ON",
108644  /* 263 */ "nmnum ::= DELETE",
108645  /* 264 */ "nmnum ::= DEFAULT",
108646  /* 265 */ "plus_num ::= plus_opt number",
108647  /* 266 */ "minus_num ::= MINUS number",
108648  /* 267 */ "number ::= INTEGER|FLOAT",
108649  /* 268 */ "plus_opt ::= PLUS",
108650  /* 269 */ "plus_opt ::=",
108651  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
108652  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
108653  /* 272 */ "trigger_time ::= BEFORE",
108654  /* 273 */ "trigger_time ::= AFTER",
108655  /* 274 */ "trigger_time ::= INSTEAD OF",
108656  /* 275 */ "trigger_time ::=",
108657  /* 276 */ "trigger_event ::= DELETE|INSERT",
108658  /* 277 */ "trigger_event ::= UPDATE",
108659  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
108660  /* 279 */ "foreach_clause ::=",
108661  /* 280 */ "foreach_clause ::= FOR EACH ROW",
108662  /* 281 */ "when_clause ::=",
108663  /* 282 */ "when_clause ::= WHEN expr",
108664  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
108665  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
108666  /* 285 */ "trnm ::= nm",
108667  /* 286 */ "trnm ::= nm DOT nm",
108668  /* 287 */ "tridxby ::=",
108669  /* 288 */ "tridxby ::= INDEXED BY nm",
108670  /* 289 */ "tridxby ::= NOT INDEXED",
108671  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
108672  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
108673  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
108674  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
108675  /* 294 */ "trigger_cmd ::= select",
108676  /* 295 */ "expr ::= RAISE LP IGNORE RP",
108677  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
108678  /* 297 */ "raisetype ::= ROLLBACK",
108679  /* 298 */ "raisetype ::= ABORT",
108680  /* 299 */ "raisetype ::= FAIL",
108681  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
108682  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
108683  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
108684  /* 303 */ "key_opt ::=",
108685  /* 304 */ "key_opt ::= KEY expr",
108686  /* 305 */ "database_kw_opt ::= DATABASE",
108687  /* 306 */ "database_kw_opt ::=",
108688  /* 307 */ "cmd ::= REINDEX",
108689  /* 308 */ "cmd ::= REINDEX nm dbnm",
108690  /* 309 */ "cmd ::= ANALYZE",
108691  /* 310 */ "cmd ::= ANALYZE nm dbnm",
108692  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
108693  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
108694  /* 313 */ "add_column_fullname ::= fullname",
108695  /* 314 */ "kwcolumn_opt ::=",
108696  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
108697  /* 316 */ "cmd ::= create_vtab",
108698  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
108699  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
108700  /* 319 */ "vtabarglist ::= vtabarg",
108701  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
108702  /* 321 */ "vtabarg ::=",
108703  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
108704  /* 323 */ "vtabargtoken ::= ANY",
108705  /* 324 */ "vtabargtoken ::= lp anylist RP",
108706  /* 325 */ "lp ::= LP",
108707  /* 326 */ "anylist ::=",
108708  /* 327 */ "anylist ::= anylist LP anylist RP",
108709  /* 328 */ "anylist ::= anylist ANY",
108710 };
108711 #endif /* NDEBUG */
108712
108713
108714 #if YYSTACKDEPTH<=0
108715 /*
108716 ** Try to increase the size of the parser stack.
108717 */
108718 static void yyGrowStack(yyParser *p){
108719   int newSize;
108720   yyStackEntry *pNew;
108721
108722   newSize = p->yystksz*2 + 100;
108723   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
108724   if( pNew ){
108725     p->yystack = pNew;
108726     p->yystksz = newSize;
108727 #ifndef NDEBUG
108728     if( yyTraceFILE ){
108729       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
108730               yyTracePrompt, p->yystksz);
108731     }
108732 #endif
108733   }
108734 }
108735 #endif
108736
108737 /* 
108738 ** This function allocates a new parser.
108739 ** The only argument is a pointer to a function which works like
108740 ** malloc.
108741 **
108742 ** Inputs:
108743 ** A pointer to the function used to allocate memory.
108744 **
108745 ** Outputs:
108746 ** A pointer to a parser.  This pointer is used in subsequent calls
108747 ** to sqlcipher3Parser and sqlcipher3ParserFree.
108748 */
108749 SQLCIPHER_PRIVATE void *sqlcipher3ParserAlloc(void *(*mallocProc)(size_t)){
108750   yyParser *pParser;
108751   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
108752   if( pParser ){
108753     pParser->yyidx = -1;
108754 #ifdef YYTRACKMAXSTACKDEPTH
108755     pParser->yyidxMax = 0;
108756 #endif
108757 #if YYSTACKDEPTH<=0
108758     pParser->yystack = NULL;
108759     pParser->yystksz = 0;
108760     yyGrowStack(pParser);
108761 #endif
108762   }
108763   return pParser;
108764 }
108765
108766 /* The following function deletes the value associated with a
108767 ** symbol.  The symbol can be either a terminal or nonterminal.
108768 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
108769 ** the value.
108770 */
108771 static void yy_destructor(
108772   yyParser *yypParser,    /* The parser */
108773   YYCODETYPE yymajor,     /* Type code for object to destroy */
108774   YYMINORTYPE *yypminor   /* The object to be destroyed */
108775 ){
108776   sqlcipher3ParserARG_FETCH;
108777   switch( yymajor ){
108778     /* Here is inserted the actions which take place when a
108779     ** terminal or non-terminal is destroyed.  This can happen
108780     ** when the symbol is popped from the stack during a
108781     ** reduce or during error processing or when a parser is 
108782     ** being destroyed before it is finished parsing.
108783     **
108784     ** Note: during a reduce, the only symbols destroyed are those
108785     ** which appear on the RHS of the rule, but which are not used
108786     ** inside the C code.
108787     */
108788     case 160: /* select */
108789     case 194: /* oneselect */
108790 {
108791 sqlcipher3SelectDelete(pParse->db, (yypminor->yy387));
108792 }
108793       break;
108794     case 174: /* term */
108795     case 175: /* expr */
108796 {
108797 sqlcipher3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
108798 }
108799       break;
108800     case 179: /* idxlist_opt */
108801     case 187: /* idxlist */
108802     case 197: /* selcollist */
108803     case 200: /* groupby_opt */
108804     case 202: /* orderby_opt */
108805     case 204: /* sclp */
108806     case 214: /* sortlist */
108807     case 216: /* nexprlist */
108808     case 217: /* setlist */
108809     case 220: /* itemlist */
108810     case 221: /* exprlist */
108811     case 226: /* case_exprlist */
108812 {
108813 sqlcipher3ExprListDelete(pParse->db, (yypminor->yy322));
108814 }
108815       break;
108816     case 193: /* fullname */
108817     case 198: /* from */
108818     case 206: /* seltablist */
108819     case 207: /* stl_prefix */
108820 {
108821 sqlcipher3SrcListDelete(pParse->db, (yypminor->yy259));
108822 }
108823       break;
108824     case 199: /* where_opt */
108825     case 201: /* having_opt */
108826     case 210: /* on_opt */
108827     case 215: /* sortitem */
108828     case 225: /* case_operand */
108829     case 227: /* case_else */
108830     case 238: /* when_clause */
108831     case 243: /* key_opt */
108832 {
108833 sqlcipher3ExprDelete(pParse->db, (yypminor->yy314));
108834 }
108835       break;
108836     case 211: /* using_opt */
108837     case 213: /* inscollist */
108838     case 219: /* inscollist_opt */
108839 {
108840 sqlcipher3IdListDelete(pParse->db, (yypminor->yy384));
108841 }
108842       break;
108843     case 234: /* trigger_cmd_list */
108844     case 239: /* trigger_cmd */
108845 {
108846 sqlcipher3DeleteTriggerStep(pParse->db, (yypminor->yy203));
108847 }
108848       break;
108849     case 236: /* trigger_event */
108850 {
108851 sqlcipher3IdListDelete(pParse->db, (yypminor->yy90).b);
108852 }
108853       break;
108854     default:  break;   /* If no destructor action specified: do nothing */
108855   }
108856 }
108857
108858 /*
108859 ** Pop the parser's stack once.
108860 **
108861 ** If there is a destructor routine associated with the token which
108862 ** is popped from the stack, then call it.
108863 **
108864 ** Return the major token number for the symbol popped.
108865 */
108866 static int yy_pop_parser_stack(yyParser *pParser){
108867   YYCODETYPE yymajor;
108868   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
108869
108870   /* There is no mechanism by which the parser stack can be popped below
108871   ** empty in SQLite.  */
108872   if( NEVER(pParser->yyidx<0) ) return 0;
108873 #ifndef NDEBUG
108874   if( yyTraceFILE && pParser->yyidx>=0 ){
108875     fprintf(yyTraceFILE,"%sPopping %s\n",
108876       yyTracePrompt,
108877       yyTokenName[yytos->major]);
108878   }
108879 #endif
108880   yymajor = yytos->major;
108881   yy_destructor(pParser, yymajor, &yytos->minor);
108882   pParser->yyidx--;
108883   return yymajor;
108884 }
108885
108886 /* 
108887 ** Deallocate and destroy a parser.  Destructors are all called for
108888 ** all stack elements before shutting the parser down.
108889 **
108890 ** Inputs:
108891 ** <ul>
108892 ** <li>  A pointer to the parser.  This should be a pointer
108893 **       obtained from sqlcipher3ParserAlloc.
108894 ** <li>  A pointer to a function used to reclaim memory obtained
108895 **       from malloc.
108896 ** </ul>
108897 */
108898 SQLCIPHER_PRIVATE void sqlcipher3ParserFree(
108899   void *p,                    /* The parser to be deleted */
108900   void (*freeProc)(void*)     /* Function used to reclaim memory */
108901 ){
108902   yyParser *pParser = (yyParser*)p;
108903   /* In SQLite, we never try to destroy a parser that was not successfully
108904   ** created in the first place. */
108905   if( NEVER(pParser==0) ) return;
108906   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
108907 #if YYSTACKDEPTH<=0
108908   free(pParser->yystack);
108909 #endif
108910   (*freeProc)((void*)pParser);
108911 }
108912
108913 /*
108914 ** Return the peak depth of the stack for a parser.
108915 */
108916 #ifdef YYTRACKMAXSTACKDEPTH
108917 SQLCIPHER_PRIVATE int sqlcipher3ParserStackPeak(void *p){
108918   yyParser *pParser = (yyParser*)p;
108919   return pParser->yyidxMax;
108920 }
108921 #endif
108922
108923 /*
108924 ** Find the appropriate action for a parser given the terminal
108925 ** look-ahead token iLookAhead.
108926 **
108927 ** If the look-ahead token is YYNOCODE, then check to see if the action is
108928 ** independent of the look-ahead.  If it is, return the action, otherwise
108929 ** return YY_NO_ACTION.
108930 */
108931 static int yy_find_shift_action(
108932   yyParser *pParser,        /* The parser */
108933   YYCODETYPE iLookAhead     /* The look-ahead token */
108934 ){
108935   int i;
108936   int stateno = pParser->yystack[pParser->yyidx].stateno;
108937  
108938   if( stateno>YY_SHIFT_COUNT
108939    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
108940     return yy_default[stateno];
108941   }
108942   assert( iLookAhead!=YYNOCODE );
108943   i += iLookAhead;
108944   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
108945     if( iLookAhead>0 ){
108946 #ifdef YYFALLBACK
108947       YYCODETYPE iFallback;            /* Fallback token */
108948       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
108949              && (iFallback = yyFallback[iLookAhead])!=0 ){
108950 #ifndef NDEBUG
108951         if( yyTraceFILE ){
108952           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
108953              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
108954         }
108955 #endif
108956         return yy_find_shift_action(pParser, iFallback);
108957       }
108958 #endif
108959 #ifdef YYWILDCARD
108960       {
108961         int j = i - iLookAhead + YYWILDCARD;
108962         if( 
108963 #if YY_SHIFT_MIN+YYWILDCARD<0
108964           j>=0 &&
108965 #endif
108966 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
108967           j<YY_ACTTAB_COUNT &&
108968 #endif
108969           yy_lookahead[j]==YYWILDCARD
108970         ){
108971 #ifndef NDEBUG
108972           if( yyTraceFILE ){
108973             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
108974                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
108975           }
108976 #endif /* NDEBUG */
108977           return yy_action[j];
108978         }
108979       }
108980 #endif /* YYWILDCARD */
108981     }
108982     return yy_default[stateno];
108983   }else{
108984     return yy_action[i];
108985   }
108986 }
108987
108988 /*
108989 ** Find the appropriate action for a parser given the non-terminal
108990 ** look-ahead token iLookAhead.
108991 **
108992 ** If the look-ahead token is YYNOCODE, then check to see if the action is
108993 ** independent of the look-ahead.  If it is, return the action, otherwise
108994 ** return YY_NO_ACTION.
108995 */
108996 static int yy_find_reduce_action(
108997   int stateno,              /* Current state number */
108998   YYCODETYPE iLookAhead     /* The look-ahead token */
108999 ){
109000   int i;
109001 #ifdef YYERRORSYMBOL
109002   if( stateno>YY_REDUCE_COUNT ){
109003     return yy_default[stateno];
109004   }
109005 #else
109006   assert( stateno<=YY_REDUCE_COUNT );
109007 #endif
109008   i = yy_reduce_ofst[stateno];
109009   assert( i!=YY_REDUCE_USE_DFLT );
109010   assert( iLookAhead!=YYNOCODE );
109011   i += iLookAhead;
109012 #ifdef YYERRORSYMBOL
109013   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109014     return yy_default[stateno];
109015   }
109016 #else
109017   assert( i>=0 && i<YY_ACTTAB_COUNT );
109018   assert( yy_lookahead[i]==iLookAhead );
109019 #endif
109020   return yy_action[i];
109021 }
109022
109023 /*
109024 ** The following routine is called if the stack overflows.
109025 */
109026 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
109027    sqlcipher3ParserARG_FETCH;
109028    yypParser->yyidx--;
109029 #ifndef NDEBUG
109030    if( yyTraceFILE ){
109031      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
109032    }
109033 #endif
109034    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109035    /* Here code is inserted which will execute if the parser
109036    ** stack every overflows */
109037
109038   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
109039   sqlcipher3ErrorMsg(pParse, "parser stack overflow");
109040   pParse->parseError = 1;
109041    sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
109042 }
109043
109044 /*
109045 ** Perform a shift action.
109046 */
109047 static void yy_shift(
109048   yyParser *yypParser,          /* The parser to be shifted */
109049   int yyNewState,               /* The new state to shift in */
109050   int yyMajor,                  /* The major token to shift in */
109051   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
109052 ){
109053   yyStackEntry *yytos;
109054   yypParser->yyidx++;
109055 #ifdef YYTRACKMAXSTACKDEPTH
109056   if( yypParser->yyidx>yypParser->yyidxMax ){
109057     yypParser->yyidxMax = yypParser->yyidx;
109058   }
109059 #endif
109060 #if YYSTACKDEPTH>0 
109061   if( yypParser->yyidx>=YYSTACKDEPTH ){
109062     yyStackOverflow(yypParser, yypMinor);
109063     return;
109064   }
109065 #else
109066   if( yypParser->yyidx>=yypParser->yystksz ){
109067     yyGrowStack(yypParser);
109068     if( yypParser->yyidx>=yypParser->yystksz ){
109069       yyStackOverflow(yypParser, yypMinor);
109070       return;
109071     }
109072   }
109073 #endif
109074   yytos = &yypParser->yystack[yypParser->yyidx];
109075   yytos->stateno = (YYACTIONTYPE)yyNewState;
109076   yytos->major = (YYCODETYPE)yyMajor;
109077   yytos->minor = *yypMinor;
109078 #ifndef NDEBUG
109079   if( yyTraceFILE && yypParser->yyidx>0 ){
109080     int i;
109081     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
109082     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
109083     for(i=1; i<=yypParser->yyidx; i++)
109084       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
109085     fprintf(yyTraceFILE,"\n");
109086   }
109087 #endif
109088 }
109089
109090 /* The following table contains information about every rule that
109091 ** is used during the reduce.
109092 */
109093 static const struct {
109094   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
109095   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
109096 } yyRuleInfo[] = {
109097   { 142, 1 },
109098   { 143, 2 },
109099   { 143, 1 },
109100   { 144, 1 },
109101   { 144, 3 },
109102   { 145, 0 },
109103   { 145, 1 },
109104   { 145, 3 },
109105   { 146, 1 },
109106   { 147, 3 },
109107   { 149, 0 },
109108   { 149, 1 },
109109   { 149, 2 },
109110   { 148, 0 },
109111   { 148, 1 },
109112   { 148, 1 },
109113   { 148, 1 },
109114   { 147, 2 },
109115   { 147, 2 },
109116   { 147, 2 },
109117   { 151, 1 },
109118   { 151, 0 },
109119   { 147, 2 },
109120   { 147, 3 },
109121   { 147, 5 },
109122   { 147, 2 },
109123   { 152, 6 },
109124   { 154, 1 },
109125   { 156, 0 },
109126   { 156, 3 },
109127   { 155, 1 },
109128   { 155, 0 },
109129   { 153, 4 },
109130   { 153, 2 },
109131   { 158, 3 },
109132   { 158, 1 },
109133   { 161, 3 },
109134   { 162, 1 },
109135   { 165, 1 },
109136   { 165, 1 },
109137   { 166, 1 },
109138   { 150, 1 },
109139   { 150, 1 },
109140   { 150, 1 },
109141   { 163, 0 },
109142   { 163, 1 },
109143   { 167, 1 },
109144   { 167, 4 },
109145   { 167, 6 },
109146   { 168, 1 },
109147   { 168, 2 },
109148   { 169, 1 },
109149   { 169, 1 },
109150   { 164, 2 },
109151   { 164, 0 },
109152   { 172, 3 },
109153   { 172, 1 },
109154   { 173, 2 },
109155   { 173, 4 },
109156   { 173, 3 },
109157   { 173, 3 },
109158   { 173, 2 },
109159   { 173, 2 },
109160   { 173, 3 },
109161   { 173, 5 },
109162   { 173, 2 },
109163   { 173, 4 },
109164   { 173, 4 },
109165   { 173, 1 },
109166   { 173, 2 },
109167   { 178, 0 },
109168   { 178, 1 },
109169   { 180, 0 },
109170   { 180, 2 },
109171   { 182, 2 },
109172   { 182, 3 },
109173   { 182, 3 },
109174   { 182, 3 },
109175   { 183, 2 },
109176   { 183, 2 },
109177   { 183, 1 },
109178   { 183, 1 },
109179   { 183, 2 },
109180   { 181, 3 },
109181   { 181, 2 },
109182   { 184, 0 },
109183   { 184, 2 },
109184   { 184, 2 },
109185   { 159, 0 },
109186   { 159, 2 },
109187   { 185, 3 },
109188   { 185, 2 },
109189   { 185, 1 },
109190   { 186, 2 },
109191   { 186, 7 },
109192   { 186, 5 },
109193   { 186, 5 },
109194   { 186, 10 },
109195   { 188, 0 },
109196   { 188, 1 },
109197   { 176, 0 },
109198   { 176, 3 },
109199   { 189, 0 },
109200   { 189, 2 },
109201   { 190, 1 },
109202   { 190, 1 },
109203   { 190, 1 },
109204   { 147, 4 },
109205   { 192, 2 },
109206   { 192, 0 },
109207   { 147, 8 },
109208   { 147, 4 },
109209   { 147, 1 },
109210   { 160, 1 },
109211   { 160, 3 },
109212   { 195, 1 },
109213   { 195, 2 },
109214   { 195, 1 },
109215   { 194, 9 },
109216   { 196, 1 },
109217   { 196, 1 },
109218   { 196, 0 },
109219   { 204, 2 },
109220   { 204, 0 },
109221   { 197, 3 },
109222   { 197, 2 },
109223   { 197, 4 },
109224   { 205, 2 },
109225   { 205, 1 },
109226   { 205, 0 },
109227   { 198, 0 },
109228   { 198, 2 },
109229   { 207, 2 },
109230   { 207, 0 },
109231   { 206, 7 },
109232   { 206, 7 },
109233   { 206, 7 },
109234   { 157, 0 },
109235   { 157, 2 },
109236   { 193, 2 },
109237   { 208, 1 },
109238   { 208, 2 },
109239   { 208, 3 },
109240   { 208, 4 },
109241   { 210, 2 },
109242   { 210, 0 },
109243   { 209, 0 },
109244   { 209, 3 },
109245   { 209, 2 },
109246   { 211, 4 },
109247   { 211, 0 },
109248   { 202, 0 },
109249   { 202, 3 },
109250   { 214, 4 },
109251   { 214, 2 },
109252   { 215, 1 },
109253   { 177, 1 },
109254   { 177, 1 },
109255   { 177, 0 },
109256   { 200, 0 },
109257   { 200, 3 },
109258   { 201, 0 },
109259   { 201, 2 },
109260   { 203, 0 },
109261   { 203, 2 },
109262   { 203, 4 },
109263   { 203, 4 },
109264   { 147, 5 },
109265   { 199, 0 },
109266   { 199, 2 },
109267   { 147, 7 },
109268   { 217, 5 },
109269   { 217, 3 },
109270   { 147, 8 },
109271   { 147, 5 },
109272   { 147, 6 },
109273   { 218, 2 },
109274   { 218, 1 },
109275   { 220, 3 },
109276   { 220, 1 },
109277   { 219, 0 },
109278   { 219, 3 },
109279   { 213, 3 },
109280   { 213, 1 },
109281   { 175, 1 },
109282   { 175, 3 },
109283   { 174, 1 },
109284   { 175, 1 },
109285   { 175, 1 },
109286   { 175, 3 },
109287   { 175, 5 },
109288   { 174, 1 },
109289   { 174, 1 },
109290   { 175, 1 },
109291   { 175, 1 },
109292   { 175, 3 },
109293   { 175, 6 },
109294   { 175, 5 },
109295   { 175, 4 },
109296   { 174, 1 },
109297   { 175, 3 },
109298   { 175, 3 },
109299   { 175, 3 },
109300   { 175, 3 },
109301   { 175, 3 },
109302   { 175, 3 },
109303   { 175, 3 },
109304   { 175, 3 },
109305   { 222, 1 },
109306   { 222, 2 },
109307   { 222, 1 },
109308   { 222, 2 },
109309   { 175, 3 },
109310   { 175, 5 },
109311   { 175, 2 },
109312   { 175, 3 },
109313   { 175, 3 },
109314   { 175, 4 },
109315   { 175, 2 },
109316   { 175, 2 },
109317   { 175, 2 },
109318   { 175, 2 },
109319   { 223, 1 },
109320   { 223, 2 },
109321   { 175, 5 },
109322   { 224, 1 },
109323   { 224, 2 },
109324   { 175, 5 },
109325   { 175, 3 },
109326   { 175, 5 },
109327   { 175, 4 },
109328   { 175, 4 },
109329   { 175, 5 },
109330   { 226, 5 },
109331   { 226, 4 },
109332   { 227, 2 },
109333   { 227, 0 },
109334   { 225, 1 },
109335   { 225, 0 },
109336   { 221, 1 },
109337   { 221, 0 },
109338   { 216, 3 },
109339   { 216, 1 },
109340   { 147, 11 },
109341   { 228, 1 },
109342   { 228, 0 },
109343   { 179, 0 },
109344   { 179, 3 },
109345   { 187, 5 },
109346   { 187, 3 },
109347   { 229, 0 },
109348   { 229, 2 },
109349   { 147, 4 },
109350   { 147, 1 },
109351   { 147, 2 },
109352   { 147, 3 },
109353   { 147, 5 },
109354   { 147, 6 },
109355   { 147, 5 },
109356   { 147, 6 },
109357   { 230, 1 },
109358   { 230, 1 },
109359   { 230, 1 },
109360   { 230, 1 },
109361   { 230, 1 },
109362   { 170, 2 },
109363   { 171, 2 },
109364   { 232, 1 },
109365   { 231, 1 },
109366   { 231, 0 },
109367   { 147, 5 },
109368   { 233, 11 },
109369   { 235, 1 },
109370   { 235, 1 },
109371   { 235, 2 },
109372   { 235, 0 },
109373   { 236, 1 },
109374   { 236, 1 },
109375   { 236, 3 },
109376   { 237, 0 },
109377   { 237, 3 },
109378   { 238, 0 },
109379   { 238, 2 },
109380   { 234, 3 },
109381   { 234, 2 },
109382   { 240, 1 },
109383   { 240, 3 },
109384   { 241, 0 },
109385   { 241, 3 },
109386   { 241, 2 },
109387   { 239, 7 },
109388   { 239, 8 },
109389   { 239, 5 },
109390   { 239, 5 },
109391   { 239, 1 },
109392   { 175, 4 },
109393   { 175, 6 },
109394   { 191, 1 },
109395   { 191, 1 },
109396   { 191, 1 },
109397   { 147, 4 },
109398   { 147, 6 },
109399   { 147, 3 },
109400   { 243, 0 },
109401   { 243, 2 },
109402   { 242, 1 },
109403   { 242, 0 },
109404   { 147, 1 },
109405   { 147, 3 },
109406   { 147, 1 },
109407   { 147, 3 },
109408   { 147, 6 },
109409   { 147, 6 },
109410   { 244, 1 },
109411   { 245, 0 },
109412   { 245, 1 },
109413   { 147, 1 },
109414   { 147, 4 },
109415   { 246, 7 },
109416   { 247, 1 },
109417   { 247, 3 },
109418   { 248, 0 },
109419   { 248, 2 },
109420   { 249, 1 },
109421   { 249, 3 },
109422   { 250, 1 },
109423   { 251, 0 },
109424   { 251, 4 },
109425   { 251, 2 },
109426 };
109427
109428 static void yy_accept(yyParser*);  /* Forward Declaration */
109429
109430 /*
109431 ** Perform a reduce action and the shift that must immediately
109432 ** follow the reduce.
109433 */
109434 static void yy_reduce(
109435   yyParser *yypParser,         /* The parser */
109436   int yyruleno                 /* Number of the rule by which to reduce */
109437 ){
109438   int yygoto;                     /* The next state */
109439   int yyact;                      /* The next action */
109440   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
109441   yyStackEntry *yymsp;            /* The top of the parser's stack */
109442   int yysize;                     /* Amount to pop the stack */
109443   sqlcipher3ParserARG_FETCH;
109444   yymsp = &yypParser->yystack[yypParser->yyidx];
109445 #ifndef NDEBUG
109446   if( yyTraceFILE && yyruleno>=0 
109447         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
109448     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
109449       yyRuleName[yyruleno]);
109450   }
109451 #endif /* NDEBUG */
109452
109453   /* Silence complaints from purify about yygotominor being uninitialized
109454   ** in some cases when it is copied into the stack after the following
109455   ** switch.  yygotominor is uninitialized when a rule reduces that does
109456   ** not set the value of its left-hand side nonterminal.  Leaving the
109457   ** value of the nonterminal uninitialized is utterly harmless as long
109458   ** as the value is never used.  So really the only thing this code
109459   ** accomplishes is to quieten purify.  
109460   **
109461   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
109462   ** without this code, their parser segfaults.  I'm not sure what there
109463   ** parser is doing to make this happen.  This is the second bug report
109464   ** from wireshark this week.  Clearly they are stressing Lemon in ways
109465   ** that it has not been previously stressed...  (SQLite ticket #2172)
109466   */
109467   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
109468   yygotominor = yyzerominor;
109469
109470
109471   switch( yyruleno ){
109472   /* Beginning here are the reduction cases.  A typical example
109473   ** follows:
109474   **   case 0:
109475   **  #line <lineno> <grammarfile>
109476   **     { ... }           // User supplied code
109477   **  #line <lineno> <thisfile>
109478   **     break;
109479   */
109480       case 5: /* explain ::= */
109481 { sqlcipher3BeginParse(pParse, 0); }
109482         break;
109483       case 6: /* explain ::= EXPLAIN */
109484 { sqlcipher3BeginParse(pParse, 1); }
109485         break;
109486       case 7: /* explain ::= EXPLAIN QUERY PLAN */
109487 { sqlcipher3BeginParse(pParse, 2); }
109488         break;
109489       case 8: /* cmdx ::= cmd */
109490 { sqlcipher3FinishCoding(pParse); }
109491         break;
109492       case 9: /* cmd ::= BEGIN transtype trans_opt */
109493 {sqlcipher3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
109494         break;
109495       case 13: /* transtype ::= */
109496 {yygotominor.yy4 = TK_DEFERRED;}
109497         break;
109498       case 14: /* transtype ::= DEFERRED */
109499       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
109500       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
109501       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
109502       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
109503 {yygotominor.yy4 = yymsp[0].major;}
109504         break;
109505       case 17: /* cmd ::= COMMIT trans_opt */
109506       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
109507 {sqlcipher3CommitTransaction(pParse);}
109508         break;
109509       case 19: /* cmd ::= ROLLBACK trans_opt */
109510 {sqlcipher3RollbackTransaction(pParse);}
109511         break;
109512       case 22: /* cmd ::= SAVEPOINT nm */
109513 {
109514   sqlcipher3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
109515 }
109516         break;
109517       case 23: /* cmd ::= RELEASE savepoint_opt nm */
109518 {
109519   sqlcipher3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
109520 }
109521         break;
109522       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
109523 {
109524   sqlcipher3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
109525 }
109526         break;
109527       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
109528 {
109529    sqlcipher3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
109530 }
109531         break;
109532       case 27: /* createkw ::= CREATE */
109533 {
109534   pParse->db->lookaside.bEnabled = 0;
109535   yygotominor.yy0 = yymsp[0].minor.yy0;
109536 }
109537         break;
109538       case 28: /* ifnotexists ::= */
109539       case 31: /* temp ::= */ yytestcase(yyruleno==31);
109540       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
109541       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
109542       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
109543       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
109544       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
109545       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
109546       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
109547       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
109548       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
109549       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
109550 {yygotominor.yy4 = 0;}
109551         break;
109552       case 29: /* ifnotexists ::= IF NOT EXISTS */
109553       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
109554       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
109555       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
109556       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
109557       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
109558       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
109559       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
109560 {yygotominor.yy4 = 1;}
109561         break;
109562       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
109563 {
109564   sqlcipher3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
109565 }
109566         break;
109567       case 33: /* create_table_args ::= AS select */
109568 {
109569   sqlcipher3EndTable(pParse,0,0,yymsp[0].minor.yy387);
109570   sqlcipher3SelectDelete(pParse->db, yymsp[0].minor.yy387);
109571 }
109572         break;
109573       case 36: /* column ::= columnid type carglist */
109574 {
109575   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
109576   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
109577 }
109578         break;
109579       case 37: /* columnid ::= nm */
109580 {
109581   sqlcipher3AddColumn(pParse,&yymsp[0].minor.yy0);
109582   yygotominor.yy0 = yymsp[0].minor.yy0;
109583 }
109584         break;
109585       case 38: /* id ::= ID */
109586       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
109587       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
109588       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
109589       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
109590       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
109591       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
109592       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
109593       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
109594       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
109595       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
109596       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
109597       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
109598       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
109599       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
109600       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
109601       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
109602       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
109603       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
109604       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
109605       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
109606       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
109607 {yygotominor.yy0 = yymsp[0].minor.yy0;}
109608         break;
109609       case 45: /* type ::= typetoken */
109610 {sqlcipher3AddColumnType(pParse,&yymsp[0].minor.yy0);}
109611         break;
109612       case 47: /* typetoken ::= typename LP signed RP */
109613 {
109614   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
109615   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
109616 }
109617         break;
109618       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
109619 {
109620   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
109621   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
109622 }
109623         break;
109624       case 50: /* typename ::= typename ids */
109625 {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);}
109626         break;
109627       case 57: /* ccons ::= DEFAULT term */
109628       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
109629 {sqlcipher3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
109630         break;
109631       case 58: /* ccons ::= DEFAULT LP expr RP */
109632 {sqlcipher3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
109633         break;
109634       case 60: /* ccons ::= DEFAULT MINUS term */
109635 {
109636   ExprSpan v;
109637   v.pExpr = sqlcipher3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
109638   v.zStart = yymsp[-1].minor.yy0.z;
109639   v.zEnd = yymsp[0].minor.yy118.zEnd;
109640   sqlcipher3AddDefaultValue(pParse,&v);
109641 }
109642         break;
109643       case 61: /* ccons ::= DEFAULT id */
109644 {
109645   ExprSpan v;
109646   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
109647   sqlcipher3AddDefaultValue(pParse,&v);
109648 }
109649         break;
109650       case 63: /* ccons ::= NOT NULL onconf */
109651 {sqlcipher3AddNotNull(pParse, yymsp[0].minor.yy4);}
109652         break;
109653       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
109654 {sqlcipher3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
109655         break;
109656       case 65: /* ccons ::= UNIQUE onconf */
109657 {sqlcipher3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
109658         break;
109659       case 66: /* ccons ::= CHECK LP expr RP */
109660 {sqlcipher3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
109661         break;
109662       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
109663 {sqlcipher3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
109664         break;
109665       case 68: /* ccons ::= defer_subclause */
109666 {sqlcipher3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
109667         break;
109668       case 69: /* ccons ::= COLLATE ids */
109669 {sqlcipher3AddCollateType(pParse, &yymsp[0].minor.yy0);}
109670         break;
109671       case 72: /* refargs ::= */
109672 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
109673         break;
109674       case 73: /* refargs ::= refargs refarg */
109675 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
109676         break;
109677       case 74: /* refarg ::= MATCH nm */
109678       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
109679 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
109680         break;
109681       case 76: /* refarg ::= ON DELETE refact */
109682 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
109683         break;
109684       case 77: /* refarg ::= ON UPDATE refact */
109685 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
109686         break;
109687       case 78: /* refact ::= SET NULL */
109688 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
109689         break;
109690       case 79: /* refact ::= SET DEFAULT */
109691 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
109692         break;
109693       case 80: /* refact ::= CASCADE */
109694 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
109695         break;
109696       case 81: /* refact ::= RESTRICT */
109697 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
109698         break;
109699       case 82: /* refact ::= NO ACTION */
109700 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
109701         break;
109702       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
109703       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
109704       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
109705       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
109706 {yygotominor.yy4 = yymsp[0].minor.yy4;}
109707         break;
109708       case 88: /* conslist_opt ::= */
109709 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
109710         break;
109711       case 89: /* conslist_opt ::= COMMA conslist */
109712 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
109713         break;
109714       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
109715 {sqlcipher3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
109716         break;
109717       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
109718 {sqlcipher3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
109719         break;
109720       case 96: /* tcons ::= CHECK LP expr RP onconf */
109721 {sqlcipher3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
109722         break;
109723       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
109724 {
109725     sqlcipher3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
109726     sqlcipher3DeferForeignKey(pParse, yymsp[0].minor.yy4);
109727 }
109728         break;
109729       case 100: /* onconf ::= */
109730 {yygotominor.yy4 = OE_Default;}
109731         break;
109732       case 102: /* orconf ::= */
109733 {yygotominor.yy210 = OE_Default;}
109734         break;
109735       case 103: /* orconf ::= OR resolvetype */
109736 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
109737         break;
109738       case 105: /* resolvetype ::= IGNORE */
109739 {yygotominor.yy4 = OE_Ignore;}
109740         break;
109741       case 106: /* resolvetype ::= REPLACE */
109742 {yygotominor.yy4 = OE_Replace;}
109743         break;
109744       case 107: /* cmd ::= DROP TABLE ifexists fullname */
109745 {
109746   sqlcipher3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
109747 }
109748         break;
109749       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
109750 {
109751   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);
109752 }
109753         break;
109754       case 111: /* cmd ::= DROP VIEW ifexists fullname */
109755 {
109756   sqlcipher3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
109757 }
109758         break;
109759       case 112: /* cmd ::= select */
109760 {
109761   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
109762   sqlcipher3Select(pParse, yymsp[0].minor.yy387, &dest);
109763   sqlcipher3SelectDelete(pParse->db, yymsp[0].minor.yy387);
109764 }
109765         break;
109766       case 113: /* select ::= oneselect */
109767 {yygotominor.yy387 = yymsp[0].minor.yy387;}
109768         break;
109769       case 114: /* select ::= select multiselect_op oneselect */
109770 {
109771   if( yymsp[0].minor.yy387 ){
109772     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
109773     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
109774   }else{
109775     sqlcipher3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
109776   }
109777   yygotominor.yy387 = yymsp[0].minor.yy387;
109778 }
109779         break;
109780       case 116: /* multiselect_op ::= UNION ALL */
109781 {yygotominor.yy4 = TK_ALL;}
109782         break;
109783       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
109784 {
109785   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);
109786 }
109787         break;
109788       case 122: /* sclp ::= selcollist COMMA */
109789       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
109790 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
109791         break;
109792       case 123: /* sclp ::= */
109793       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
109794       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
109795       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
109796       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
109797 {yygotominor.yy322 = 0;}
109798         break;
109799       case 124: /* selcollist ::= sclp expr as */
109800 {
109801    yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
109802    if( yymsp[0].minor.yy0.n>0 ) sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
109803    sqlcipher3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
109804 }
109805         break;
109806       case 125: /* selcollist ::= sclp STAR */
109807 {
109808   Expr *p = sqlcipher3Expr(pParse->db, TK_ALL, 0);
109809   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
109810 }
109811         break;
109812       case 126: /* selcollist ::= sclp nm DOT STAR */
109813 {
109814   Expr *pRight = sqlcipher3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
109815   Expr *pLeft = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
109816   Expr *pDot = sqlcipher3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
109817   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
109818 }
109819         break;
109820       case 129: /* as ::= */
109821 {yygotominor.yy0.n = 0;}
109822         break;
109823       case 130: /* from ::= */
109824 {yygotominor.yy259 = sqlcipher3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
109825         break;
109826       case 131: /* from ::= FROM seltablist */
109827 {
109828   yygotominor.yy259 = yymsp[0].minor.yy259;
109829   sqlcipher3SrcListShiftJoinType(yygotominor.yy259);
109830 }
109831         break;
109832       case 132: /* stl_prefix ::= seltablist joinop */
109833 {
109834    yygotominor.yy259 = yymsp[-1].minor.yy259;
109835    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
109836 }
109837         break;
109838       case 133: /* stl_prefix ::= */
109839 {yygotominor.yy259 = 0;}
109840         break;
109841       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
109842 {
109843   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);
109844   sqlcipher3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
109845 }
109846         break;
109847       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
109848 {
109849     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);
109850   }
109851         break;
109852       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
109853 {
109854     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
109855       yygotominor.yy259 = yymsp[-4].minor.yy259;
109856     }else{
109857       Select *pSubquery;
109858       sqlcipher3SrcListShiftJoinType(yymsp[-4].minor.yy259);
109859       pSubquery = sqlcipher3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
109860       yygotominor.yy259 = sqlcipher3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
109861     }
109862   }
109863         break;
109864       case 137: /* dbnm ::= */
109865       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
109866 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
109867         break;
109868       case 139: /* fullname ::= nm dbnm */
109869 {yygotominor.yy259 = sqlcipher3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
109870         break;
109871       case 140: /* joinop ::= COMMA|JOIN */
109872 { yygotominor.yy4 = JT_INNER; }
109873         break;
109874       case 141: /* joinop ::= JOIN_KW JOIN */
109875 { yygotominor.yy4 = sqlcipher3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
109876         break;
109877       case 142: /* joinop ::= JOIN_KW nm JOIN */
109878 { yygotominor.yy4 = sqlcipher3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
109879         break;
109880       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
109881 { yygotominor.yy4 = sqlcipher3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
109882         break;
109883       case 144: /* on_opt ::= ON expr */
109884       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
109885       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
109886       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
109887       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
109888       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
109889 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
109890         break;
109891       case 145: /* on_opt ::= */
109892       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
109893       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
109894       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
109895       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
109896 {yygotominor.yy314 = 0;}
109897         break;
109898       case 148: /* indexed_opt ::= NOT INDEXED */
109899 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
109900         break;
109901       case 149: /* using_opt ::= USING LP inscollist RP */
109902       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
109903 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
109904         break;
109905       case 150: /* using_opt ::= */
109906       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
109907 {yygotominor.yy384 = 0;}
109908         break;
109909       case 152: /* orderby_opt ::= ORDER BY sortlist */
109910       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
109911       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
109912 {yygotominor.yy322 = yymsp[0].minor.yy322;}
109913         break;
109914       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
109915 {
109916   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
109917   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
109918 }
109919         break;
109920       case 154: /* sortlist ::= sortitem sortorder */
109921 {
109922   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
109923   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
109924 }
109925         break;
109926       case 156: /* sortorder ::= ASC */
109927       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
109928 {yygotominor.yy4 = SQLCIPHER_SO_ASC;}
109929         break;
109930       case 157: /* sortorder ::= DESC */
109931 {yygotominor.yy4 = SQLCIPHER_SO_DESC;}
109932         break;
109933       case 163: /* limit_opt ::= */
109934 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
109935         break;
109936       case 164: /* limit_opt ::= LIMIT expr */
109937 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
109938         break;
109939       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
109940 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
109941         break;
109942       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
109943 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
109944         break;
109945       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
109946 {
109947   sqlcipher3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
109948   sqlcipher3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
109949 }
109950         break;
109951       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
109952 {
109953   sqlcipher3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
109954   sqlcipher3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
109955   sqlcipher3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
109956 }
109957         break;
109958       case 171: /* setlist ::= setlist COMMA nm EQ expr */
109959 {
109960   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
109961   sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
109962 }
109963         break;
109964       case 172: /* setlist ::= nm EQ expr */
109965 {
109966   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
109967   sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
109968 }
109969         break;
109970       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
109971 {sqlcipher3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
109972         break;
109973       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
109974 {sqlcipher3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
109975         break;
109976       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
109977 {sqlcipher3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
109978         break;
109979       case 176: /* insert_cmd ::= INSERT orconf */
109980 {yygotominor.yy210 = yymsp[0].minor.yy210;}
109981         break;
109982       case 177: /* insert_cmd ::= REPLACE */
109983 {yygotominor.yy210 = OE_Replace;}
109984         break;
109985       case 178: /* itemlist ::= itemlist COMMA expr */
109986       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
109987 {yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
109988         break;
109989       case 179: /* itemlist ::= expr */
109990       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
109991 {yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
109992         break;
109993       case 182: /* inscollist ::= inscollist COMMA nm */
109994 {yygotominor.yy384 = sqlcipher3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
109995         break;
109996       case 183: /* inscollist ::= nm */
109997 {yygotominor.yy384 = sqlcipher3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
109998         break;
109999       case 184: /* expr ::= term */
110000 {yygotominor.yy118 = yymsp[0].minor.yy118;}
110001         break;
110002       case 185: /* expr ::= LP expr RP */
110003 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
110004         break;
110005       case 186: /* term ::= NULL */
110006       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
110007       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
110008 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
110009         break;
110010       case 187: /* expr ::= id */
110011       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
110012 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
110013         break;
110014       case 189: /* expr ::= nm DOT nm */
110015 {
110016   Expr *temp1 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110017   Expr *temp2 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110018   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_DOT, temp1, temp2, 0);
110019   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
110020 }
110021         break;
110022       case 190: /* expr ::= nm DOT nm DOT nm */
110023 {
110024   Expr *temp1 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
110025   Expr *temp2 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110026   Expr *temp3 = sqlcipher3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110027   Expr *temp4 = sqlcipher3PExpr(pParse, TK_DOT, temp2, temp3, 0);
110028   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_DOT, temp1, temp4, 0);
110029   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110030 }
110031         break;
110032       case 193: /* expr ::= REGISTER */
110033 {
110034   /* When doing a nested parse, one can include terms in an expression
110035   ** that look like this:   #1 #2 ...  These terms refer to registers
110036   ** in the virtual machine.  #N is the N-th register. */
110037   if( pParse->nested==0 ){
110038     sqlcipher3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
110039     yygotominor.yy118.pExpr = 0;
110040   }else{
110041     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
110042     if( yygotominor.yy118.pExpr ) sqlcipher3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
110043   }
110044   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110045 }
110046         break;
110047       case 194: /* expr ::= VARIABLE */
110048 {
110049   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
110050   sqlcipher3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
110051   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110052 }
110053         break;
110054       case 195: /* expr ::= expr COLLATE ids */
110055 {
110056   yygotominor.yy118.pExpr = sqlcipher3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
110057   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
110058   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110059 }
110060         break;
110061       case 196: /* expr ::= CAST LP expr AS typetoken RP */
110062 {
110063   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
110064   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
110065 }
110066         break;
110067       case 197: /* expr ::= ID LP distinct exprlist RP */
110068 {
110069   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLCIPHER_LIMIT_FUNCTION_ARG] ){
110070     sqlcipher3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
110071   }
110072   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
110073   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110074   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
110075     yygotominor.yy118.pExpr->flags |= EP_Distinct;
110076   }
110077 }
110078         break;
110079       case 198: /* expr ::= ID LP STAR RP */
110080 {
110081   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
110082   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
110083 }
110084         break;
110085       case 199: /* term ::= CTIME_KW */
110086 {
110087   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
110088   ** treated as functions that return constants */
110089   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
110090   if( yygotominor.yy118.pExpr ){
110091     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
110092   }
110093   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110094 }
110095         break;
110096       case 200: /* expr ::= expr AND expr */
110097       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
110098       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
110099       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
110100       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
110101       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
110102       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
110103       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
110104 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
110105         break;
110106       case 208: /* likeop ::= LIKE_KW */
110107       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
110108 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
110109         break;
110110       case 209: /* likeop ::= NOT LIKE_KW */
110111       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
110112 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
110113         break;
110114       case 212: /* expr ::= expr likeop expr */
110115 {
110116   ExprList *pList;
110117   pList = sqlcipher3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
110118   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
110119   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
110120   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110121   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
110122   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
110123   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
110124 }
110125         break;
110126       case 213: /* expr ::= expr likeop expr ESCAPE expr */
110127 {
110128   ExprList *pList;
110129   pList = sqlcipher3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
110130   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
110131   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
110132   yygotominor.yy118.pExpr = sqlcipher3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
110133   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110134   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110135   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
110136   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
110137 }
110138         break;
110139       case 214: /* expr ::= expr ISNULL|NOTNULL */
110140 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
110141         break;
110142       case 215: /* expr ::= expr NOT NULL */
110143 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
110144         break;
110145       case 216: /* expr ::= expr IS expr */
110146 {
110147   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
110148   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
110149 }
110150         break;
110151       case 217: /* expr ::= expr IS NOT expr */
110152 {
110153   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
110154   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
110155 }
110156         break;
110157       case 218: /* expr ::= NOT expr */
110158       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
110159 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
110160         break;
110161       case 220: /* expr ::= MINUS expr */
110162 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
110163         break;
110164       case 221: /* expr ::= PLUS expr */
110165 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
110166         break;
110167       case 224: /* expr ::= expr between_op expr AND expr */
110168 {
110169   ExprList *pList = sqlcipher3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
110170   pList = sqlcipher3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
110171   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
110172   if( yygotominor.yy118.pExpr ){
110173     yygotominor.yy118.pExpr->x.pList = pList;
110174   }else{
110175     sqlcipher3ExprListDelete(pParse->db, pList);
110176   } 
110177   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110178   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110179   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
110180 }
110181         break;
110182       case 227: /* expr ::= expr in_op LP exprlist RP */
110183 {
110184     if( yymsp[-1].minor.yy322==0 ){
110185       /* Expressions of the form
110186       **
110187       **      expr1 IN ()
110188       **      expr1 NOT IN ()
110189       **
110190       ** simplify to constants 0 (false) and 1 (true), respectively,
110191       ** regardless of the value of expr1.
110192       */
110193       yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_INTEGER, 0, 0, &sqlcipher3IntTokens[yymsp[-3].minor.yy4]);
110194       sqlcipher3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
110195     }else{
110196       yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
110197       if( yygotominor.yy118.pExpr ){
110198         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
110199         sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110200       }else{
110201         sqlcipher3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
110202       }
110203       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110204     }
110205     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110206     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110207   }
110208         break;
110209       case 228: /* expr ::= LP select RP */
110210 {
110211     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_SELECT, 0, 0, 0);
110212     if( yygotominor.yy118.pExpr ){
110213       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
110214       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
110215       sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110216     }else{
110217       sqlcipher3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
110218     }
110219     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
110220     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110221   }
110222         break;
110223       case 229: /* expr ::= expr in_op LP select RP */
110224 {
110225     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
110226     if( yygotominor.yy118.pExpr ){
110227       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
110228       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
110229       sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110230     }else{
110231       sqlcipher3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
110232     }
110233     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110234     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
110235     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110236   }
110237         break;
110238       case 230: /* expr ::= expr in_op nm dbnm */
110239 {
110240     SrcList *pSrc = sqlcipher3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
110241     yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
110242     if( yygotominor.yy118.pExpr ){
110243       yygotominor.yy118.pExpr->x.pSelect = sqlcipher3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
110244       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
110245       sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110246     }else{
110247       sqlcipher3SrcListDelete(pParse->db, pSrc);
110248     }
110249     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
110250     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
110251     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];
110252   }
110253         break;
110254       case 231: /* expr ::= EXISTS LP select RP */
110255 {
110256     Expr *p = yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_EXISTS, 0, 0, 0);
110257     if( p ){
110258       p->x.pSelect = yymsp[-1].minor.yy387;
110259       ExprSetProperty(p, EP_xIsSelect);
110260       sqlcipher3ExprSetHeight(pParse, p);
110261     }else{
110262       sqlcipher3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
110263     }
110264     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
110265     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110266   }
110267         break;
110268       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
110269 {
110270   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
110271   if( yygotominor.yy118.pExpr ){
110272     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
110273     sqlcipher3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
110274   }else{
110275     sqlcipher3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
110276   }
110277   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
110278   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110279 }
110280         break;
110281       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
110282 {
110283   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
110284   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
110285 }
110286         break;
110287       case 234: /* case_exprlist ::= WHEN expr THEN expr */
110288 {
110289   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
110290   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
110291 }
110292         break;
110293       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
110294 {
110295   sqlcipher3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
110296                      sqlcipher3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
110297                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLCIPHER_SO_ASC, yymsp[-7].minor.yy4);
110298 }
110299         break;
110300       case 244: /* uniqueflag ::= UNIQUE */
110301       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
110302 {yygotominor.yy4 = OE_Abort;}
110303         break;
110304       case 245: /* uniqueflag ::= */
110305 {yygotominor.yy4 = OE_None;}
110306         break;
110307       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
110308 {
110309   Expr *p = 0;
110310   if( yymsp[-1].minor.yy0.n>0 ){
110311     p = sqlcipher3Expr(pParse->db, TK_COLUMN, 0);
110312     sqlcipher3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110313   }
110314   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
110315   sqlcipher3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
110316   sqlcipher3ExprListCheckLength(pParse, yygotominor.yy322, "index");
110317   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
110318 }
110319         break;
110320       case 249: /* idxlist ::= nm collate sortorder */
110321 {
110322   Expr *p = 0;
110323   if( yymsp[-1].minor.yy0.n>0 ){
110324     p = sqlcipher3PExpr(pParse, TK_COLUMN, 0, 0, 0);
110325     sqlcipher3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110326   }
110327   yygotominor.yy322 = sqlcipher3ExprListAppend(pParse,0, p);
110328   sqlcipher3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
110329   sqlcipher3ExprListCheckLength(pParse, yygotominor.yy322, "index");
110330   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
110331 }
110332         break;
110333       case 250: /* collate ::= */
110334 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
110335         break;
110336       case 252: /* cmd ::= DROP INDEX ifexists fullname */
110337 {sqlcipher3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
110338         break;
110339       case 253: /* cmd ::= VACUUM */
110340       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
110341 {sqlcipher3Vacuum(pParse);}
110342         break;
110343       case 255: /* cmd ::= PRAGMA nm dbnm */
110344 {sqlcipher3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
110345         break;
110346       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
110347 {sqlcipher3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
110348         break;
110349       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
110350 {sqlcipher3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
110351         break;
110352       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
110353 {sqlcipher3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
110354         break;
110355       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
110356 {sqlcipher3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
110357         break;
110358       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
110359 {
110360   Token all;
110361   all.z = yymsp[-3].minor.yy0.z;
110362   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
110363   sqlcipher3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
110364 }
110365         break;
110366       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
110367 {
110368   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);
110369   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
110370 }
110371         break;
110372       case 272: /* trigger_time ::= BEFORE */
110373       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
110374 { yygotominor.yy4 = TK_BEFORE; }
110375         break;
110376       case 273: /* trigger_time ::= AFTER */
110377 { yygotominor.yy4 = TK_AFTER;  }
110378         break;
110379       case 274: /* trigger_time ::= INSTEAD OF */
110380 { yygotominor.yy4 = TK_INSTEAD;}
110381         break;
110382       case 276: /* trigger_event ::= DELETE|INSERT */
110383       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
110384 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
110385         break;
110386       case 278: /* trigger_event ::= UPDATE OF inscollist */
110387 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
110388         break;
110389       case 281: /* when_clause ::= */
110390       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
110391 { yygotominor.yy314 = 0; }
110392         break;
110393       case 282: /* when_clause ::= WHEN expr */
110394       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
110395 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
110396         break;
110397       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
110398 {
110399   assert( yymsp[-2].minor.yy203!=0 );
110400   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
110401   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
110402   yygotominor.yy203 = yymsp[-2].minor.yy203;
110403 }
110404         break;
110405       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
110406
110407   assert( yymsp[-1].minor.yy203!=0 );
110408   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
110409   yygotominor.yy203 = yymsp[-1].minor.yy203;
110410 }
110411         break;
110412       case 286: /* trnm ::= nm DOT nm */
110413 {
110414   yygotominor.yy0 = yymsp[0].minor.yy0;
110415   sqlcipher3ErrorMsg(pParse, 
110416         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
110417         "statements within triggers");
110418 }
110419         break;
110420       case 288: /* tridxby ::= INDEXED BY nm */
110421 {
110422   sqlcipher3ErrorMsg(pParse,
110423         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
110424         "within triggers");
110425 }
110426         break;
110427       case 289: /* tridxby ::= NOT INDEXED */
110428 {
110429   sqlcipher3ErrorMsg(pParse,
110430         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
110431         "within triggers");
110432 }
110433         break;
110434       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
110435 { yygotominor.yy203 = sqlcipher3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
110436         break;
110437       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
110438 {yygotominor.yy203 = sqlcipher3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
110439         break;
110440       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
110441 {yygotominor.yy203 = sqlcipher3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
110442         break;
110443       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
110444 {yygotominor.yy203 = sqlcipher3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
110445         break;
110446       case 294: /* trigger_cmd ::= select */
110447 {yygotominor.yy203 = sqlcipher3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
110448         break;
110449       case 295: /* expr ::= RAISE LP IGNORE RP */
110450 {
110451   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_RAISE, 0, 0, 0); 
110452   if( yygotominor.yy118.pExpr ){
110453     yygotominor.yy118.pExpr->affinity = OE_Ignore;
110454   }
110455   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
110456   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110457 }
110458         break;
110459       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
110460 {
110461   yygotominor.yy118.pExpr = sqlcipher3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
110462   if( yygotominor.yy118.pExpr ) {
110463     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
110464   }
110465   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
110466   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110467 }
110468         break;
110469       case 297: /* raisetype ::= ROLLBACK */
110470 {yygotominor.yy4 = OE_Rollback;}
110471         break;
110472       case 299: /* raisetype ::= FAIL */
110473 {yygotominor.yy4 = OE_Fail;}
110474         break;
110475       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
110476 {
110477   sqlcipher3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
110478 }
110479         break;
110480       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
110481 {
110482   sqlcipher3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
110483 }
110484         break;
110485       case 302: /* cmd ::= DETACH database_kw_opt expr */
110486 {
110487   sqlcipher3Detach(pParse, yymsp[0].minor.yy118.pExpr);
110488 }
110489         break;
110490       case 307: /* cmd ::= REINDEX */
110491 {sqlcipher3Reindex(pParse, 0, 0);}
110492         break;
110493       case 308: /* cmd ::= REINDEX nm dbnm */
110494 {sqlcipher3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110495         break;
110496       case 309: /* cmd ::= ANALYZE */
110497 {sqlcipher3Analyze(pParse, 0, 0);}
110498         break;
110499       case 310: /* cmd ::= ANALYZE nm dbnm */
110500 {sqlcipher3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110501         break;
110502       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
110503 {
110504   sqlcipher3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
110505 }
110506         break;
110507       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
110508 {
110509   sqlcipher3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
110510 }
110511         break;
110512       case 313: /* add_column_fullname ::= fullname */
110513 {
110514   pParse->db->lookaside.bEnabled = 0;
110515   sqlcipher3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
110516 }
110517         break;
110518       case 316: /* cmd ::= create_vtab */
110519 {sqlcipher3VtabFinishParse(pParse,0);}
110520         break;
110521       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
110522 {sqlcipher3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
110523         break;
110524       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
110525 {
110526     sqlcipher3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
110527 }
110528         break;
110529       case 321: /* vtabarg ::= */
110530 {sqlcipher3VtabArgInit(pParse);}
110531         break;
110532       case 323: /* vtabargtoken ::= ANY */
110533       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
110534       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
110535 {sqlcipher3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
110536         break;
110537       default:
110538       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
110539       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
110540       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
110541       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
110542       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
110543       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
110544       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
110545       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
110546       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
110547       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
110548       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
110549       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
110550       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
110551       /* (44) type ::= */ yytestcase(yyruleno==44);
110552       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
110553       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
110554       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
110555       /* (54) carglist ::= */ yytestcase(yyruleno==54);
110556       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
110557       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
110558       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
110559       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
110560       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
110561       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
110562       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
110563       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
110564       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
110565       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
110566       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
110567       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
110568       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
110569       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
110570       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
110571       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
110572       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
110573       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
110574       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
110575       /* (326) anylist ::= */ yytestcase(yyruleno==326);
110576       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
110577       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
110578         break;
110579   };
110580   yygoto = yyRuleInfo[yyruleno].lhs;
110581   yysize = yyRuleInfo[yyruleno].nrhs;
110582   yypParser->yyidx -= yysize;
110583   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
110584   if( yyact < YYNSTATE ){
110585 #ifdef NDEBUG
110586     /* If we are not debugging and the reduce action popped at least
110587     ** one element off the stack, then we can push the new element back
110588     ** onto the stack here, and skip the stack overflow test in yy_shift().
110589     ** That gives a significant speed improvement. */
110590     if( yysize ){
110591       yypParser->yyidx++;
110592       yymsp -= yysize-1;
110593       yymsp->stateno = (YYACTIONTYPE)yyact;
110594       yymsp->major = (YYCODETYPE)yygoto;
110595       yymsp->minor = yygotominor;
110596     }else
110597 #endif
110598     {
110599       yy_shift(yypParser,yyact,yygoto,&yygotominor);
110600     }
110601   }else{
110602     assert( yyact == YYNSTATE + YYNRULE + 1 );
110603     yy_accept(yypParser);
110604   }
110605 }
110606
110607 /*
110608 ** The following code executes when the parse fails
110609 */
110610 #ifndef YYNOERRORRECOVERY
110611 static void yy_parse_failed(
110612   yyParser *yypParser           /* The parser */
110613 ){
110614   sqlcipher3ParserARG_FETCH;
110615 #ifndef NDEBUG
110616   if( yyTraceFILE ){
110617     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
110618   }
110619 #endif
110620   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110621   /* Here code is inserted which will be executed whenever the
110622   ** parser fails */
110623   sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110624 }
110625 #endif /* YYNOERRORRECOVERY */
110626
110627 /*
110628 ** The following code executes when a syntax error first occurs.
110629 */
110630 static void yy_syntax_error(
110631   yyParser *yypParser,           /* The parser */
110632   int yymajor,                   /* The major type of the error token */
110633   YYMINORTYPE yyminor            /* The minor type of the error token */
110634 ){
110635   sqlcipher3ParserARG_FETCH;
110636 #define TOKEN (yyminor.yy0)
110637
110638   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
110639   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
110640   sqlcipher3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
110641   pParse->parseError = 1;
110642   sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110643 }
110644
110645 /*
110646 ** The following is executed when the parser accepts
110647 */
110648 static void yy_accept(
110649   yyParser *yypParser           /* The parser */
110650 ){
110651   sqlcipher3ParserARG_FETCH;
110652 #ifndef NDEBUG
110653   if( yyTraceFILE ){
110654     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
110655   }
110656 #endif
110657   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110658   /* Here code is inserted which will be executed whenever the
110659   ** parser accepts */
110660   sqlcipher3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
110661 }
110662
110663 /* The main parser program.
110664 ** The first argument is a pointer to a structure obtained from
110665 ** "sqlcipher3ParserAlloc" which describes the current state of the parser.
110666 ** The second argument is the major token number.  The third is
110667 ** the minor token.  The fourth optional argument is whatever the
110668 ** user wants (and specified in the grammar) and is available for
110669 ** use by the action routines.
110670 **
110671 ** Inputs:
110672 ** <ul>
110673 ** <li> A pointer to the parser (an opaque structure.)
110674 ** <li> The major token number.
110675 ** <li> The minor token number.
110676 ** <li> An option argument of a grammar-specified type.
110677 ** </ul>
110678 **
110679 ** Outputs:
110680 ** None.
110681 */
110682 SQLCIPHER_PRIVATE void sqlcipher3Parser(
110683   void *yyp,                   /* The parser */
110684   int yymajor,                 /* The major token code number */
110685   sqlcipher3ParserTOKENTYPE yyminor       /* The value for the token */
110686   sqlcipher3ParserARG_PDECL               /* Optional %extra_argument parameter */
110687 ){
110688   YYMINORTYPE yyminorunion;
110689   int yyact;            /* The parser action. */
110690 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
110691   int yyendofinput;     /* True if we are at the end of input */
110692 #endif
110693 #ifdef YYERRORSYMBOL
110694   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
110695 #endif
110696   yyParser *yypParser;  /* The parser */
110697
110698   /* (re)initialize the parser, if necessary */
110699   yypParser = (yyParser*)yyp;
110700   if( yypParser->yyidx<0 ){
110701 #if YYSTACKDEPTH<=0
110702     if( yypParser->yystksz <=0 ){
110703       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
110704       yyminorunion = yyzerominor;
110705       yyStackOverflow(yypParser, &yyminorunion);
110706       return;
110707     }
110708 #endif
110709     yypParser->yyidx = 0;
110710     yypParser->yyerrcnt = -1;
110711     yypParser->yystack[0].stateno = 0;
110712     yypParser->yystack[0].major = 0;
110713   }
110714   yyminorunion.yy0 = yyminor;
110715 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
110716   yyendofinput = (yymajor==0);
110717 #endif
110718   sqlcipher3ParserARG_STORE;
110719
110720 #ifndef NDEBUG
110721   if( yyTraceFILE ){
110722     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
110723   }
110724 #endif
110725
110726   do{
110727     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
110728     if( yyact<YYNSTATE ){
110729       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
110730       yypParser->yyerrcnt--;
110731       yymajor = YYNOCODE;
110732     }else if( yyact < YYNSTATE + YYNRULE ){
110733       yy_reduce(yypParser,yyact-YYNSTATE);
110734     }else{
110735       assert( yyact == YY_ERROR_ACTION );
110736 #ifdef YYERRORSYMBOL
110737       int yymx;
110738 #endif
110739 #ifndef NDEBUG
110740       if( yyTraceFILE ){
110741         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
110742       }
110743 #endif
110744 #ifdef YYERRORSYMBOL
110745       /* A syntax error has occurred.
110746       ** The response to an error depends upon whether or not the
110747       ** grammar defines an error token "ERROR".  
110748       **
110749       ** This is what we do if the grammar does define ERROR:
110750       **
110751       **  * Call the %syntax_error function.
110752       **
110753       **  * Begin popping the stack until we enter a state where
110754       **    it is legal to shift the error symbol, then shift
110755       **    the error symbol.
110756       **
110757       **  * Set the error count to three.
110758       **
110759       **  * Begin accepting and shifting new tokens.  No new error
110760       **    processing will occur until three tokens have been
110761       **    shifted successfully.
110762       **
110763       */
110764       if( yypParser->yyerrcnt<0 ){
110765         yy_syntax_error(yypParser,yymajor,yyminorunion);
110766       }
110767       yymx = yypParser->yystack[yypParser->yyidx].major;
110768       if( yymx==YYERRORSYMBOL || yyerrorhit ){
110769 #ifndef NDEBUG
110770         if( yyTraceFILE ){
110771           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
110772              yyTracePrompt,yyTokenName[yymajor]);
110773         }
110774 #endif
110775         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
110776         yymajor = YYNOCODE;
110777       }else{
110778          while(
110779           yypParser->yyidx >= 0 &&
110780           yymx != YYERRORSYMBOL &&
110781           (yyact = yy_find_reduce_action(
110782                         yypParser->yystack[yypParser->yyidx].stateno,
110783                         YYERRORSYMBOL)) >= YYNSTATE
110784         ){
110785           yy_pop_parser_stack(yypParser);
110786         }
110787         if( yypParser->yyidx < 0 || yymajor==0 ){
110788           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110789           yy_parse_failed(yypParser);
110790           yymajor = YYNOCODE;
110791         }else if( yymx!=YYERRORSYMBOL ){
110792           YYMINORTYPE u2;
110793           u2.YYERRSYMDT = 0;
110794           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
110795         }
110796       }
110797       yypParser->yyerrcnt = 3;
110798       yyerrorhit = 1;
110799 #elif defined(YYNOERRORRECOVERY)
110800       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
110801       ** do any kind of error recovery.  Instead, simply invoke the syntax
110802       ** error routine and continue going as if nothing had happened.
110803       **
110804       ** Applications can set this macro (for example inside %include) if
110805       ** they intend to abandon the parse upon the first syntax error seen.
110806       */
110807       yy_syntax_error(yypParser,yymajor,yyminorunion);
110808       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110809       yymajor = YYNOCODE;
110810       
110811 #else  /* YYERRORSYMBOL is not defined */
110812       /* This is what we do if the grammar does not define ERROR:
110813       **
110814       **  * Report an error message, and throw away the input token.
110815       **
110816       **  * If the input token is $, then fail the parse.
110817       **
110818       ** As before, subsequent error messages are suppressed until
110819       ** three input tokens have been successfully shifted.
110820       */
110821       if( yypParser->yyerrcnt<=0 ){
110822         yy_syntax_error(yypParser,yymajor,yyminorunion);
110823       }
110824       yypParser->yyerrcnt = 3;
110825       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
110826       if( yyendofinput ){
110827         yy_parse_failed(yypParser);
110828       }
110829       yymajor = YYNOCODE;
110830 #endif
110831     }
110832   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
110833   return;
110834 }
110835
110836 /************** End of parse.c ***********************************************/
110837 /************** Begin file tokenize.c ****************************************/
110838 /*
110839 ** 2001 September 15
110840 **
110841 ** The author disclaims copyright to this source code.  In place of
110842 ** a legal notice, here is a blessing:
110843 **
110844 **    May you do good and not evil.
110845 **    May you find forgiveness for yourself and forgive others.
110846 **    May you share freely, never taking more than you give.
110847 **
110848 *************************************************************************
110849 ** An tokenizer for SQL
110850 **
110851 ** This file contains C code that splits an SQL input string up into
110852 ** individual tokens and sends those tokens one-by-one over to the
110853 ** parser for analysis.
110854 */
110855 /* #include <stdlib.h> */
110856
110857 /*
110858 ** The charMap() macro maps alphabetic characters into their
110859 ** lower-case ASCII equivalent.  On ASCII machines, this is just
110860 ** an upper-to-lower case map.  On EBCDIC machines we also need
110861 ** to adjust the encoding.  Only alphabetic characters and underscores
110862 ** need to be translated.
110863 */
110864 #ifdef SQLCIPHER_ASCII
110865 # define charMap(X) sqlcipher3UpperToLower[(unsigned char)X]
110866 #endif
110867 #ifdef SQLCIPHER_EBCDIC
110868 # define charMap(X) ebcdicToAscii[(unsigned char)X]
110869 const unsigned char ebcdicToAscii[] = {
110870 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
110871    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
110872    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
110873    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
110874    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
110875    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
110876    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
110877    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
110878    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
110879    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
110880    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
110881    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
110882    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
110883    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
110884    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
110885    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
110886    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
110887 };
110888 #endif
110889
110890 /*
110891 ** The sqlcipher3KeywordCode function looks up an identifier to determine if
110892 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
110893 ** returned.  If the input is not a keyword, TK_ID is returned.
110894 **
110895 ** The implementation of this routine was generated by a program,
110896 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
110897 ** The output of the mkkeywordhash.c program is written into a file
110898 ** named keywordhash.h and then included into this source file by
110899 ** the #include below.
110900 */
110901 /************** Include keywordhash.h in the middle of tokenize.c ************/
110902 /************** Begin file keywordhash.h *************************************/
110903 /***** This file contains automatically generated code ******
110904 **
110905 ** The code in this file has been automatically generated by
110906 **
110907 **   sqlcipher/tool/mkkeywordhash.c
110908 **
110909 ** The code in this file implements a function that determines whether
110910 ** or not a given identifier is really an SQL keyword.  The same thing
110911 ** might be implemented more directly using a hand-written hash table.
110912 ** But by using this automatically generated code, the size of the code
110913 ** is substantially reduced.  This is important for embedded applications
110914 ** on platforms with limited memory.
110915 */
110916 /* Hash score: 175 */
110917 static int keywordCode(const char *z, int n){
110918   /* zText[] encodes 811 bytes of keywords in 541 bytes */
110919   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
110920   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
110921   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
110922   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
110923   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
110924   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
110925   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
110926   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
110927   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
110928   /*   INITIALLY                                                          */
110929   static const char zText[540] = {
110930     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
110931     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
110932     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
110933     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
110934     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
110935     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
110936     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
110937     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
110938     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
110939     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
110940     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
110941     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
110942     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
110943     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
110944     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
110945     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
110946     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
110947     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
110948     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
110949     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
110950     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
110951     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
110952     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
110953     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
110954     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
110955     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
110956     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
110957     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
110958     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
110959     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
110960   };
110961   static const unsigned char aHash[127] = {
110962       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
110963       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
110964      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
110965        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
110966        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
110967       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
110968       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
110969       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
110970       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
110971       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
110972   };
110973   static const unsigned char aNext[121] = {
110974        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
110975        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
110976        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
110977        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
110978        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
110979       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
110980       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
110981        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
110982      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
110983       35,  64,   0,   0,
110984   };
110985   static const unsigned char aLen[121] = {
110986        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
110987        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
110988       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
110989        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
110990        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
110991        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
110992        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
110993        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
110994        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
110995        6,   4,   9,   3,
110996   };
110997   static const unsigned short int aOffset[121] = {
110998        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
110999       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
111000       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
111001      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
111002      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
111003      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
111004      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
111005      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
111006      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
111007      521, 527, 531, 536,
111008   };
111009   static const unsigned char aCode[121] = {
111010     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
111011     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
111012     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
111013     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
111014     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
111015     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
111016     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
111017     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
111018     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
111019     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
111020     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
111021     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
111022     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
111023     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
111024     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
111025     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
111026     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
111027     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
111028     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
111029     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
111030     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
111031     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
111032     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
111033     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
111034     TK_ALL,        
111035   };
111036   int h, i;
111037   if( n<2 ) return TK_ID;
111038   h = ((charMap(z[0])*4) ^
111039       (charMap(z[n-1])*3) ^
111040       n) % 127;
111041   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
111042     if( aLen[i]==n && sqlcipher3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
111043       testcase( i==0 ); /* REINDEX */
111044       testcase( i==1 ); /* INDEXED */
111045       testcase( i==2 ); /* INDEX */
111046       testcase( i==3 ); /* DESC */
111047       testcase( i==4 ); /* ESCAPE */
111048       testcase( i==5 ); /* EACH */
111049       testcase( i==6 ); /* CHECK */
111050       testcase( i==7 ); /* KEY */
111051       testcase( i==8 ); /* BEFORE */
111052       testcase( i==9 ); /* FOREIGN */
111053       testcase( i==10 ); /* FOR */
111054       testcase( i==11 ); /* IGNORE */
111055       testcase( i==12 ); /* REGEXP */
111056       testcase( i==13 ); /* EXPLAIN */
111057       testcase( i==14 ); /* INSTEAD */
111058       testcase( i==15 ); /* ADD */
111059       testcase( i==16 ); /* DATABASE */
111060       testcase( i==17 ); /* AS */
111061       testcase( i==18 ); /* SELECT */
111062       testcase( i==19 ); /* TABLE */
111063       testcase( i==20 ); /* LEFT */
111064       testcase( i==21 ); /* THEN */
111065       testcase( i==22 ); /* END */
111066       testcase( i==23 ); /* DEFERRABLE */
111067       testcase( i==24 ); /* ELSE */
111068       testcase( i==25 ); /* EXCEPT */
111069       testcase( i==26 ); /* TRANSACTION */
111070       testcase( i==27 ); /* ACTION */
111071       testcase( i==28 ); /* ON */
111072       testcase( i==29 ); /* NATURAL */
111073       testcase( i==30 ); /* ALTER */
111074       testcase( i==31 ); /* RAISE */
111075       testcase( i==32 ); /* EXCLUSIVE */
111076       testcase( i==33 ); /* EXISTS */
111077       testcase( i==34 ); /* SAVEPOINT */
111078       testcase( i==35 ); /* INTERSECT */
111079       testcase( i==36 ); /* TRIGGER */
111080       testcase( i==37 ); /* REFERENCES */
111081       testcase( i==38 ); /* CONSTRAINT */
111082       testcase( i==39 ); /* INTO */
111083       testcase( i==40 ); /* OFFSET */
111084       testcase( i==41 ); /* OF */
111085       testcase( i==42 ); /* SET */
111086       testcase( i==43 ); /* TEMPORARY */
111087       testcase( i==44 ); /* TEMP */
111088       testcase( i==45 ); /* OR */
111089       testcase( i==46 ); /* UNIQUE */
111090       testcase( i==47 ); /* QUERY */
111091       testcase( i==48 ); /* ATTACH */
111092       testcase( i==49 ); /* HAVING */
111093       testcase( i==50 ); /* GROUP */
111094       testcase( i==51 ); /* UPDATE */
111095       testcase( i==52 ); /* BEGIN */
111096       testcase( i==53 ); /* INNER */
111097       testcase( i==54 ); /* RELEASE */
111098       testcase( i==55 ); /* BETWEEN */
111099       testcase( i==56 ); /* NOTNULL */
111100       testcase( i==57 ); /* NOT */
111101       testcase( i==58 ); /* NO */
111102       testcase( i==59 ); /* NULL */
111103       testcase( i==60 ); /* LIKE */
111104       testcase( i==61 ); /* CASCADE */
111105       testcase( i==62 ); /* ASC */
111106       testcase( i==63 ); /* DELETE */
111107       testcase( i==64 ); /* CASE */
111108       testcase( i==65 ); /* COLLATE */
111109       testcase( i==66 ); /* CREATE */
111110       testcase( i==67 ); /* CURRENT_DATE */
111111       testcase( i==68 ); /* DETACH */
111112       testcase( i==69 ); /* IMMEDIATE */
111113       testcase( i==70 ); /* JOIN */
111114       testcase( i==71 ); /* INSERT */
111115       testcase( i==72 ); /* MATCH */
111116       testcase( i==73 ); /* PLAN */
111117       testcase( i==74 ); /* ANALYZE */
111118       testcase( i==75 ); /* PRAGMA */
111119       testcase( i==76 ); /* ABORT */
111120       testcase( i==77 ); /* VALUES */
111121       testcase( i==78 ); /* VIRTUAL */
111122       testcase( i==79 ); /* LIMIT */
111123       testcase( i==80 ); /* WHEN */
111124       testcase( i==81 ); /* WHERE */
111125       testcase( i==82 ); /* RENAME */
111126       testcase( i==83 ); /* AFTER */
111127       testcase( i==84 ); /* REPLACE */
111128       testcase( i==85 ); /* AND */
111129       testcase( i==86 ); /* DEFAULT */
111130       testcase( i==87 ); /* AUTOINCREMENT */
111131       testcase( i==88 ); /* TO */
111132       testcase( i==89 ); /* IN */
111133       testcase( i==90 ); /* CAST */
111134       testcase( i==91 ); /* COLUMN */
111135       testcase( i==92 ); /* COMMIT */
111136       testcase( i==93 ); /* CONFLICT */
111137       testcase( i==94 ); /* CROSS */
111138       testcase( i==95 ); /* CURRENT_TIMESTAMP */
111139       testcase( i==96 ); /* CURRENT_TIME */
111140       testcase( i==97 ); /* PRIMARY */
111141       testcase( i==98 ); /* DEFERRED */
111142       testcase( i==99 ); /* DISTINCT */
111143       testcase( i==100 ); /* IS */
111144       testcase( i==101 ); /* DROP */
111145       testcase( i==102 ); /* FAIL */
111146       testcase( i==103 ); /* FROM */
111147       testcase( i==104 ); /* FULL */
111148       testcase( i==105 ); /* GLOB */
111149       testcase( i==106 ); /* BY */
111150       testcase( i==107 ); /* IF */
111151       testcase( i==108 ); /* ISNULL */
111152       testcase( i==109 ); /* ORDER */
111153       testcase( i==110 ); /* RESTRICT */
111154       testcase( i==111 ); /* OUTER */
111155       testcase( i==112 ); /* RIGHT */
111156       testcase( i==113 ); /* ROLLBACK */
111157       testcase( i==114 ); /* ROW */
111158       testcase( i==115 ); /* UNION */
111159       testcase( i==116 ); /* USING */
111160       testcase( i==117 ); /* VACUUM */
111161       testcase( i==118 ); /* VIEW */
111162       testcase( i==119 ); /* INITIALLY */
111163       testcase( i==120 ); /* ALL */
111164       return aCode[i];
111165     }
111166   }
111167   return TK_ID;
111168 }
111169 SQLCIPHER_PRIVATE int sqlcipher3KeywordCode(const unsigned char *z, int n){
111170   return keywordCode((char*)z, n);
111171 }
111172 #define SQLCIPHER_N_KEYWORD 121
111173
111174 /************** End of keywordhash.h *****************************************/
111175 /************** Continuing where we left off in tokenize.c *******************/
111176
111177
111178 /*
111179 ** If X is a character that can be used in an identifier then
111180 ** IdChar(X) will be true.  Otherwise it is false.
111181 **
111182 ** For ASCII, any character with the high-order bit set is
111183 ** allowed in an identifier.  For 7-bit characters, 
111184 ** sqlcipher3IsIdChar[X] must be 1.
111185 **
111186 ** For EBCDIC, the rules are more complex but have the same
111187 ** end result.
111188 **
111189 ** Ticket #1066.  the SQL standard does not allow '$' in the
111190 ** middle of identfiers.  But many SQL implementations do. 
111191 ** SQLite will allow '$' in identifiers for compatibility.
111192 ** But the feature is undocumented.
111193 */
111194 #ifdef SQLCIPHER_ASCII
111195 #define IdChar(C)  ((sqlcipher3CtypeMap[(unsigned char)C]&0x46)!=0)
111196 #endif
111197 #ifdef SQLCIPHER_EBCDIC
111198 SQLCIPHER_PRIVATE const char sqlcipher3IsEbcdicIdChar[] = {
111199 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
111200     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
111201     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
111202     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
111203     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
111204     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
111205     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
111206     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
111207     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
111208     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
111209     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
111210     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
111211     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
111212 };
111213 #define IdChar(C)  (((c=C)>=0x42 && sqlcipher3IsEbcdicIdChar[c-0x40]))
111214 #endif
111215
111216
111217 /*
111218 ** Return the length of the token that begins at z[0]. 
111219 ** Store the token type in *tokenType before returning.
111220 */
111221 SQLCIPHER_PRIVATE int sqlcipher3GetToken(const unsigned char *z, int *tokenType){
111222   int i, c;
111223   switch( *z ){
111224     case ' ': case '\t': case '\n': case '\f': case '\r': {
111225       testcase( z[0]==' ' );
111226       testcase( z[0]=='\t' );
111227       testcase( z[0]=='\n' );
111228       testcase( z[0]=='\f' );
111229       testcase( z[0]=='\r' );
111230       for(i=1; sqlcipher3Isspace(z[i]); i++){}
111231       *tokenType = TK_SPACE;
111232       return i;
111233     }
111234     case '-': {
111235       if( z[1]=='-' ){
111236         /* IMP: R-15891-05542 -- syntax diagram for comments */
111237         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
111238         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111239         return i;
111240       }
111241       *tokenType = TK_MINUS;
111242       return 1;
111243     }
111244     case '(': {
111245       *tokenType = TK_LP;
111246       return 1;
111247     }
111248     case ')': {
111249       *tokenType = TK_RP;
111250       return 1;
111251     }
111252     case ';': {
111253       *tokenType = TK_SEMI;
111254       return 1;
111255     }
111256     case '+': {
111257       *tokenType = TK_PLUS;
111258       return 1;
111259     }
111260     case '*': {
111261       *tokenType = TK_STAR;
111262       return 1;
111263     }
111264     case '/': {
111265       if( z[1]!='*' || z[2]==0 ){
111266         *tokenType = TK_SLASH;
111267         return 1;
111268       }
111269       /* IMP: R-15891-05542 -- syntax diagram for comments */
111270       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
111271       if( c ) i++;
111272       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111273       return i;
111274     }
111275     case '%': {
111276       *tokenType = TK_REM;
111277       return 1;
111278     }
111279     case '=': {
111280       *tokenType = TK_EQ;
111281       return 1 + (z[1]=='=');
111282     }
111283     case '<': {
111284       if( (c=z[1])=='=' ){
111285         *tokenType = TK_LE;
111286         return 2;
111287       }else if( c=='>' ){
111288         *tokenType = TK_NE;
111289         return 2;
111290       }else if( c=='<' ){
111291         *tokenType = TK_LSHIFT;
111292         return 2;
111293       }else{
111294         *tokenType = TK_LT;
111295         return 1;
111296       }
111297     }
111298     case '>': {
111299       if( (c=z[1])=='=' ){
111300         *tokenType = TK_GE;
111301         return 2;
111302       }else if( c=='>' ){
111303         *tokenType = TK_RSHIFT;
111304         return 2;
111305       }else{
111306         *tokenType = TK_GT;
111307         return 1;
111308       }
111309     }
111310     case '!': {
111311       if( z[1]!='=' ){
111312         *tokenType = TK_ILLEGAL;
111313         return 2;
111314       }else{
111315         *tokenType = TK_NE;
111316         return 2;
111317       }
111318     }
111319     case '|': {
111320       if( z[1]!='|' ){
111321         *tokenType = TK_BITOR;
111322         return 1;
111323       }else{
111324         *tokenType = TK_CONCAT;
111325         return 2;
111326       }
111327     }
111328     case ',': {
111329       *tokenType = TK_COMMA;
111330       return 1;
111331     }
111332     case '&': {
111333       *tokenType = TK_BITAND;
111334       return 1;
111335     }
111336     case '~': {
111337       *tokenType = TK_BITNOT;
111338       return 1;
111339     }
111340     case '`':
111341     case '\'':
111342     case '"': {
111343       int delim = z[0];
111344       testcase( delim=='`' );
111345       testcase( delim=='\'' );
111346       testcase( delim=='"' );
111347       for(i=1; (c=z[i])!=0; i++){
111348         if( c==delim ){
111349           if( z[i+1]==delim ){
111350             i++;
111351           }else{
111352             break;
111353           }
111354         }
111355       }
111356       if( c=='\'' ){
111357         *tokenType = TK_STRING;
111358         return i+1;
111359       }else if( c!=0 ){
111360         *tokenType = TK_ID;
111361         return i+1;
111362       }else{
111363         *tokenType = TK_ILLEGAL;
111364         return i;
111365       }
111366     }
111367     case '.': {
111368 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
111369       if( !sqlcipher3Isdigit(z[1]) )
111370 #endif
111371       {
111372         *tokenType = TK_DOT;
111373         return 1;
111374       }
111375       /* If the next character is a digit, this is a floating point
111376       ** number that begins with ".".  Fall thru into the next case */
111377     }
111378     case '0': case '1': case '2': case '3': case '4':
111379     case '5': case '6': case '7': case '8': case '9': {
111380       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
111381       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
111382       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
111383       testcase( z[0]=='9' );
111384       *tokenType = TK_INTEGER;
111385       for(i=0; sqlcipher3Isdigit(z[i]); i++){}
111386 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
111387       if( z[i]=='.' ){
111388         i++;
111389         while( sqlcipher3Isdigit(z[i]) ){ i++; }
111390         *tokenType = TK_FLOAT;
111391       }
111392       if( (z[i]=='e' || z[i]=='E') &&
111393            ( sqlcipher3Isdigit(z[i+1]) 
111394             || ((z[i+1]=='+' || z[i+1]=='-') && sqlcipher3Isdigit(z[i+2]))
111395            )
111396       ){
111397         i += 2;
111398         while( sqlcipher3Isdigit(z[i]) ){ i++; }
111399         *tokenType = TK_FLOAT;
111400       }
111401 #endif
111402       while( IdChar(z[i]) ){
111403         *tokenType = TK_ILLEGAL;
111404         i++;
111405       }
111406       return i;
111407     }
111408     case '[': {
111409       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
111410       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
111411       return i;
111412     }
111413     case '?': {
111414       *tokenType = TK_VARIABLE;
111415       for(i=1; sqlcipher3Isdigit(z[i]); i++){}
111416       return i;
111417     }
111418     case '#': {
111419       for(i=1; sqlcipher3Isdigit(z[i]); i++){}
111420       if( i>1 ){
111421         /* Parameters of the form #NNN (where NNN is a number) are used
111422         ** internally by sqlcipher3NestedParse.  */
111423         *tokenType = TK_REGISTER;
111424         return i;
111425       }
111426       /* Fall through into the next case if the '#' is not followed by
111427       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
111428     }
111429 #ifndef SQLCIPHER_OMIT_TCL_VARIABLE
111430     case '$':
111431 #endif
111432     case '@':  /* For compatibility with MS SQL Server */
111433     case ':': {
111434       int n = 0;
111435       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
111436       *tokenType = TK_VARIABLE;
111437       for(i=1; (c=z[i])!=0; i++){
111438         if( IdChar(c) ){
111439           n++;
111440 #ifndef SQLCIPHER_OMIT_TCL_VARIABLE
111441         }else if( c=='(' && n>0 ){
111442           do{
111443             i++;
111444           }while( (c=z[i])!=0 && !sqlcipher3Isspace(c) && c!=')' );
111445           if( c==')' ){
111446             i++;
111447           }else{
111448             *tokenType = TK_ILLEGAL;
111449           }
111450           break;
111451         }else if( c==':' && z[i+1]==':' ){
111452           i++;
111453 #endif
111454         }else{
111455           break;
111456         }
111457       }
111458       if( n==0 ) *tokenType = TK_ILLEGAL;
111459       return i;
111460     }
111461 #ifndef SQLCIPHER_OMIT_BLOB_LITERAL
111462     case 'x': case 'X': {
111463       testcase( z[0]=='x' ); testcase( z[0]=='X' );
111464       if( z[1]=='\'' ){
111465         *tokenType = TK_BLOB;
111466         for(i=2; sqlcipher3Isxdigit(z[i]); i++){}
111467         if( z[i]!='\'' || i%2 ){
111468           *tokenType = TK_ILLEGAL;
111469           while( z[i] && z[i]!='\'' ){ i++; }
111470         }
111471         if( z[i] ) i++;
111472         return i;
111473       }
111474       /* Otherwise fall through to the next case */
111475     }
111476 #endif
111477     default: {
111478       if( !IdChar(*z) ){
111479         break;
111480       }
111481       for(i=1; IdChar(z[i]); i++){}
111482       *tokenType = keywordCode((char*)z, i);
111483       return i;
111484     }
111485   }
111486   *tokenType = TK_ILLEGAL;
111487   return 1;
111488 }
111489
111490 /*
111491 ** Run the parser on the given SQL string.  The parser structure is
111492 ** passed in.  An SQLCIPHER_ status code is returned.  If an error occurs
111493 ** then an and attempt is made to write an error message into 
111494 ** memory obtained from sqlcipher3_malloc() and to make *pzErrMsg point to that
111495 ** error message.
111496 */
111497 SQLCIPHER_PRIVATE int sqlcipher3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
111498   int nErr = 0;                   /* Number of errors encountered */
111499   int i;                          /* Loop counter */
111500   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
111501   int tokenType;                  /* type of the next token */
111502   int lastTokenParsed = -1;       /* type of the previous token */
111503   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
111504   sqlcipher3 *db = pParse->db;       /* The database connection */
111505   int mxSqlLen;                   /* Max length of an SQL string */
111506
111507
111508   mxSqlLen = db->aLimit[SQLCIPHER_LIMIT_SQL_LENGTH];
111509   if( db->activeVdbeCnt==0 ){
111510     db->u1.isInterrupted = 0;
111511   }
111512   pParse->rc = SQLCIPHER_OK;
111513   pParse->zTail = zSql;
111514   i = 0;
111515   assert( pzErrMsg!=0 );
111516   pEngine = sqlcipher3ParserAlloc((void*(*)(size_t))sqlcipher3Malloc);
111517   if( pEngine==0 ){
111518     db->mallocFailed = 1;
111519     return SQLCIPHER_NOMEM;
111520   }
111521   assert( pParse->pNewTable==0 );
111522   assert( pParse->pNewTrigger==0 );
111523   assert( pParse->nVar==0 );
111524   assert( pParse->nzVar==0 );
111525   assert( pParse->azVar==0 );
111526   enableLookaside = db->lookaside.bEnabled;
111527   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
111528   while( !db->mallocFailed && zSql[i]!=0 ){
111529     assert( i>=0 );
111530     pParse->sLastToken.z = &zSql[i];
111531     pParse->sLastToken.n = sqlcipher3GetToken((unsigned char*)&zSql[i],&tokenType);
111532     i += pParse->sLastToken.n;
111533     if( i>mxSqlLen ){
111534       pParse->rc = SQLCIPHER_TOOBIG;
111535       break;
111536     }
111537     switch( tokenType ){
111538       case TK_SPACE: {
111539         if( db->u1.isInterrupted ){
111540           sqlcipher3ErrorMsg(pParse, "interrupt");
111541           pParse->rc = SQLCIPHER_INTERRUPT;
111542           goto abort_parse;
111543         }
111544         break;
111545       }
111546       case TK_ILLEGAL: {
111547         sqlcipher3DbFree(db, *pzErrMsg);
111548         *pzErrMsg = sqlcipher3MPrintf(db, "unrecognized token: \"%T\"",
111549                         &pParse->sLastToken);
111550         nErr++;
111551         goto abort_parse;
111552       }
111553       case TK_SEMI: {
111554         pParse->zTail = &zSql[i];
111555         /* Fall thru into the default case */
111556       }
111557       default: {
111558         sqlcipher3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
111559         lastTokenParsed = tokenType;
111560         if( pParse->rc!=SQLCIPHER_OK ){
111561           goto abort_parse;
111562         }
111563         break;
111564       }
111565     }
111566   }
111567 abort_parse:
111568   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLCIPHER_OK ){
111569     if( lastTokenParsed!=TK_SEMI ){
111570       sqlcipher3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
111571       pParse->zTail = &zSql[i];
111572     }
111573     sqlcipher3Parser(pEngine, 0, pParse->sLastToken, pParse);
111574   }
111575 #ifdef YYTRACKMAXSTACKDEPTH
111576   sqlcipher3StatusSet(SQLCIPHER_STATUS_PARSER_STACK,
111577       sqlcipher3ParserStackPeak(pEngine)
111578   );
111579 #endif /* YYDEBUG */
111580   sqlcipher3ParserFree(pEngine, sqlcipher3_free);
111581   db->lookaside.bEnabled = enableLookaside;
111582   if( db->mallocFailed ){
111583     pParse->rc = SQLCIPHER_NOMEM;
111584   }
111585   if( pParse->rc!=SQLCIPHER_OK && pParse->rc!=SQLCIPHER_DONE && pParse->zErrMsg==0 ){
111586     sqlcipher3SetString(&pParse->zErrMsg, db, "%s", sqlcipher3ErrStr(pParse->rc));
111587   }
111588   assert( pzErrMsg!=0 );
111589   if( pParse->zErrMsg ){
111590     *pzErrMsg = pParse->zErrMsg;
111591     sqlcipher3_log(pParse->rc, "%s", *pzErrMsg);
111592     pParse->zErrMsg = 0;
111593     nErr++;
111594   }
111595   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
111596     sqlcipher3VdbeDelete(pParse->pVdbe);
111597     pParse->pVdbe = 0;
111598   }
111599 #ifndef SQLCIPHER_OMIT_SHARED_CACHE
111600   if( pParse->nested==0 ){
111601     sqlcipher3DbFree(db, pParse->aTableLock);
111602     pParse->aTableLock = 0;
111603     pParse->nTableLock = 0;
111604   }
111605 #endif
111606 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
111607   sqlcipher3_free(pParse->apVtabLock);
111608 #endif
111609
111610   if( !IN_DECLARE_VTAB ){
111611     /* If the pParse->declareVtab flag is set, do not delete any table 
111612     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
111613     ** will take responsibility for freeing the Table structure.
111614     */
111615     sqlcipher3DeleteTable(db, pParse->pNewTable);
111616   }
111617
111618   sqlcipher3DeleteTrigger(db, pParse->pNewTrigger);
111619   for(i=pParse->nzVar-1; i>=0; i--) sqlcipher3DbFree(db, pParse->azVar[i]);
111620   sqlcipher3DbFree(db, pParse->azVar);
111621   sqlcipher3DbFree(db, pParse->aAlias);
111622   while( pParse->pAinc ){
111623     AutoincInfo *p = pParse->pAinc;
111624     pParse->pAinc = p->pNext;
111625     sqlcipher3DbFree(db, p);
111626   }
111627   while( pParse->pZombieTab ){
111628     Table *p = pParse->pZombieTab;
111629     pParse->pZombieTab = p->pNextZombie;
111630     sqlcipher3DeleteTable(db, p);
111631   }
111632   if( nErr>0 && pParse->rc==SQLCIPHER_OK ){
111633     pParse->rc = SQLCIPHER_ERROR;
111634   }
111635   return nErr;
111636 }
111637
111638 /************** End of tokenize.c ********************************************/
111639 /************** Begin file complete.c ****************************************/
111640 /*
111641 ** 2001 September 15
111642 **
111643 ** The author disclaims copyright to this source code.  In place of
111644 ** a legal notice, here is a blessing:
111645 **
111646 **    May you do good and not evil.
111647 **    May you find forgiveness for yourself and forgive others.
111648 **    May you share freely, never taking more than you give.
111649 **
111650 *************************************************************************
111651 ** An tokenizer for SQL
111652 **
111653 ** This file contains C code that implements the sqlcipher3_complete() API.
111654 ** This code used to be part of the tokenizer.c source file.  But by
111655 ** separating it out, the code will be automatically omitted from
111656 ** static links that do not use it.
111657 */
111658 #ifndef SQLCIPHER_OMIT_COMPLETE
111659
111660 /*
111661 ** This is defined in tokenize.c.  We just have to import the definition.
111662 */
111663 #ifndef SQLCIPHER_AMALGAMATION
111664 #ifdef SQLCIPHER_ASCII
111665 #define IdChar(C)  ((sqlcipher3CtypeMap[(unsigned char)C]&0x46)!=0)
111666 #endif
111667 #ifdef SQLCIPHER_EBCDIC
111668 SQLCIPHER_PRIVATE const char sqlcipher3IsEbcdicIdChar[];
111669 #define IdChar(C)  (((c=C)>=0x42 && sqlcipher3IsEbcdicIdChar[c-0x40]))
111670 #endif
111671 #endif /* SQLCIPHER_AMALGAMATION */
111672
111673
111674 /*
111675 ** Token types used by the sqlcipher3_complete() routine.  See the header
111676 ** comments on that procedure for additional information.
111677 */
111678 #define tkSEMI    0
111679 #define tkWS      1
111680 #define tkOTHER   2
111681 #ifndef SQLCIPHER_OMIT_TRIGGER
111682 #define tkEXPLAIN 3
111683 #define tkCREATE  4
111684 #define tkTEMP    5
111685 #define tkTRIGGER 6
111686 #define tkEND     7
111687 #endif
111688
111689 /*
111690 ** Return TRUE if the given SQL string ends in a semicolon.
111691 **
111692 ** Special handling is require for CREATE TRIGGER statements.
111693 ** Whenever the CREATE TRIGGER keywords are seen, the statement
111694 ** must end with ";END;".
111695 **
111696 ** This implementation uses a state machine with 8 states:
111697 **
111698 **   (0) INVALID   We have not yet seen a non-whitespace character.
111699 **
111700 **   (1) START     At the beginning or end of an SQL statement.  This routine
111701 **                 returns 1 if it ends in the START state and 0 if it ends
111702 **                 in any other state.
111703 **
111704 **   (2) NORMAL    We are in the middle of statement which ends with a single
111705 **                 semicolon.
111706 **
111707 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
111708 **                 a statement.
111709 **
111710 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
111711 **                 statement, possibly preceeded by EXPLAIN and/or followed by
111712 **                 TEMP or TEMPORARY
111713 **
111714 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
111715 **                 ended by a semicolon, the keyword END, and another semicolon.
111716 **
111717 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
111718 **                 the end of a trigger definition.
111719 **
111720 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
111721 **                 of a trigger difinition.
111722 **
111723 ** Transitions between states above are determined by tokens extracted
111724 ** from the input.  The following tokens are significant:
111725 **
111726 **   (0) tkSEMI      A semicolon.
111727 **   (1) tkWS        Whitespace.
111728 **   (2) tkOTHER     Any other SQL token.
111729 **   (3) tkEXPLAIN   The "explain" keyword.
111730 **   (4) tkCREATE    The "create" keyword.
111731 **   (5) tkTEMP      The "temp" or "temporary" keyword.
111732 **   (6) tkTRIGGER   The "trigger" keyword.
111733 **   (7) tkEND       The "end" keyword.
111734 **
111735 ** Whitespace never causes a state transition and is always ignored.
111736 ** This means that a SQL string of all whitespace is invalid.
111737 **
111738 ** If we compile with SQLCIPHER_OMIT_TRIGGER, all of the computation needed
111739 ** to recognize the end of a trigger can be omitted.  All we have to do
111740 ** is look for a semicolon that is not part of an string or comment.
111741 */
111742 SQLCIPHER_API int sqlcipher3_complete(const char *zSql){
111743   u8 state = 0;   /* Current state, using numbers defined in header comment */
111744   u8 token;       /* Value of the next token */
111745
111746 #ifndef SQLCIPHER_OMIT_TRIGGER
111747   /* A complex statement machine used to detect the end of a CREATE TRIGGER
111748   ** statement.  This is the normal case.
111749   */
111750   static const u8 trans[8][8] = {
111751                      /* Token:                                                */
111752      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
111753      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
111754      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
111755      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
111756      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
111757      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
111758      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
111759      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
111760      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
111761   };
111762 #else
111763   /* If triggers are not supported by this compile then the statement machine
111764   ** used to detect the end of a statement is much simplier
111765   */
111766   static const u8 trans[3][3] = {
111767                      /* Token:           */
111768      /* State:       **  SEMI  WS  OTHER */
111769      /* 0 INVALID: */ {    1,  0,     2, },
111770      /* 1   START: */ {    1,  1,     2, },
111771      /* 2  NORMAL: */ {    1,  2,     2, },
111772   };
111773 #endif /* SQLCIPHER_OMIT_TRIGGER */
111774
111775   while( *zSql ){
111776     switch( *zSql ){
111777       case ';': {  /* A semicolon */
111778         token = tkSEMI;
111779         break;
111780       }
111781       case ' ':
111782       case '\r':
111783       case '\t':
111784       case '\n':
111785       case '\f': {  /* White space is ignored */
111786         token = tkWS;
111787         break;
111788       }
111789       case '/': {   /* C-style comments */
111790         if( zSql[1]!='*' ){
111791           token = tkOTHER;
111792           break;
111793         }
111794         zSql += 2;
111795         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
111796         if( zSql[0]==0 ) return 0;
111797         zSql++;
111798         token = tkWS;
111799         break;
111800       }
111801       case '-': {   /* SQL-style comments from "--" to end of line */
111802         if( zSql[1]!='-' ){
111803           token = tkOTHER;
111804           break;
111805         }
111806         while( *zSql && *zSql!='\n' ){ zSql++; }
111807         if( *zSql==0 ) return state==1;
111808         token = tkWS;
111809         break;
111810       }
111811       case '[': {   /* Microsoft-style identifiers in [...] */
111812         zSql++;
111813         while( *zSql && *zSql!=']' ){ zSql++; }
111814         if( *zSql==0 ) return 0;
111815         token = tkOTHER;
111816         break;
111817       }
111818       case '`':     /* Grave-accent quoted symbols used by MySQL */
111819       case '"':     /* single- and double-quoted strings */
111820       case '\'': {
111821         int c = *zSql;
111822         zSql++;
111823         while( *zSql && *zSql!=c ){ zSql++; }
111824         if( *zSql==0 ) return 0;
111825         token = tkOTHER;
111826         break;
111827       }
111828       default: {
111829 #ifdef SQLCIPHER_EBCDIC
111830         unsigned char c;
111831 #endif
111832         if( IdChar((u8)*zSql) ){
111833           /* Keywords and unquoted identifiers */
111834           int nId;
111835           for(nId=1; IdChar(zSql[nId]); nId++){}
111836 #ifdef SQLCIPHER_OMIT_TRIGGER
111837           token = tkOTHER;
111838 #else
111839           switch( *zSql ){
111840             case 'c': case 'C': {
111841               if( nId==6 && sqlcipher3StrNICmp(zSql, "create", 6)==0 ){
111842                 token = tkCREATE;
111843               }else{
111844                 token = tkOTHER;
111845               }
111846               break;
111847             }
111848             case 't': case 'T': {
111849               if( nId==7 && sqlcipher3StrNICmp(zSql, "trigger", 7)==0 ){
111850                 token = tkTRIGGER;
111851               }else if( nId==4 && sqlcipher3StrNICmp(zSql, "temp", 4)==0 ){
111852                 token = tkTEMP;
111853               }else if( nId==9 && sqlcipher3StrNICmp(zSql, "temporary", 9)==0 ){
111854                 token = tkTEMP;
111855               }else{
111856                 token = tkOTHER;
111857               }
111858               break;
111859             }
111860             case 'e':  case 'E': {
111861               if( nId==3 && sqlcipher3StrNICmp(zSql, "end", 3)==0 ){
111862                 token = tkEND;
111863               }else
111864 #ifndef SQLCIPHER_OMIT_EXPLAIN
111865               if( nId==7 && sqlcipher3StrNICmp(zSql, "explain", 7)==0 ){
111866                 token = tkEXPLAIN;
111867               }else
111868 #endif
111869               {
111870                 token = tkOTHER;
111871               }
111872               break;
111873             }
111874             default: {
111875               token = tkOTHER;
111876               break;
111877             }
111878           }
111879 #endif /* SQLCIPHER_OMIT_TRIGGER */
111880           zSql += nId-1;
111881         }else{
111882           /* Operators and special symbols */
111883           token = tkOTHER;
111884         }
111885         break;
111886       }
111887     }
111888     state = trans[state][token];
111889     zSql++;
111890   }
111891   return state==1;
111892 }
111893
111894 #ifndef SQLCIPHER_OMIT_UTF16
111895 /*
111896 ** This routine is the same as the sqlcipher3_complete() routine described
111897 ** above, except that the parameter is required to be UTF-16 encoded, not
111898 ** UTF-8.
111899 */
111900 SQLCIPHER_API int sqlcipher3_complete16(const void *zSql){
111901   sqlcipher3_value *pVal;
111902   char const *zSql8;
111903   int rc = SQLCIPHER_NOMEM;
111904
111905 #ifndef SQLCIPHER_OMIT_AUTOINIT
111906   rc = sqlcipher3_initialize();
111907   if( rc ) return rc;
111908 #endif
111909   pVal = sqlcipher3ValueNew(0);
111910   sqlcipher3ValueSetStr(pVal, -1, zSql, SQLCIPHER_UTF16NATIVE, SQLCIPHER_STATIC);
111911   zSql8 = sqlcipher3ValueText(pVal, SQLCIPHER_UTF8);
111912   if( zSql8 ){
111913     rc = sqlcipher3_complete(zSql8);
111914   }else{
111915     rc = SQLCIPHER_NOMEM;
111916   }
111917   sqlcipher3ValueFree(pVal);
111918   return sqlcipher3ApiExit(0, rc);
111919 }
111920 #endif /* SQLCIPHER_OMIT_UTF16 */
111921 #endif /* SQLCIPHER_OMIT_COMPLETE */
111922
111923 /************** End of complete.c ********************************************/
111924 /************** Begin file main.c ********************************************/
111925 /*
111926 ** 2001 September 15
111927 **
111928 ** The author disclaims copyright to this source code.  In place of
111929 ** a legal notice, here is a blessing:
111930 **
111931 **    May you do good and not evil.
111932 **    May you find forgiveness for yourself and forgive others.
111933 **    May you share freely, never taking more than you give.
111934 **
111935 *************************************************************************
111936 ** Main file for the SQLite library.  The routines in this file
111937 ** implement the programmer interface to the library.  Routines in
111938 ** other files are for internal use by SQLite and should not be
111939 ** accessed by users of the library.
111940 */
111941
111942 #ifdef SQLCIPHER_ENABLE_FTS3
111943 /************** Include fts3.h in the middle of main.c ***********************/
111944 /************** Begin file fts3.h ********************************************/
111945 /*
111946 ** 2006 Oct 10
111947 **
111948 ** The author disclaims copyright to this source code.  In place of
111949 ** a legal notice, here is a blessing:
111950 **
111951 **    May you do good and not evil.
111952 **    May you find forgiveness for yourself and forgive others.
111953 **    May you share freely, never taking more than you give.
111954 **
111955 ******************************************************************************
111956 **
111957 ** This header file is used by programs that want to link against the
111958 ** FTS3 library.  All it does is declare the sqlcipher3Fts3Init() interface.
111959 */
111960
111961 #if 0
111962 extern "C" {
111963 #endif  /* __cplusplus */
111964
111965 SQLCIPHER_PRIVATE int sqlcipher3Fts3Init(sqlcipher3 *db);
111966
111967 #if 0
111968 }  /* extern "C" */
111969 #endif  /* __cplusplus */
111970
111971 /************** End of fts3.h ************************************************/
111972 /************** Continuing where we left off in main.c ***********************/
111973 #endif
111974 #ifdef SQLCIPHER_ENABLE_RTREE
111975 /************** Include rtree.h in the middle of main.c **********************/
111976 /************** Begin file rtree.h *******************************************/
111977 /*
111978 ** 2008 May 26
111979 **
111980 ** The author disclaims copyright to this source code.  In place of
111981 ** a legal notice, here is a blessing:
111982 **
111983 **    May you do good and not evil.
111984 **    May you find forgiveness for yourself and forgive others.
111985 **    May you share freely, never taking more than you give.
111986 **
111987 ******************************************************************************
111988 **
111989 ** This header file is used by programs that want to link against the
111990 ** RTREE library.  All it does is declare the sqlcipher3RtreeInit() interface.
111991 */
111992
111993 #if 0
111994 extern "C" {
111995 #endif  /* __cplusplus */
111996
111997 SQLCIPHER_PRIVATE int sqlcipher3RtreeInit(sqlcipher3 *db);
111998
111999 #if 0
112000 }  /* extern "C" */
112001 #endif  /* __cplusplus */
112002
112003 /************** End of rtree.h ***********************************************/
112004 /************** Continuing where we left off in main.c ***********************/
112005 #endif
112006 #ifdef SQLCIPHER_ENABLE_ICU
112007 /************** Include sqlciphericu.h in the middle of main.c ******************/
112008 /************** Begin file sqlciphericu.h ***************************************/
112009 /*
112010 ** 2008 May 26
112011 **
112012 ** The author disclaims copyright to this source code.  In place of
112013 ** a legal notice, here is a blessing:
112014 **
112015 **    May you do good and not evil.
112016 **    May you find forgiveness for yourself and forgive others.
112017 **    May you share freely, never taking more than you give.
112018 **
112019 ******************************************************************************
112020 **
112021 ** This header file is used by programs that want to link against the
112022 ** ICU extension.  All it does is declare the sqlcipher3IcuInit() interface.
112023 */
112024
112025 #if 0
112026 extern "C" {
112027 #endif  /* __cplusplus */
112028
112029 SQLCIPHER_PRIVATE int sqlcipher3IcuInit(sqlcipher3 *db);
112030
112031 #if 0
112032 }  /* extern "C" */
112033 #endif  /* __cplusplus */
112034
112035
112036 /************** End of sqlciphericu.h *******************************************/
112037 /************** Continuing where we left off in main.c ***********************/
112038 #endif
112039
112040 #ifndef SQLCIPHER_AMALGAMATION
112041 /* IMPLEMENTATION-OF: R-46656-45156 The sqlcipher3_version[] string constant
112042 ** contains the text of SQLCIPHER_VERSION macro. 
112043 */
112044 SQLCIPHER_API const char sqlcipher3_version[] = SQLCIPHER_VERSION;
112045 #endif
112046
112047 /* IMPLEMENTATION-OF: R-53536-42575 The sqlcipher3_libversion() function returns
112048 ** a pointer to the to the sqlcipher3_version[] string constant. 
112049 */
112050 SQLCIPHER_API const char *sqlcipher3_libversion(void){ return sqlcipher3_version; }
112051
112052 /* IMPLEMENTATION-OF: R-63124-39300 The sqlcipher3_sourceid() function returns a
112053 ** pointer to a string constant whose value is the same as the
112054 ** SQLCIPHER_SOURCE_ID C preprocessor macro. 
112055 */
112056 SQLCIPHER_API const char *sqlcipher3_sourceid(void){ return SQLCIPHER_SOURCE_ID; }
112057
112058 /* IMPLEMENTATION-OF: R-35210-63508 The sqlcipher3_libversion_number() function
112059 ** returns an integer equal to SQLCIPHER_VERSION_NUMBER.
112060 */
112061 SQLCIPHER_API int sqlcipher3_libversion_number(void){ return SQLCIPHER_VERSION_NUMBER; }
112062
112063 /* IMPLEMENTATION-OF: R-54823-41343 The sqlcipher3_threadsafe() function returns
112064 ** zero if and only if SQLite was compiled mutexing code omitted due to
112065 ** the SQLCIPHER_THREADSAFE compile-time option being set to 0.
112066 */
112067 SQLCIPHER_API int sqlcipher3_threadsafe(void){ return SQLCIPHER_THREADSAFE; }
112068
112069 #if !defined(SQLCIPHER_OMIT_TRACE) && defined(SQLCIPHER_ENABLE_IOTRACE)
112070 /*
112071 ** If the following function pointer is not NULL and if
112072 ** SQLCIPHER_ENABLE_IOTRACE is enabled, then messages describing
112073 ** I/O active are written using this function.  These messages
112074 ** are intended for debugging activity only.
112075 */
112076 SQLCIPHER_PRIVATE void (*sqlcipher3IoTrace)(const char*, ...) = 0;
112077 #endif
112078
112079 /*
112080 ** If the following global variable points to a string which is the
112081 ** name of a directory, then that directory will be used to store
112082 ** temporary files.
112083 **
112084 ** See also the "PRAGMA temp_store_directory" SQL command.
112085 */
112086 SQLCIPHER_API char *sqlcipher3_temp_directory = 0;
112087
112088 /*
112089 ** Initialize SQLite.  
112090 **
112091 ** This routine must be called to initialize the memory allocation,
112092 ** VFS, and mutex subsystems prior to doing any serious work with
112093 ** SQLite.  But as long as you do not compile with SQLCIPHER_OMIT_AUTOINIT
112094 ** this routine will be called automatically by key routines such as
112095 ** sqlcipher3_open().  
112096 **
112097 ** This routine is a no-op except on its very first call for the process,
112098 ** or for the first call after a call to sqlcipher3_shutdown.
112099 **
112100 ** The first thread to call this routine runs the initialization to
112101 ** completion.  If subsequent threads call this routine before the first
112102 ** thread has finished the initialization process, then the subsequent
112103 ** threads must block until the first thread finishes with the initialization.
112104 **
112105 ** The first thread might call this routine recursively.  Recursive
112106 ** calls to this routine should not block, of course.  Otherwise the
112107 ** initialization process would never complete.
112108 **
112109 ** Let X be the first thread to enter this routine.  Let Y be some other
112110 ** thread.  Then while the initial invocation of this routine by X is
112111 ** incomplete, it is required that:
112112 **
112113 **    *  Calls to this routine from Y must block until the outer-most
112114 **       call by X completes.
112115 **
112116 **    *  Recursive calls to this routine from thread X return immediately
112117 **       without blocking.
112118 */
112119 SQLCIPHER_API int sqlcipher3_initialize(void){
112120   MUTEX_LOGIC( sqlcipher3_mutex *pMaster; )       /* The main static mutex */
112121   int rc;                                      /* Result code */
112122
112123 #ifdef SQLCIPHER_OMIT_WSD
112124   rc = sqlcipher3_wsd_init(4096, 24);
112125   if( rc!=SQLCIPHER_OK ){
112126     return rc;
112127   }
112128 #endif
112129
112130   /* If SQLite is already completely initialized, then this call
112131   ** to sqlcipher3_initialize() should be a no-op.  But the initialization
112132   ** must be complete.  So isInit must not be set until the very end
112133   ** of this routine.
112134   */
112135   if( sqlcipher3GlobalConfig.isInit ) return SQLCIPHER_OK;
112136
112137   /* Make sure the mutex subsystem is initialized.  If unable to 
112138   ** initialize the mutex subsystem, return early with the error.
112139   ** If the system is so sick that we are unable to allocate a mutex,
112140   ** there is not much SQLite is going to be able to do.
112141   **
112142   ** The mutex subsystem must take care of serializing its own
112143   ** initialization.
112144   */
112145   rc = sqlcipher3MutexInit();
112146   if( rc ) return rc;
112147
112148   /* Initialize the malloc() system and the recursive pInitMutex mutex.
112149   ** This operation is protected by the STATIC_MASTER mutex.  Note that
112150   ** MutexAlloc() is called for a static mutex prior to initializing the
112151   ** malloc subsystem - this implies that the allocation of a static
112152   ** mutex must not require support from the malloc subsystem.
112153   */
112154   MUTEX_LOGIC( pMaster = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER); )
112155   sqlcipher3_mutex_enter(pMaster);
112156   sqlcipher3GlobalConfig.isMutexInit = 1;
112157   if( !sqlcipher3GlobalConfig.isMallocInit ){
112158     rc = sqlcipher3MallocInit();
112159   }
112160   if( rc==SQLCIPHER_OK ){
112161     sqlcipher3GlobalConfig.isMallocInit = 1;
112162     if( !sqlcipher3GlobalConfig.pInitMutex ){
112163       sqlcipher3GlobalConfig.pInitMutex =
112164            sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_RECURSIVE);
112165       if( sqlcipher3GlobalConfig.bCoreMutex && !sqlcipher3GlobalConfig.pInitMutex ){
112166         rc = SQLCIPHER_NOMEM;
112167       }
112168     }
112169   }
112170   if( rc==SQLCIPHER_OK ){
112171     sqlcipher3GlobalConfig.nRefInitMutex++;
112172   }
112173   sqlcipher3_mutex_leave(pMaster);
112174
112175   /* If rc is not SQLCIPHER_OK at this point, then either the malloc
112176   ** subsystem could not be initialized or the system failed to allocate
112177   ** the pInitMutex mutex. Return an error in either case.  */
112178   if( rc!=SQLCIPHER_OK ){
112179     return rc;
112180   }
112181
112182   /* Do the rest of the initialization under the recursive mutex so
112183   ** that we will be able to handle recursive calls into
112184   ** sqlcipher3_initialize().  The recursive calls normally come through
112185   ** sqlcipher3_os_init() when it invokes sqlcipher3_vfs_register(), but other
112186   ** recursive calls might also be possible.
112187   **
112188   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
112189   ** to the xInit method, so the xInit method need not be threadsafe.
112190   **
112191   ** The following mutex is what serializes access to the appdef pcache xInit
112192   ** methods.  The sqlcipher3_pcache_methods.xInit() all is embedded in the
112193   ** call to sqlcipher3PcacheInitialize().
112194   */
112195   sqlcipher3_mutex_enter(sqlcipher3GlobalConfig.pInitMutex);
112196   if( sqlcipher3GlobalConfig.isInit==0 && sqlcipher3GlobalConfig.inProgress==0 ){
112197     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlcipher3GlobalFunctions);
112198     sqlcipher3GlobalConfig.inProgress = 1;
112199     memset(pHash, 0, sizeof(sqlcipher3GlobalFunctions));
112200     sqlcipher3RegisterGlobalFunctions();
112201     if( sqlcipher3GlobalConfig.isPCacheInit==0 ){
112202       rc = sqlcipher3PcacheInitialize();
112203     }
112204     if( rc==SQLCIPHER_OK ){
112205       sqlcipher3GlobalConfig.isPCacheInit = 1;
112206       rc = sqlcipher3OsInit();
112207     }
112208     if( rc==SQLCIPHER_OK ){
112209       sqlcipher3PCacheBufferSetup( sqlcipher3GlobalConfig.pPage, 
112210           sqlcipher3GlobalConfig.szPage, sqlcipher3GlobalConfig.nPage);
112211       sqlcipher3GlobalConfig.isInit = 1;
112212     }
112213     sqlcipher3GlobalConfig.inProgress = 0;
112214   }
112215   sqlcipher3_mutex_leave(sqlcipher3GlobalConfig.pInitMutex);
112216
112217   /* Go back under the static mutex and clean up the recursive
112218   ** mutex to prevent a resource leak.
112219   */
112220   sqlcipher3_mutex_enter(pMaster);
112221   sqlcipher3GlobalConfig.nRefInitMutex--;
112222   if( sqlcipher3GlobalConfig.nRefInitMutex<=0 ){
112223     assert( sqlcipher3GlobalConfig.nRefInitMutex==0 );
112224     sqlcipher3_mutex_free(sqlcipher3GlobalConfig.pInitMutex);
112225     sqlcipher3GlobalConfig.pInitMutex = 0;
112226   }
112227   sqlcipher3_mutex_leave(pMaster);
112228
112229   /* The following is just a sanity check to make sure SQLite has
112230   ** been compiled correctly.  It is important to run this code, but
112231   ** we don't want to run it too often and soak up CPU cycles for no
112232   ** reason.  So we run it once during initialization.
112233   */
112234 #ifndef NDEBUG
112235 #ifndef SQLCIPHER_OMIT_FLOATING_POINT
112236   /* This section of code's only "output" is via assert() statements. */
112237   if ( rc==SQLCIPHER_OK ){
112238     u64 x = (((u64)1)<<63)-1;
112239     double y;
112240     assert(sizeof(x)==8);
112241     assert(sizeof(x)==sizeof(y));
112242     memcpy(&y, &x, 8);
112243     assert( sqlcipher3IsNaN(y) );
112244   }
112245 #endif
112246 #endif
112247
112248   /* Do extra initialization steps requested by the SQLCIPHER_EXTRA_INIT
112249   ** compile-time option.
112250   */
112251 #ifdef SQLCIPHER_EXTRA_INIT
112252   if( rc==SQLCIPHER_OK && sqlcipher3GlobalConfig.isInit ){
112253     int SQLCIPHER_EXTRA_INIT(void);
112254     rc = SQLCIPHER_EXTRA_INIT();
112255   }
112256 #endif
112257
112258   return rc;
112259 }
112260
112261 /*
112262 ** Undo the effects of sqlcipher3_initialize().  Must not be called while
112263 ** there are outstanding database connections or memory allocations or
112264 ** while any part of SQLite is otherwise in use in any thread.  This
112265 ** routine is not threadsafe.  But it is safe to invoke this routine
112266 ** on when SQLite is already shut down.  If SQLite is already shut down
112267 ** when this routine is invoked, then this routine is a harmless no-op.
112268 */
112269 SQLCIPHER_API int sqlcipher3_shutdown(void){
112270   if( sqlcipher3GlobalConfig.isInit ){
112271     sqlcipher3_os_end();
112272     sqlcipher3_reset_auto_extension();
112273     sqlcipher3GlobalConfig.isInit = 0;
112274   }
112275   if( sqlcipher3GlobalConfig.isPCacheInit ){
112276     sqlcipher3PcacheShutdown();
112277     sqlcipher3GlobalConfig.isPCacheInit = 0;
112278   }
112279   if( sqlcipher3GlobalConfig.isMallocInit ){
112280     sqlcipher3MallocEnd();
112281     sqlcipher3GlobalConfig.isMallocInit = 0;
112282   }
112283   if( sqlcipher3GlobalConfig.isMutexInit ){
112284     sqlcipher3MutexEnd();
112285     sqlcipher3GlobalConfig.isMutexInit = 0;
112286   }
112287
112288   return SQLCIPHER_OK;
112289 }
112290
112291 /*
112292 ** This API allows applications to modify the global configuration of
112293 ** the SQLite library at run-time.
112294 **
112295 ** This routine should only be called when there are no outstanding
112296 ** database connections or memory allocations.  This routine is not
112297 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
112298 ** behavior.
112299 */
112300 SQLCIPHER_API int sqlcipher3_config(int op, ...){
112301   va_list ap;
112302   int rc = SQLCIPHER_OK;
112303
112304   /* sqlcipher3_config() shall return SQLCIPHER_MISUSE if it is invoked while
112305   ** the SQLite library is in use. */
112306   if( sqlcipher3GlobalConfig.isInit ) return SQLCIPHER_MISUSE_BKPT;
112307
112308   va_start(ap, op);
112309   switch( op ){
112310
112311     /* Mutex configuration options are only available in a threadsafe
112312     ** compile. 
112313     */
112314 #if defined(SQLCIPHER_THREADSAFE) && SQLCIPHER_THREADSAFE>0
112315     case SQLCIPHER_CONFIG_SINGLETHREAD: {
112316       /* Disable all mutexing */
112317       sqlcipher3GlobalConfig.bCoreMutex = 0;
112318       sqlcipher3GlobalConfig.bFullMutex = 0;
112319       break;
112320     }
112321     case SQLCIPHER_CONFIG_MULTITHREAD: {
112322       /* Disable mutexing of database connections */
112323       /* Enable mutexing of core data structures */
112324       sqlcipher3GlobalConfig.bCoreMutex = 1;
112325       sqlcipher3GlobalConfig.bFullMutex = 0;
112326       break;
112327     }
112328     case SQLCIPHER_CONFIG_SERIALIZED: {
112329       /* Enable all mutexing */
112330       sqlcipher3GlobalConfig.bCoreMutex = 1;
112331       sqlcipher3GlobalConfig.bFullMutex = 1;
112332       break;
112333     }
112334     case SQLCIPHER_CONFIG_MUTEX: {
112335       /* Specify an alternative mutex implementation */
112336       sqlcipher3GlobalConfig.mutex = *va_arg(ap, sqlcipher3_mutex_methods*);
112337       break;
112338     }
112339     case SQLCIPHER_CONFIG_GETMUTEX: {
112340       /* Retrieve the current mutex implementation */
112341       *va_arg(ap, sqlcipher3_mutex_methods*) = sqlcipher3GlobalConfig.mutex;
112342       break;
112343     }
112344 #endif
112345
112346
112347     case SQLCIPHER_CONFIG_MALLOC: {
112348       /* Specify an alternative malloc implementation */
112349       sqlcipher3GlobalConfig.m = *va_arg(ap, sqlcipher3_mem_methods*);
112350       break;
112351     }
112352     case SQLCIPHER_CONFIG_GETMALLOC: {
112353       /* Retrieve the current malloc() implementation */
112354       if( sqlcipher3GlobalConfig.m.xMalloc==0 ) sqlcipher3MemSetDefault();
112355       *va_arg(ap, sqlcipher3_mem_methods*) = sqlcipher3GlobalConfig.m;
112356       break;
112357     }
112358     case SQLCIPHER_CONFIG_MEMSTATUS: {
112359       /* Enable or disable the malloc status collection */
112360       sqlcipher3GlobalConfig.bMemstat = va_arg(ap, int);
112361       break;
112362     }
112363     case SQLCIPHER_CONFIG_SCRATCH: {
112364       /* Designate a buffer for scratch memory space */
112365       sqlcipher3GlobalConfig.pScratch = va_arg(ap, void*);
112366       sqlcipher3GlobalConfig.szScratch = va_arg(ap, int);
112367       sqlcipher3GlobalConfig.nScratch = va_arg(ap, int);
112368       break;
112369     }
112370     case SQLCIPHER_CONFIG_PAGECACHE: {
112371       /* Designate a buffer for page cache memory space */
112372       sqlcipher3GlobalConfig.pPage = va_arg(ap, void*);
112373       sqlcipher3GlobalConfig.szPage = va_arg(ap, int);
112374       sqlcipher3GlobalConfig.nPage = va_arg(ap, int);
112375       break;
112376     }
112377
112378     case SQLCIPHER_CONFIG_PCACHE: {
112379       /* Specify an alternative page cache implementation */
112380       sqlcipher3GlobalConfig.pcache = *va_arg(ap, sqlcipher3_pcache_methods*);
112381       break;
112382     }
112383
112384     case SQLCIPHER_CONFIG_GETPCACHE: {
112385       if( sqlcipher3GlobalConfig.pcache.xInit==0 ){
112386         sqlcipher3PCacheSetDefault();
112387       }
112388       *va_arg(ap, sqlcipher3_pcache_methods*) = sqlcipher3GlobalConfig.pcache;
112389       break;
112390     }
112391
112392 #if defined(SQLCIPHER_ENABLE_MEMSYS3) || defined(SQLCIPHER_ENABLE_MEMSYS5)
112393     case SQLCIPHER_CONFIG_HEAP: {
112394       /* Designate a buffer for heap memory space */
112395       sqlcipher3GlobalConfig.pHeap = va_arg(ap, void*);
112396       sqlcipher3GlobalConfig.nHeap = va_arg(ap, int);
112397       sqlcipher3GlobalConfig.mnReq = va_arg(ap, int);
112398
112399       if( sqlcipher3GlobalConfig.mnReq<1 ){
112400         sqlcipher3GlobalConfig.mnReq = 1;
112401       }else if( sqlcipher3GlobalConfig.mnReq>(1<<12) ){
112402         /* cap min request size at 2^12 */
112403         sqlcipher3GlobalConfig.mnReq = (1<<12);
112404       }
112405
112406       if( sqlcipher3GlobalConfig.pHeap==0 ){
112407         /* If the heap pointer is NULL, then restore the malloc implementation
112408         ** back to NULL pointers too.  This will cause the malloc to go
112409         ** back to its default implementation when sqlcipher3_initialize() is
112410         ** run.
112411         */
112412         memset(&sqlcipher3GlobalConfig.m, 0, sizeof(sqlcipher3GlobalConfig.m));
112413       }else{
112414         /* The heap pointer is not NULL, then install one of the
112415         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
112416         ** ENABLE_MEMSYS5 is defined, return an error.
112417         */
112418 #ifdef SQLCIPHER_ENABLE_MEMSYS3
112419         sqlcipher3GlobalConfig.m = *sqlcipher3MemGetMemsys3();
112420 #endif
112421 #ifdef SQLCIPHER_ENABLE_MEMSYS5
112422         sqlcipher3GlobalConfig.m = *sqlcipher3MemGetMemsys5();
112423 #endif
112424       }
112425       break;
112426     }
112427 #endif
112428
112429     case SQLCIPHER_CONFIG_LOOKASIDE: {
112430       sqlcipher3GlobalConfig.szLookaside = va_arg(ap, int);
112431       sqlcipher3GlobalConfig.nLookaside = va_arg(ap, int);
112432       break;
112433     }
112434     
112435     /* Record a pointer to the logger funcction and its first argument.
112436     ** The default is NULL.  Logging is disabled if the function pointer is
112437     ** NULL.
112438     */
112439     case SQLCIPHER_CONFIG_LOG: {
112440       /* MSVC is picky about pulling func ptrs from va lists.
112441       ** http://support.microsoft.com/kb/47961
112442       ** sqlcipher3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
112443       */
112444       typedef void(*LOGFUNC_t)(void*,int,const char*);
112445       sqlcipher3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
112446       sqlcipher3GlobalConfig.pLogArg = va_arg(ap, void*);
112447       break;
112448     }
112449
112450     case SQLCIPHER_CONFIG_URI: {
112451       sqlcipher3GlobalConfig.bOpenUri = va_arg(ap, int);
112452       break;
112453     }
112454
112455     default: {
112456       rc = SQLCIPHER_ERROR;
112457       break;
112458     }
112459   }
112460   va_end(ap);
112461   return rc;
112462 }
112463
112464 /*
112465 ** Set up the lookaside buffers for a database connection.
112466 ** Return SQLCIPHER_OK on success.  
112467 ** If lookaside is already active, return SQLCIPHER_BUSY.
112468 **
112469 ** The sz parameter is the number of bytes in each lookaside slot.
112470 ** The cnt parameter is the number of slots.  If pStart is NULL the
112471 ** space for the lookaside memory is obtained from sqlcipher3_malloc().
112472 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
112473 ** the lookaside memory.
112474 */
112475 static int setupLookaside(sqlcipher3 *db, void *pBuf, int sz, int cnt){
112476   void *pStart;
112477   if( db->lookaside.nOut ){
112478     return SQLCIPHER_BUSY;
112479   }
112480   /* Free any existing lookaside buffer for this handle before
112481   ** allocating a new one so we don't have to have space for 
112482   ** both at the same time.
112483   */
112484   if( db->lookaside.bMalloced ){
112485     sqlcipher3_free(db->lookaside.pStart);
112486   }
112487   /* The size of a lookaside slot needs to be larger than a pointer
112488   ** to be useful.
112489   */
112490   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
112491   if( cnt<0 ) cnt = 0;
112492   if( sz==0 || cnt==0 ){
112493     sz = 0;
112494     pStart = 0;
112495   }else if( pBuf==0 ){
112496     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
112497     sqlcipher3BeginBenignMalloc();
112498     pStart = sqlcipher3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
112499     sqlcipher3EndBenignMalloc();
112500   }else{
112501     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
112502     pStart = pBuf;
112503   }
112504   db->lookaside.pStart = pStart;
112505   db->lookaside.pFree = 0;
112506   db->lookaside.sz = (u16)sz;
112507   if( pStart ){
112508     int i;
112509     LookasideSlot *p;
112510     assert( sz > (int)sizeof(LookasideSlot*) );
112511     p = (LookasideSlot*)pStart;
112512     for(i=cnt-1; i>=0; i--){
112513       p->pNext = db->lookaside.pFree;
112514       db->lookaside.pFree = p;
112515       p = (LookasideSlot*)&((u8*)p)[sz];
112516     }
112517     db->lookaside.pEnd = p;
112518     db->lookaside.bEnabled = 1;
112519     db->lookaside.bMalloced = pBuf==0 ?1:0;
112520   }else{
112521     db->lookaside.pEnd = 0;
112522     db->lookaside.bEnabled = 0;
112523     db->lookaside.bMalloced = 0;
112524   }
112525   return SQLCIPHER_OK;
112526 }
112527
112528 /*
112529 ** Return the mutex associated with a database connection.
112530 */
112531 SQLCIPHER_API sqlcipher3_mutex *sqlcipher3_db_mutex(sqlcipher3 *db){
112532   return db->mutex;
112533 }
112534
112535 /*
112536 ** Configuration settings for an individual database connection
112537 */
112538 SQLCIPHER_API int sqlcipher3_db_config(sqlcipher3 *db, int op, ...){
112539   va_list ap;
112540   int rc;
112541   va_start(ap, op);
112542   switch( op ){
112543     case SQLCIPHER_DBCONFIG_LOOKASIDE: {
112544       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
112545       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
112546       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
112547       rc = setupLookaside(db, pBuf, sz, cnt);
112548       break;
112549     }
112550     default: {
112551       static const struct {
112552         int op;      /* The opcode */
112553         u32 mask;    /* Mask of the bit in sqlcipher3.flags to set/clear */
112554       } aFlagOp[] = {
112555         { SQLCIPHER_DBCONFIG_ENABLE_FKEY,    SQLCIPHER_ForeignKeys    },
112556         { SQLCIPHER_DBCONFIG_ENABLE_TRIGGER, SQLCIPHER_EnableTrigger  },
112557       };
112558       unsigned int i;
112559       rc = SQLCIPHER_ERROR; /* IMP: R-42790-23372 */
112560       for(i=0; i<ArraySize(aFlagOp); i++){
112561         if( aFlagOp[i].op==op ){
112562           int onoff = va_arg(ap, int);
112563           int *pRes = va_arg(ap, int*);
112564           int oldFlags = db->flags;
112565           if( onoff>0 ){
112566             db->flags |= aFlagOp[i].mask;
112567           }else if( onoff==0 ){
112568             db->flags &= ~aFlagOp[i].mask;
112569           }
112570           if( oldFlags!=db->flags ){
112571             sqlcipher3ExpirePreparedStatements(db);
112572           }
112573           if( pRes ){
112574             *pRes = (db->flags & aFlagOp[i].mask)!=0;
112575           }
112576           rc = SQLCIPHER_OK;
112577           break;
112578         }
112579       }
112580       break;
112581     }
112582   }
112583   va_end(ap);
112584   return rc;
112585 }
112586
112587
112588 /*
112589 ** Return true if the buffer z[0..n-1] contains all spaces.
112590 */
112591 static int allSpaces(const char *z, int n){
112592   while( n>0 && z[n-1]==' ' ){ n--; }
112593   return n==0;
112594 }
112595
112596 /*
112597 ** This is the default collating function named "BINARY" which is always
112598 ** available.
112599 **
112600 ** If the padFlag argument is not NULL then space padding at the end
112601 ** of strings is ignored.  This implements the RTRIM collation.
112602 */
112603 static int binCollFunc(
112604   void *padFlag,
112605   int nKey1, const void *pKey1,
112606   int nKey2, const void *pKey2
112607 ){
112608   int rc, n;
112609   n = nKey1<nKey2 ? nKey1 : nKey2;
112610   rc = memcmp(pKey1, pKey2, n);
112611   if( rc==0 ){
112612     if( padFlag
112613      && allSpaces(((char*)pKey1)+n, nKey1-n)
112614      && allSpaces(((char*)pKey2)+n, nKey2-n)
112615     ){
112616       /* Leave rc unchanged at 0 */
112617     }else{
112618       rc = nKey1 - nKey2;
112619     }
112620   }
112621   return rc;
112622 }
112623
112624 /*
112625 ** Another built-in collating sequence: NOCASE. 
112626 **
112627 ** This collating sequence is intended to be used for "case independant
112628 ** comparison". SQLite's knowledge of upper and lower case equivalents
112629 ** extends only to the 26 characters used in the English language.
112630 **
112631 ** At the moment there is only a UTF-8 implementation.
112632 */
112633 static int nocaseCollatingFunc(
112634   void *NotUsed,
112635   int nKey1, const void *pKey1,
112636   int nKey2, const void *pKey2
112637 ){
112638   int r = sqlcipher3StrNICmp(
112639       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
112640   UNUSED_PARAMETER(NotUsed);
112641   if( 0==r ){
112642     r = nKey1-nKey2;
112643   }
112644   return r;
112645 }
112646
112647 /*
112648 ** Return the ROWID of the most recent insert
112649 */
112650 SQLCIPHER_API sqlcipher_int64 sqlcipher3_last_insert_rowid(sqlcipher3 *db){
112651   return db->lastRowid;
112652 }
112653
112654 /*
112655 ** Return the number of changes in the most recent call to sqlcipher3_exec().
112656 */
112657 SQLCIPHER_API int sqlcipher3_changes(sqlcipher3 *db){
112658   return db->nChange;
112659 }
112660
112661 /*
112662 ** Return the number of changes since the database handle was opened.
112663 */
112664 SQLCIPHER_API int sqlcipher3_total_changes(sqlcipher3 *db){
112665   return db->nTotalChange;
112666 }
112667
112668 /*
112669 ** Close all open savepoints. This function only manipulates fields of the
112670 ** database handle object, it does not close any savepoints that may be open
112671 ** at the b-tree/pager level.
112672 */
112673 SQLCIPHER_PRIVATE void sqlcipher3CloseSavepoints(sqlcipher3 *db){
112674   while( db->pSavepoint ){
112675     Savepoint *pTmp = db->pSavepoint;
112676     db->pSavepoint = pTmp->pNext;
112677     sqlcipher3DbFree(db, pTmp);
112678   }
112679   db->nSavepoint = 0;
112680   db->nStatement = 0;
112681   db->isTransactionSavepoint = 0;
112682 }
112683
112684 /*
112685 ** Invoke the destructor function associated with FuncDef p, if any. Except,
112686 ** if this is not the last copy of the function, do not invoke it. Multiple
112687 ** copies of a single function are created when create_function() is called
112688 ** with SQLCIPHER_ANY as the encoding.
112689 */
112690 static void functionDestroy(sqlcipher3 *db, FuncDef *p){
112691   FuncDestructor *pDestructor = p->pDestructor;
112692   if( pDestructor ){
112693     pDestructor->nRef--;
112694     if( pDestructor->nRef==0 ){
112695       pDestructor->xDestroy(pDestructor->pUserData);
112696       sqlcipher3DbFree(db, pDestructor);
112697     }
112698   }
112699 }
112700
112701 /*
112702 ** Close an existing SQLite database
112703 */
112704 SQLCIPHER_API int sqlcipher3_close(sqlcipher3 *db){
112705   HashElem *i;                    /* Hash table iterator */
112706   int j;
112707
112708   if( !db ){
112709     return SQLCIPHER_OK;
112710   }
112711   if( !sqlcipher3SafetyCheckSickOrOk(db) ){
112712     return SQLCIPHER_MISUSE_BKPT;
112713   }
112714   sqlcipher3_mutex_enter(db->mutex);
112715
112716   /* Force xDestroy calls on all virtual tables */
112717   sqlcipher3ResetInternalSchema(db, -1);
112718
112719   /* If a transaction is open, the ResetInternalSchema() call above
112720   ** will not have called the xDisconnect() method on any virtual
112721   ** tables in the db->aVTrans[] array. The following sqlcipher3VtabRollback()
112722   ** call will do so. We need to do this before the check for active
112723   ** SQL statements below, as the v-table implementation may be storing
112724   ** some prepared statements internally.
112725   */
112726   sqlcipher3VtabRollback(db);
112727
112728   /* If there are any outstanding VMs, return SQLCIPHER_BUSY. */
112729   if( db->pVdbe ){
112730     sqlcipher3Error(db, SQLCIPHER_BUSY, 
112731         "unable to close due to unfinalised statements");
112732     sqlcipher3_mutex_leave(db->mutex);
112733     return SQLCIPHER_BUSY;
112734   }
112735   assert( sqlcipher3SafetyCheckSickOrOk(db) );
112736
112737   for(j=0; j<db->nDb; j++){
112738     Btree *pBt = db->aDb[j].pBt;
112739     if( pBt && sqlcipher3BtreeIsInBackup(pBt) ){
112740       sqlcipher3Error(db, SQLCIPHER_BUSY, 
112741           "unable to close due to unfinished backup operation");
112742       sqlcipher3_mutex_leave(db->mutex);
112743       return SQLCIPHER_BUSY;
112744     }
112745   }
112746
112747   /* Free any outstanding Savepoint structures. */
112748   sqlcipher3CloseSavepoints(db);
112749
112750   for(j=0; j<db->nDb; j++){
112751     struct Db *pDb = &db->aDb[j];
112752     if( pDb->pBt ){
112753       sqlcipher3BtreeClose(pDb->pBt);
112754       pDb->pBt = 0;
112755       if( j!=1 ){
112756         pDb->pSchema = 0;
112757       }
112758     }
112759   }
112760   sqlcipher3ResetInternalSchema(db, -1);
112761
112762   /* Tell the code in notify.c that the connection no longer holds any
112763   ** locks and does not require any further unlock-notify callbacks.
112764   */
112765   sqlcipher3ConnectionClosed(db);
112766
112767   assert( db->nDb<=2 );
112768   assert( db->aDb==db->aDbStatic );
112769   for(j=0; j<ArraySize(db->aFunc.a); j++){
112770     FuncDef *pNext, *pHash, *p;
112771     for(p=db->aFunc.a[j]; p; p=pHash){
112772       pHash = p->pHash;
112773       while( p ){
112774         functionDestroy(db, p);
112775         pNext = p->pNext;
112776         sqlcipher3DbFree(db, p);
112777         p = pNext;
112778       }
112779     }
112780   }
112781   for(i=sqlcipherHashFirst(&db->aCollSeq); i; i=sqlcipherHashNext(i)){
112782     CollSeq *pColl = (CollSeq *)sqlcipherHashData(i);
112783     /* Invoke any destructors registered for collation sequence user data. */
112784     for(j=0; j<3; j++){
112785       if( pColl[j].xDel ){
112786         pColl[j].xDel(pColl[j].pUser);
112787       }
112788     }
112789     sqlcipher3DbFree(db, pColl);
112790   }
112791   sqlcipher3HashClear(&db->aCollSeq);
112792 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
112793   for(i=sqlcipherHashFirst(&db->aModule); i; i=sqlcipherHashNext(i)){
112794     Module *pMod = (Module *)sqlcipherHashData(i);
112795     if( pMod->xDestroy ){
112796       pMod->xDestroy(pMod->pAux);
112797     }
112798     sqlcipher3DbFree(db, pMod);
112799   }
112800   sqlcipher3HashClear(&db->aModule);
112801 #endif
112802
112803   sqlcipher3Error(db, SQLCIPHER_OK, 0); /* Deallocates any cached error strings. */
112804   if( db->pErr ){
112805     sqlcipher3ValueFree(db->pErr);
112806   }
112807   sqlcipher3CloseExtensions(db);
112808
112809   db->magic = SQLCIPHER_MAGIC_ERROR;
112810
112811   /* The temp-database schema is allocated differently from the other schema
112812   ** objects (using sqlcipherMalloc() directly, instead of sqlcipher3BtreeSchema()).
112813   ** So it needs to be freed here. Todo: Why not roll the temp schema into
112814   ** the same sqlcipherMalloc() as the one that allocates the database 
112815   ** structure?
112816   */
112817   sqlcipher3DbFree(db, db->aDb[1].pSchema);
112818   sqlcipher3_mutex_leave(db->mutex);
112819   db->magic = SQLCIPHER_MAGIC_CLOSED;
112820   sqlcipher3_mutex_free(db->mutex);
112821   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
112822   if( db->lookaside.bMalloced ){
112823     sqlcipher3_free(db->lookaside.pStart);
112824   }
112825   sqlcipher3_free(db);
112826   return SQLCIPHER_OK;
112827 }
112828
112829 /*
112830 ** Rollback all database files.
112831 */
112832 SQLCIPHER_PRIVATE void sqlcipher3RollbackAll(sqlcipher3 *db){
112833   int i;
112834   int inTrans = 0;
112835   assert( sqlcipher3_mutex_held(db->mutex) );
112836   sqlcipher3BeginBenignMalloc();
112837   for(i=0; i<db->nDb; i++){
112838     if( db->aDb[i].pBt ){
112839       if( sqlcipher3BtreeIsInTrans(db->aDb[i].pBt) ){
112840         inTrans = 1;
112841       }
112842       sqlcipher3BtreeRollback(db->aDb[i].pBt);
112843       db->aDb[i].inTrans = 0;
112844     }
112845   }
112846   sqlcipher3VtabRollback(db);
112847   sqlcipher3EndBenignMalloc();
112848
112849   if( db->flags&SQLCIPHER_InternChanges ){
112850     sqlcipher3ExpirePreparedStatements(db);
112851     sqlcipher3ResetInternalSchema(db, -1);
112852   }
112853
112854   /* Any deferred constraint violations have now been resolved. */
112855   db->nDeferredCons = 0;
112856
112857   /* If one has been configured, invoke the rollback-hook callback */
112858   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
112859     db->xRollbackCallback(db->pRollbackArg);
112860   }
112861 }
112862
112863 /*
112864 ** Return a static string that describes the kind of error specified in the
112865 ** argument.
112866 */
112867 SQLCIPHER_PRIVATE const char *sqlcipher3ErrStr(int rc){
112868   static const char* const aMsg[] = {
112869     /* SQLCIPHER_OK          */ "not an error",
112870     /* SQLCIPHER_ERROR       */ "SQL logic error or missing database",
112871     /* SQLCIPHER_INTERNAL    */ 0,
112872     /* SQLCIPHER_PERM        */ "access permission denied",
112873     /* SQLCIPHER_ABORT       */ "callback requested query abort",
112874     /* SQLCIPHER_BUSY        */ "database is locked",
112875     /* SQLCIPHER_LOCKED      */ "database table is locked",
112876     /* SQLCIPHER_NOMEM       */ "out of memory",
112877     /* SQLCIPHER_READONLY    */ "attempt to write a readonly database",
112878     /* SQLCIPHER_INTERRUPT   */ "interrupted",
112879     /* SQLCIPHER_IOERR       */ "disk I/O error",
112880     /* SQLCIPHER_CORRUPT     */ "database disk image is malformed",
112881     /* SQLCIPHER_NOTFOUND    */ "unknown operation",
112882     /* SQLCIPHER_FULL        */ "database or disk is full",
112883     /* SQLCIPHER_CANTOPEN    */ "unable to open database file",
112884     /* SQLCIPHER_PROTOCOL    */ "locking protocol",
112885     /* SQLCIPHER_EMPTY       */ "table contains no data",
112886     /* SQLCIPHER_SCHEMA      */ "database schema has changed",
112887     /* SQLCIPHER_TOOBIG      */ "string or blob too big",
112888     /* SQLCIPHER_CONSTRAINT  */ "constraint failed",
112889     /* SQLCIPHER_MISMATCH    */ "datatype mismatch",
112890     /* SQLCIPHER_MISUSE      */ "library routine called out of sequence",
112891     /* SQLCIPHER_NOLFS       */ "large file support is disabled",
112892     /* SQLCIPHER_AUTH        */ "authorization denied",
112893     /* SQLCIPHER_FORMAT      */ "auxiliary database format error",
112894     /* SQLCIPHER_RANGE       */ "bind or column index out of range",
112895     /* SQLCIPHER_NOTADB      */ "file is encrypted or is not a database",
112896   };
112897   rc &= 0xff;
112898   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
112899     return aMsg[rc];
112900   }else{
112901     return "unknown error";
112902   }
112903 }
112904
112905 /*
112906 ** This routine implements a busy callback that sleeps and tries
112907 ** again until a timeout value is reached.  The timeout value is
112908 ** an integer number of milliseconds passed in as the first
112909 ** argument.
112910 */
112911 static int sqlcipherDefaultBusyCallback(
112912  void *ptr,               /* Database connection */
112913  int count                /* Number of times table has been busy */
112914 ){
112915 #if SQLCIPHER_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
112916   static const u8 delays[] =
112917      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
112918   static const u8 totals[] =
112919      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
112920 # define NDELAY ArraySize(delays)
112921   sqlcipher3 *db = (sqlcipher3 *)ptr;
112922   int timeout = db->busyTimeout;
112923   int delay, prior;
112924
112925   assert( count>=0 );
112926   if( count < NDELAY ){
112927     delay = delays[count];
112928     prior = totals[count];
112929   }else{
112930     delay = delays[NDELAY-1];
112931     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
112932   }
112933   if( prior + delay > timeout ){
112934     delay = timeout - prior;
112935     if( delay<=0 ) return 0;
112936   }
112937   sqlcipher3OsSleep(db->pVfs, delay*1000);
112938   return 1;
112939 #else
112940   sqlcipher3 *db = (sqlcipher3 *)ptr;
112941   int timeout = ((sqlcipher3 *)ptr)->busyTimeout;
112942   if( (count+1)*1000 > timeout ){
112943     return 0;
112944   }
112945   sqlcipher3OsSleep(db->pVfs, 1000000);
112946   return 1;
112947 #endif
112948 }
112949
112950 /*
112951 ** Invoke the given busy handler.
112952 **
112953 ** This routine is called when an operation failed with a lock.
112954 ** If this routine returns non-zero, the lock is retried.  If it
112955 ** returns 0, the operation aborts with an SQLCIPHER_BUSY error.
112956 */
112957 SQLCIPHER_PRIVATE int sqlcipher3InvokeBusyHandler(BusyHandler *p){
112958   int rc;
112959   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
112960   rc = p->xFunc(p->pArg, p->nBusy);
112961   if( rc==0 ){
112962     p->nBusy = -1;
112963   }else{
112964     p->nBusy++;
112965   }
112966   return rc; 
112967 }
112968
112969 /*
112970 ** This routine sets the busy callback for an Sqlite database to the
112971 ** given callback function with the given argument.
112972 */
112973 SQLCIPHER_API int sqlcipher3_busy_handler(
112974   sqlcipher3 *db,
112975   int (*xBusy)(void*,int),
112976   void *pArg
112977 ){
112978   sqlcipher3_mutex_enter(db->mutex);
112979   db->busyHandler.xFunc = xBusy;
112980   db->busyHandler.pArg = pArg;
112981   db->busyHandler.nBusy = 0;
112982   sqlcipher3_mutex_leave(db->mutex);
112983   return SQLCIPHER_OK;
112984 }
112985
112986 #ifndef SQLCIPHER_OMIT_PROGRESS_CALLBACK
112987 /*
112988 ** This routine sets the progress callback for an Sqlite database to the
112989 ** given callback function with the given argument. The progress callback will
112990 ** be invoked every nOps opcodes.
112991 */
112992 SQLCIPHER_API void sqlcipher3_progress_handler(
112993   sqlcipher3 *db, 
112994   int nOps,
112995   int (*xProgress)(void*), 
112996   void *pArg
112997 ){
112998   sqlcipher3_mutex_enter(db->mutex);
112999   if( nOps>0 ){
113000     db->xProgress = xProgress;
113001     db->nProgressOps = nOps;
113002     db->pProgressArg = pArg;
113003   }else{
113004     db->xProgress = 0;
113005     db->nProgressOps = 0;
113006     db->pProgressArg = 0;
113007   }
113008   sqlcipher3_mutex_leave(db->mutex);
113009 }
113010 #endif
113011
113012
113013 /*
113014 ** This routine installs a default busy handler that waits for the
113015 ** specified number of milliseconds before returning 0.
113016 */
113017 SQLCIPHER_API int sqlcipher3_busy_timeout(sqlcipher3 *db, int ms){
113018   if( ms>0 ){
113019     db->busyTimeout = ms;
113020     sqlcipher3_busy_handler(db, sqlcipherDefaultBusyCallback, (void*)db);
113021   }else{
113022     sqlcipher3_busy_handler(db, 0, 0);
113023   }
113024   return SQLCIPHER_OK;
113025 }
113026
113027 /*
113028 ** Cause any pending operation to stop at its earliest opportunity.
113029 */
113030 SQLCIPHER_API void sqlcipher3_interrupt(sqlcipher3 *db){
113031   db->u1.isInterrupted = 1;
113032 }
113033
113034
113035 /*
113036 ** This function is exactly the same as sqlcipher3_create_function(), except
113037 ** that it is designed to be called by internal code. The difference is
113038 ** that if a malloc() fails in sqlcipher3_create_function(), an error code
113039 ** is returned and the mallocFailed flag cleared. 
113040 */
113041 SQLCIPHER_PRIVATE int sqlcipher3CreateFunc(
113042   sqlcipher3 *db,
113043   const char *zFunctionName,
113044   int nArg,
113045   int enc,
113046   void *pUserData,
113047   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value **),
113048   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value **),
113049   void (*xFinal)(sqlcipher3_context*),
113050   FuncDestructor *pDestructor
113051 ){
113052   FuncDef *p;
113053   int nName;
113054
113055   assert( sqlcipher3_mutex_held(db->mutex) );
113056   if( zFunctionName==0 ||
113057       (xFunc && (xFinal || xStep)) || 
113058       (!xFunc && (xFinal && !xStep)) ||
113059       (!xFunc && (!xFinal && xStep)) ||
113060       (nArg<-1 || nArg>SQLCIPHER_MAX_FUNCTION_ARG) ||
113061       (255<(nName = sqlcipher3Strlen30( zFunctionName))) ){
113062     return SQLCIPHER_MISUSE_BKPT;
113063   }
113064   
113065 #ifndef SQLCIPHER_OMIT_UTF16
113066   /* If SQLCIPHER_UTF16 is specified as the encoding type, transform this
113067   ** to one of SQLCIPHER_UTF16LE or SQLCIPHER_UTF16BE using the
113068   ** SQLCIPHER_UTF16NATIVE macro. SQLCIPHER_UTF16 is not used internally.
113069   **
113070   ** If SQLCIPHER_ANY is specified, add three versions of the function
113071   ** to the hash table.
113072   */
113073   if( enc==SQLCIPHER_UTF16 ){
113074     enc = SQLCIPHER_UTF16NATIVE;
113075   }else if( enc==SQLCIPHER_ANY ){
113076     int rc;
113077     rc = sqlcipher3CreateFunc(db, zFunctionName, nArg, SQLCIPHER_UTF8,
113078          pUserData, xFunc, xStep, xFinal, pDestructor);
113079     if( rc==SQLCIPHER_OK ){
113080       rc = sqlcipher3CreateFunc(db, zFunctionName, nArg, SQLCIPHER_UTF16LE,
113081           pUserData, xFunc, xStep, xFinal, pDestructor);
113082     }
113083     if( rc!=SQLCIPHER_OK ){
113084       return rc;
113085     }
113086     enc = SQLCIPHER_UTF16BE;
113087   }
113088 #else
113089   enc = SQLCIPHER_UTF8;
113090 #endif
113091   
113092   /* Check if an existing function is being overridden or deleted. If so,
113093   ** and there are active VMs, then return SQLCIPHER_BUSY. If a function
113094   ** is being overridden/deleted but there are no active VMs, allow the
113095   ** operation to continue but invalidate all precompiled statements.
113096   */
113097   p = sqlcipher3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
113098   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
113099     if( db->activeVdbeCnt ){
113100       sqlcipher3Error(db, SQLCIPHER_BUSY, 
113101         "unable to delete/modify user-function due to active statements");
113102       assert( !db->mallocFailed );
113103       return SQLCIPHER_BUSY;
113104     }else{
113105       sqlcipher3ExpirePreparedStatements(db);
113106     }
113107   }
113108
113109   p = sqlcipher3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
113110   assert(p || db->mallocFailed);
113111   if( !p ){
113112     return SQLCIPHER_NOMEM;
113113   }
113114
113115   /* If an older version of the function with a configured destructor is
113116   ** being replaced invoke the destructor function here. */
113117   functionDestroy(db, p);
113118
113119   if( pDestructor ){
113120     pDestructor->nRef++;
113121   }
113122   p->pDestructor = pDestructor;
113123   p->flags = 0;
113124   p->xFunc = xFunc;
113125   p->xStep = xStep;
113126   p->xFinalize = xFinal;
113127   p->pUserData = pUserData;
113128   p->nArg = (u16)nArg;
113129   return SQLCIPHER_OK;
113130 }
113131
113132 /*
113133 ** Create new user functions.
113134 */
113135 SQLCIPHER_API int sqlcipher3_create_function(
113136   sqlcipher3 *db,
113137   const char *zFunc,
113138   int nArg,
113139   int enc,
113140   void *p,
113141   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value **),
113142   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value **),
113143   void (*xFinal)(sqlcipher3_context*)
113144 ){
113145   return sqlcipher3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
113146                                     xFinal, 0);
113147 }
113148
113149 SQLCIPHER_API int sqlcipher3_create_function_v2(
113150   sqlcipher3 *db,
113151   const char *zFunc,
113152   int nArg,
113153   int enc,
113154   void *p,
113155   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value **),
113156   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value **),
113157   void (*xFinal)(sqlcipher3_context*),
113158   void (*xDestroy)(void *)
113159 ){
113160   int rc = SQLCIPHER_ERROR;
113161   FuncDestructor *pArg = 0;
113162   sqlcipher3_mutex_enter(db->mutex);
113163   if( xDestroy ){
113164     pArg = (FuncDestructor *)sqlcipher3DbMallocZero(db, sizeof(FuncDestructor));
113165     if( !pArg ){
113166       xDestroy(p);
113167       goto out;
113168     }
113169     pArg->xDestroy = xDestroy;
113170     pArg->pUserData = p;
113171   }
113172   rc = sqlcipher3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
113173   if( pArg && pArg->nRef==0 ){
113174     assert( rc!=SQLCIPHER_OK );
113175     xDestroy(p);
113176     sqlcipher3DbFree(db, pArg);
113177   }
113178
113179  out:
113180   rc = sqlcipher3ApiExit(db, rc);
113181   sqlcipher3_mutex_leave(db->mutex);
113182   return rc;
113183 }
113184
113185 #ifndef SQLCIPHER_OMIT_UTF16
113186 SQLCIPHER_API int sqlcipher3_create_function16(
113187   sqlcipher3 *db,
113188   const void *zFunctionName,
113189   int nArg,
113190   int eTextRep,
113191   void *p,
113192   void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**),
113193   void (*xStep)(sqlcipher3_context*,int,sqlcipher3_value**),
113194   void (*xFinal)(sqlcipher3_context*)
113195 ){
113196   int rc;
113197   char *zFunc8;
113198   sqlcipher3_mutex_enter(db->mutex);
113199   assert( !db->mallocFailed );
113200   zFunc8 = sqlcipher3Utf16to8(db, zFunctionName, -1, SQLCIPHER_UTF16NATIVE);
113201   rc = sqlcipher3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
113202   sqlcipher3DbFree(db, zFunc8);
113203   rc = sqlcipher3ApiExit(db, rc);
113204   sqlcipher3_mutex_leave(db->mutex);
113205   return rc;
113206 }
113207 #endif
113208
113209
113210 /*
113211 ** Declare that a function has been overloaded by a virtual table.
113212 **
113213 ** If the function already exists as a regular global function, then
113214 ** this routine is a no-op.  If the function does not exist, then create
113215 ** a new one that always throws a run-time error.  
113216 **
113217 ** When virtual tables intend to provide an overloaded function, they
113218 ** should call this routine to make sure the global function exists.
113219 ** A global function must exist in order for name resolution to work
113220 ** properly.
113221 */
113222 SQLCIPHER_API int sqlcipher3_overload_function(
113223   sqlcipher3 *db,
113224   const char *zName,
113225   int nArg
113226 ){
113227   int nName = sqlcipher3Strlen30(zName);
113228   int rc = SQLCIPHER_OK;
113229   sqlcipher3_mutex_enter(db->mutex);
113230   if( sqlcipher3FindFunction(db, zName, nName, nArg, SQLCIPHER_UTF8, 0)==0 ){
113231     rc = sqlcipher3CreateFunc(db, zName, nArg, SQLCIPHER_UTF8,
113232                            0, sqlcipher3InvalidFunction, 0, 0, 0);
113233   }
113234   rc = sqlcipher3ApiExit(db, rc);
113235   sqlcipher3_mutex_leave(db->mutex);
113236   return rc;
113237 }
113238
113239 #ifndef SQLCIPHER_OMIT_TRACE
113240 /*
113241 ** Register a trace function.  The pArg from the previously registered trace
113242 ** is returned.  
113243 **
113244 ** A NULL trace function means that no tracing is executes.  A non-NULL
113245 ** trace is a pointer to a function that is invoked at the start of each
113246 ** SQL statement.
113247 */
113248 SQLCIPHER_API void *sqlcipher3_trace(sqlcipher3 *db, void (*xTrace)(void*,const char*), void *pArg){
113249   void *pOld;
113250   sqlcipher3_mutex_enter(db->mutex);
113251   pOld = db->pTraceArg;
113252   db->xTrace = xTrace;
113253   db->pTraceArg = pArg;
113254   sqlcipher3_mutex_leave(db->mutex);
113255   return pOld;
113256 }
113257 /*
113258 ** Register a profile function.  The pArg from the previously registered 
113259 ** profile function is returned.  
113260 **
113261 ** A NULL profile function means that no profiling is executes.  A non-NULL
113262 ** profile is a pointer to a function that is invoked at the conclusion of
113263 ** each SQL statement that is run.
113264 */
113265 SQLCIPHER_API void *sqlcipher3_profile(
113266   sqlcipher3 *db,
113267   void (*xProfile)(void*,const char*,sqlcipher_uint64),
113268   void *pArg
113269 ){
113270   void *pOld;
113271   sqlcipher3_mutex_enter(db->mutex);
113272   pOld = db->pProfileArg;
113273   db->xProfile = xProfile;
113274   db->pProfileArg = pArg;
113275   sqlcipher3_mutex_leave(db->mutex);
113276   return pOld;
113277 }
113278 #endif /* SQLCIPHER_OMIT_TRACE */
113279
113280 /*** EXPERIMENTAL ***
113281 **
113282 ** Register a function to be invoked when a transaction comments.
113283 ** If the invoked function returns non-zero, then the commit becomes a
113284 ** rollback.
113285 */
113286 SQLCIPHER_API void *sqlcipher3_commit_hook(
113287   sqlcipher3 *db,              /* Attach the hook to this database */
113288   int (*xCallback)(void*),  /* Function to invoke on each commit */
113289   void *pArg                /* Argument to the function */
113290 ){
113291   void *pOld;
113292   sqlcipher3_mutex_enter(db->mutex);
113293   pOld = db->pCommitArg;
113294   db->xCommitCallback = xCallback;
113295   db->pCommitArg = pArg;
113296   sqlcipher3_mutex_leave(db->mutex);
113297   return pOld;
113298 }
113299
113300 /*
113301 ** Register a callback to be invoked each time a row is updated,
113302 ** inserted or deleted using this database connection.
113303 */
113304 SQLCIPHER_API void *sqlcipher3_update_hook(
113305   sqlcipher3 *db,              /* Attach the hook to this database */
113306   void (*xCallback)(void*,int,char const *,char const *,sqlcipher_int64),
113307   void *pArg                /* Argument to the function */
113308 ){
113309   void *pRet;
113310   sqlcipher3_mutex_enter(db->mutex);
113311   pRet = db->pUpdateArg;
113312   db->xUpdateCallback = xCallback;
113313   db->pUpdateArg = pArg;
113314   sqlcipher3_mutex_leave(db->mutex);
113315   return pRet;
113316 }
113317
113318 /*
113319 ** Register a callback to be invoked each time a transaction is rolled
113320 ** back by this database connection.
113321 */
113322 SQLCIPHER_API void *sqlcipher3_rollback_hook(
113323   sqlcipher3 *db,              /* Attach the hook to this database */
113324   void (*xCallback)(void*), /* Callback function */
113325   void *pArg                /* Argument to the function */
113326 ){
113327   void *pRet;
113328   sqlcipher3_mutex_enter(db->mutex);
113329   pRet = db->pRollbackArg;
113330   db->xRollbackCallback = xCallback;
113331   db->pRollbackArg = pArg;
113332   sqlcipher3_mutex_leave(db->mutex);
113333   return pRet;
113334 }
113335
113336 #ifndef SQLCIPHER_OMIT_WAL
113337 /*
113338 ** The sqlcipher3_wal_hook() callback registered by sqlcipher3_wal_autocheckpoint().
113339 ** Invoke sqlcipher3_wal_checkpoint if the number of frames in the log file
113340 ** is greater than sqlcipher3.pWalArg cast to an integer (the value configured by
113341 ** wal_autocheckpoint()).
113342 */ 
113343 SQLCIPHER_PRIVATE int sqlcipher3WalDefaultHook(
113344   void *pClientData,     /* Argument */
113345   sqlcipher3 *db,           /* Connection */
113346   const char *zDb,       /* Database */
113347   int nFrame             /* Size of WAL */
113348 ){
113349   if( nFrame>=SQLCIPHER_PTR_TO_INT(pClientData) ){
113350     sqlcipher3BeginBenignMalloc();
113351     sqlcipher3_wal_checkpoint(db, zDb);
113352     sqlcipher3EndBenignMalloc();
113353   }
113354   return SQLCIPHER_OK;
113355 }
113356 #endif /* SQLCIPHER_OMIT_WAL */
113357
113358 /*
113359 ** Configure an sqlcipher3_wal_hook() callback to automatically checkpoint
113360 ** a database after committing a transaction if there are nFrame or
113361 ** more frames in the log file. Passing zero or a negative value as the
113362 ** nFrame parameter disables automatic checkpoints entirely.
113363 **
113364 ** The callback registered by this function replaces any existing callback
113365 ** registered using sqlcipher3_wal_hook(). Likewise, registering a callback
113366 ** using sqlcipher3_wal_hook() disables the automatic checkpoint mechanism
113367 ** configured by this function.
113368 */
113369 SQLCIPHER_API int sqlcipher3_wal_autocheckpoint(sqlcipher3 *db, int nFrame){
113370 #ifdef SQLCIPHER_OMIT_WAL
113371   UNUSED_PARAMETER(db);
113372   UNUSED_PARAMETER(nFrame);
113373 #else
113374   if( nFrame>0 ){
113375     sqlcipher3_wal_hook(db, sqlcipher3WalDefaultHook, SQLCIPHER_INT_TO_PTR(nFrame));
113376   }else{
113377     sqlcipher3_wal_hook(db, 0, 0);
113378   }
113379 #endif
113380   return SQLCIPHER_OK;
113381 }
113382
113383 /*
113384 ** Register a callback to be invoked each time a transaction is written
113385 ** into the write-ahead-log by this database connection.
113386 */
113387 SQLCIPHER_API void *sqlcipher3_wal_hook(
113388   sqlcipher3 *db,                    /* Attach the hook to this db handle */
113389   int(*xCallback)(void *, sqlcipher3*, const char*, int),
113390   void *pArg                      /* First argument passed to xCallback() */
113391 ){
113392 #ifndef SQLCIPHER_OMIT_WAL
113393   void *pRet;
113394   sqlcipher3_mutex_enter(db->mutex);
113395   pRet = db->pWalArg;
113396   db->xWalCallback = xCallback;
113397   db->pWalArg = pArg;
113398   sqlcipher3_mutex_leave(db->mutex);
113399   return pRet;
113400 #else
113401   return 0;
113402 #endif
113403 }
113404
113405 /*
113406 ** Checkpoint database zDb.
113407 */
113408 SQLCIPHER_API int sqlcipher3_wal_checkpoint_v2(
113409   sqlcipher3 *db,                    /* Database handle */
113410   const char *zDb,                /* Name of attached database (or NULL) */
113411   int eMode,                      /* SQLCIPHER_CHECKPOINT_* value */
113412   int *pnLog,                     /* OUT: Size of WAL log in frames */
113413   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
113414 ){
113415 #ifdef SQLCIPHER_OMIT_WAL
113416   return SQLCIPHER_OK;
113417 #else
113418   int rc;                         /* Return code */
113419   int iDb = SQLCIPHER_MAX_ATTACHED;  /* sqlcipher3.aDb[] index of db to checkpoint */
113420
113421   /* Initialize the output variables to -1 in case an error occurs. */
113422   if( pnLog ) *pnLog = -1;
113423   if( pnCkpt ) *pnCkpt = -1;
113424
113425   assert( SQLCIPHER_CHECKPOINT_FULL>SQLCIPHER_CHECKPOINT_PASSIVE );
113426   assert( SQLCIPHER_CHECKPOINT_FULL<SQLCIPHER_CHECKPOINT_RESTART );
113427   assert( SQLCIPHER_CHECKPOINT_PASSIVE+2==SQLCIPHER_CHECKPOINT_RESTART );
113428   if( eMode<SQLCIPHER_CHECKPOINT_PASSIVE || eMode>SQLCIPHER_CHECKPOINT_RESTART ){
113429     return SQLCIPHER_MISUSE;
113430   }
113431
113432   sqlcipher3_mutex_enter(db->mutex);
113433   if( zDb && zDb[0] ){
113434     iDb = sqlcipher3FindDbName(db, zDb);
113435   }
113436   if( iDb<0 ){
113437     rc = SQLCIPHER_ERROR;
113438     sqlcipher3Error(db, SQLCIPHER_ERROR, "unknown database: %s", zDb);
113439   }else{
113440     rc = sqlcipher3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
113441     sqlcipher3Error(db, rc, 0);
113442   }
113443   rc = sqlcipher3ApiExit(db, rc);
113444   sqlcipher3_mutex_leave(db->mutex);
113445   return rc;
113446 #endif
113447 }
113448
113449
113450 /*
113451 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
113452 ** to contains a zero-length string, all attached databases are 
113453 ** checkpointed.
113454 */
113455 SQLCIPHER_API int sqlcipher3_wal_checkpoint(sqlcipher3 *db, const char *zDb){
113456   return sqlcipher3_wal_checkpoint_v2(db, zDb, SQLCIPHER_CHECKPOINT_PASSIVE, 0, 0);
113457 }
113458
113459 #ifndef SQLCIPHER_OMIT_WAL
113460 /*
113461 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
113462 ** not currently open in WAL mode.
113463 **
113464 ** If a transaction is open on the database being checkpointed, this 
113465 ** function returns SQLCIPHER_LOCKED and a checkpoint is not attempted. If 
113466 ** an error occurs while running the checkpoint, an SQLite error code is 
113467 ** returned (i.e. SQLCIPHER_IOERR). Otherwise, SQLCIPHER_OK.
113468 **
113469 ** The mutex on database handle db should be held by the caller. The mutex
113470 ** associated with the specific b-tree being checkpointed is taken by
113471 ** this function while the checkpoint is running.
113472 **
113473 ** If iDb is passed SQLCIPHER_MAX_ATTACHED, then all attached databases are
113474 ** checkpointed. If an error is encountered it is returned immediately -
113475 ** no attempt is made to checkpoint any remaining databases.
113476 **
113477 ** Parameter eMode is one of SQLCIPHER_CHECKPOINT_PASSIVE, FULL or RESTART.
113478 */
113479 SQLCIPHER_PRIVATE int sqlcipher3Checkpoint(sqlcipher3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
113480   int rc = SQLCIPHER_OK;             /* Return code */
113481   int i;                          /* Used to iterate through attached dbs */
113482   int bBusy = 0;                  /* True if SQLCIPHER_BUSY has been encountered */
113483
113484   assert( sqlcipher3_mutex_held(db->mutex) );
113485   assert( !pnLog || *pnLog==-1 );
113486   assert( !pnCkpt || *pnCkpt==-1 );
113487
113488   for(i=0; i<db->nDb && rc==SQLCIPHER_OK; i++){
113489     if( i==iDb || iDb==SQLCIPHER_MAX_ATTACHED ){
113490       rc = sqlcipher3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
113491       pnLog = 0;
113492       pnCkpt = 0;
113493       if( rc==SQLCIPHER_BUSY ){
113494         bBusy = 1;
113495         rc = SQLCIPHER_OK;
113496       }
113497     }
113498   }
113499
113500   return (rc==SQLCIPHER_OK && bBusy) ? SQLCIPHER_BUSY : rc;
113501 }
113502 #endif /* SQLCIPHER_OMIT_WAL */
113503
113504 /*
113505 ** This function returns true if main-memory should be used instead of
113506 ** a temporary file for transient pager files and statement journals.
113507 ** The value returned depends on the value of db->temp_store (runtime
113508 ** parameter) and the compile time value of SQLCIPHER_TEMP_STORE. The
113509 ** following table describes the relationship between these two values
113510 ** and this functions return value.
113511 **
113512 **   SQLCIPHER_TEMP_STORE     db->temp_store     Location of temporary database
113513 **   -----------------     --------------     ------------------------------
113514 **   0                     any                file      (return 0)
113515 **   1                     1                  file      (return 0)
113516 **   1                     2                  memory    (return 1)
113517 **   1                     0                  file      (return 0)
113518 **   2                     1                  file      (return 0)
113519 **   2                     2                  memory    (return 1)
113520 **   2                     0                  memory    (return 1)
113521 **   3                     any                memory    (return 1)
113522 */
113523 SQLCIPHER_PRIVATE int sqlcipher3TempInMemory(const sqlcipher3 *db){
113524 #if SQLCIPHER_TEMP_STORE==1
113525   return ( db->temp_store==2 );
113526 #endif
113527 #if SQLCIPHER_TEMP_STORE==2
113528   return ( db->temp_store!=1 );
113529 #endif
113530 #if SQLCIPHER_TEMP_STORE==3
113531   return 1;
113532 #endif
113533 #if SQLCIPHER_TEMP_STORE<1 || SQLCIPHER_TEMP_STORE>3
113534   return 0;
113535 #endif
113536 }
113537
113538 /*
113539 ** Return UTF-8 encoded English language explanation of the most recent
113540 ** error.
113541 */
113542 SQLCIPHER_API const char *sqlcipher3_errmsg(sqlcipher3 *db){
113543   const char *z;
113544   if( !db ){
113545     return sqlcipher3ErrStr(SQLCIPHER_NOMEM);
113546   }
113547   if( !sqlcipher3SafetyCheckSickOrOk(db) ){
113548     return sqlcipher3ErrStr(SQLCIPHER_MISUSE_BKPT);
113549   }
113550   sqlcipher3_mutex_enter(db->mutex);
113551   if( db->mallocFailed ){
113552     z = sqlcipher3ErrStr(SQLCIPHER_NOMEM);
113553   }else{
113554     z = (char*)sqlcipher3_value_text(db->pErr);
113555     assert( !db->mallocFailed );
113556     if( z==0 ){
113557       z = sqlcipher3ErrStr(db->errCode);
113558     }
113559   }
113560   sqlcipher3_mutex_leave(db->mutex);
113561   return z;
113562 }
113563
113564 #ifndef SQLCIPHER_OMIT_UTF16
113565 /*
113566 ** Return UTF-16 encoded English language explanation of the most recent
113567 ** error.
113568 */
113569 SQLCIPHER_API const void *sqlcipher3_errmsg16(sqlcipher3 *db){
113570   static const u16 outOfMem[] = {
113571     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
113572   };
113573   static const u16 misuse[] = {
113574     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
113575     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
113576     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
113577     'o', 'u', 't', ' ', 
113578     'o', 'f', ' ', 
113579     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
113580   };
113581
113582   const void *z;
113583   if( !db ){
113584     return (void *)outOfMem;
113585   }
113586   if( !sqlcipher3SafetyCheckSickOrOk(db) ){
113587     return (void *)misuse;
113588   }
113589   sqlcipher3_mutex_enter(db->mutex);
113590   if( db->mallocFailed ){
113591     z = (void *)outOfMem;
113592   }else{
113593     z = sqlcipher3_value_text16(db->pErr);
113594     if( z==0 ){
113595       sqlcipher3ValueSetStr(db->pErr, -1, sqlcipher3ErrStr(db->errCode),
113596            SQLCIPHER_UTF8, SQLCIPHER_STATIC);
113597       z = sqlcipher3_value_text16(db->pErr);
113598     }
113599     /* A malloc() may have failed within the call to sqlcipher3_value_text16()
113600     ** above. If this is the case, then the db->mallocFailed flag needs to
113601     ** be cleared before returning. Do this directly, instead of via
113602     ** sqlcipher3ApiExit(), to avoid setting the database handle error message.
113603     */
113604     db->mallocFailed = 0;
113605   }
113606   sqlcipher3_mutex_leave(db->mutex);
113607   return z;
113608 }
113609 #endif /* SQLCIPHER_OMIT_UTF16 */
113610
113611 /*
113612 ** Return the most recent error code generated by an SQLite routine. If NULL is
113613 ** passed to this function, we assume a malloc() failed during sqlcipher3_open().
113614 */
113615 SQLCIPHER_API int sqlcipher3_errcode(sqlcipher3 *db){
113616   if( db && !sqlcipher3SafetyCheckSickOrOk(db) ){
113617     return SQLCIPHER_MISUSE_BKPT;
113618   }
113619   if( !db || db->mallocFailed ){
113620     return SQLCIPHER_NOMEM;
113621   }
113622   return db->errCode & db->errMask;
113623 }
113624 SQLCIPHER_API int sqlcipher3_extended_errcode(sqlcipher3 *db){
113625   if( db && !sqlcipher3SafetyCheckSickOrOk(db) ){
113626     return SQLCIPHER_MISUSE_BKPT;
113627   }
113628   if( !db || db->mallocFailed ){
113629     return SQLCIPHER_NOMEM;
113630   }
113631   return db->errCode;
113632 }
113633
113634 /*
113635 ** Create a new collating function for database "db".  The name is zName
113636 ** and the encoding is enc.
113637 */
113638 static int createCollation(
113639   sqlcipher3* db,
113640   const char *zName, 
113641   u8 enc,
113642   u8 collType,
113643   void* pCtx,
113644   int(*xCompare)(void*,int,const void*,int,const void*),
113645   void(*xDel)(void*)
113646 ){
113647   CollSeq *pColl;
113648   int enc2;
113649   int nName = sqlcipher3Strlen30(zName);
113650   
113651   assert( sqlcipher3_mutex_held(db->mutex) );
113652
113653   /* If SQLCIPHER_UTF16 is specified as the encoding type, transform this
113654   ** to one of SQLCIPHER_UTF16LE or SQLCIPHER_UTF16BE using the
113655   ** SQLCIPHER_UTF16NATIVE macro. SQLCIPHER_UTF16 is not used internally.
113656   */
113657   enc2 = enc;
113658   testcase( enc2==SQLCIPHER_UTF16 );
113659   testcase( enc2==SQLCIPHER_UTF16_ALIGNED );
113660   if( enc2==SQLCIPHER_UTF16 || enc2==SQLCIPHER_UTF16_ALIGNED ){
113661     enc2 = SQLCIPHER_UTF16NATIVE;
113662   }
113663   if( enc2<SQLCIPHER_UTF8 || enc2>SQLCIPHER_UTF16BE ){
113664     return SQLCIPHER_MISUSE_BKPT;
113665   }
113666
113667   /* Check if this call is removing or replacing an existing collation 
113668   ** sequence. If so, and there are active VMs, return busy. If there
113669   ** are no active VMs, invalidate any pre-compiled statements.
113670   */
113671   pColl = sqlcipher3FindCollSeq(db, (u8)enc2, zName, 0);
113672   if( pColl && pColl->xCmp ){
113673     if( db->activeVdbeCnt ){
113674       sqlcipher3Error(db, SQLCIPHER_BUSY, 
113675         "unable to delete/modify collation sequence due to active statements");
113676       return SQLCIPHER_BUSY;
113677     }
113678     sqlcipher3ExpirePreparedStatements(db);
113679
113680     /* If collation sequence pColl was created directly by a call to
113681     ** sqlcipher3_create_collation, and not generated by synthCollSeq(),
113682     ** then any copies made by synthCollSeq() need to be invalidated.
113683     ** Also, collation destructor - CollSeq.xDel() - function may need
113684     ** to be called.
113685     */ 
113686     if( (pColl->enc & ~SQLCIPHER_UTF16_ALIGNED)==enc2 ){
113687       CollSeq *aColl = sqlcipher3HashFind(&db->aCollSeq, zName, nName);
113688       int j;
113689       for(j=0; j<3; j++){
113690         CollSeq *p = &aColl[j];
113691         if( p->enc==pColl->enc ){
113692           if( p->xDel ){
113693             p->xDel(p->pUser);
113694           }
113695           p->xCmp = 0;
113696         }
113697       }
113698     }
113699   }
113700
113701   pColl = sqlcipher3FindCollSeq(db, (u8)enc2, zName, 1);
113702   if( pColl==0 ) return SQLCIPHER_NOMEM;
113703   pColl->xCmp = xCompare;
113704   pColl->pUser = pCtx;
113705   pColl->xDel = xDel;
113706   pColl->enc = (u8)(enc2 | (enc & SQLCIPHER_UTF16_ALIGNED));
113707   pColl->type = collType;
113708   sqlcipher3Error(db, SQLCIPHER_OK, 0);
113709   return SQLCIPHER_OK;
113710 }
113711
113712
113713 /*
113714 ** This array defines hard upper bounds on limit values.  The
113715 ** initializer must be kept in sync with the SQLCIPHER_LIMIT_*
113716 ** #defines in sqlcipher3.h.
113717 */
113718 static const int aHardLimit[] = {
113719   SQLCIPHER_MAX_LENGTH,
113720   SQLCIPHER_MAX_SQL_LENGTH,
113721   SQLCIPHER_MAX_COLUMN,
113722   SQLCIPHER_MAX_EXPR_DEPTH,
113723   SQLCIPHER_MAX_COMPOUND_SELECT,
113724   SQLCIPHER_MAX_VDBE_OP,
113725   SQLCIPHER_MAX_FUNCTION_ARG,
113726   SQLCIPHER_MAX_ATTACHED,
113727   SQLCIPHER_MAX_LIKE_PATTERN_LENGTH,
113728   SQLCIPHER_MAX_VARIABLE_NUMBER,
113729   SQLCIPHER_MAX_TRIGGER_DEPTH,
113730 };
113731
113732 /*
113733 ** Make sure the hard limits are set to reasonable values
113734 */
113735 #if SQLCIPHER_MAX_LENGTH<100
113736 # error SQLCIPHER_MAX_LENGTH must be at least 100
113737 #endif
113738 #if SQLCIPHER_MAX_SQL_LENGTH<100
113739 # error SQLCIPHER_MAX_SQL_LENGTH must be at least 100
113740 #endif
113741 #if SQLCIPHER_MAX_SQL_LENGTH>SQLCIPHER_MAX_LENGTH
113742 # error SQLCIPHER_MAX_SQL_LENGTH must not be greater than SQLCIPHER_MAX_LENGTH
113743 #endif
113744 #if SQLCIPHER_MAX_COMPOUND_SELECT<2
113745 # error SQLCIPHER_MAX_COMPOUND_SELECT must be at least 2
113746 #endif
113747 #if SQLCIPHER_MAX_VDBE_OP<40
113748 # error SQLCIPHER_MAX_VDBE_OP must be at least 40
113749 #endif
113750 #if SQLCIPHER_MAX_FUNCTION_ARG<0 || SQLCIPHER_MAX_FUNCTION_ARG>1000
113751 # error SQLCIPHER_MAX_FUNCTION_ARG must be between 0 and 1000
113752 #endif
113753 #if SQLCIPHER_MAX_ATTACHED<0 || SQLCIPHER_MAX_ATTACHED>62
113754 # error SQLCIPHER_MAX_ATTACHED must be between 0 and 62
113755 #endif
113756 #if SQLCIPHER_MAX_LIKE_PATTERN_LENGTH<1
113757 # error SQLCIPHER_MAX_LIKE_PATTERN_LENGTH must be at least 1
113758 #endif
113759 #if SQLCIPHER_MAX_COLUMN>32767
113760 # error SQLCIPHER_MAX_COLUMN must not exceed 32767
113761 #endif
113762 #if SQLCIPHER_MAX_TRIGGER_DEPTH<1
113763 # error SQLCIPHER_MAX_TRIGGER_DEPTH must be at least 1
113764 #endif
113765
113766
113767 /*
113768 ** Change the value of a limit.  Report the old value.
113769 ** If an invalid limit index is supplied, report -1.
113770 ** Make no changes but still report the old value if the
113771 ** new limit is negative.
113772 **
113773 ** A new lower limit does not shrink existing constructs.
113774 ** It merely prevents new constructs that exceed the limit
113775 ** from forming.
113776 */
113777 SQLCIPHER_API int sqlcipher3_limit(sqlcipher3 *db, int limitId, int newLimit){
113778   int oldLimit;
113779
113780
113781   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLCIPHER_LIMIT_NAME
113782   ** there is a hard upper bound set at compile-time by a C preprocessor
113783   ** macro called SQLCIPHER_MAX_NAME. (The "_LIMIT_" in the name is changed to
113784   ** "_MAX_".)
113785   */
113786   assert( aHardLimit[SQLCIPHER_LIMIT_LENGTH]==SQLCIPHER_MAX_LENGTH );
113787   assert( aHardLimit[SQLCIPHER_LIMIT_SQL_LENGTH]==SQLCIPHER_MAX_SQL_LENGTH );
113788   assert( aHardLimit[SQLCIPHER_LIMIT_COLUMN]==SQLCIPHER_MAX_COLUMN );
113789   assert( aHardLimit[SQLCIPHER_LIMIT_EXPR_DEPTH]==SQLCIPHER_MAX_EXPR_DEPTH );
113790   assert( aHardLimit[SQLCIPHER_LIMIT_COMPOUND_SELECT]==SQLCIPHER_MAX_COMPOUND_SELECT);
113791   assert( aHardLimit[SQLCIPHER_LIMIT_VDBE_OP]==SQLCIPHER_MAX_VDBE_OP );
113792   assert( aHardLimit[SQLCIPHER_LIMIT_FUNCTION_ARG]==SQLCIPHER_MAX_FUNCTION_ARG );
113793   assert( aHardLimit[SQLCIPHER_LIMIT_ATTACHED]==SQLCIPHER_MAX_ATTACHED );
113794   assert( aHardLimit[SQLCIPHER_LIMIT_LIKE_PATTERN_LENGTH]==
113795                                                SQLCIPHER_MAX_LIKE_PATTERN_LENGTH );
113796   assert( aHardLimit[SQLCIPHER_LIMIT_VARIABLE_NUMBER]==SQLCIPHER_MAX_VARIABLE_NUMBER);
113797   assert( aHardLimit[SQLCIPHER_LIMIT_TRIGGER_DEPTH]==SQLCIPHER_MAX_TRIGGER_DEPTH );
113798   assert( SQLCIPHER_LIMIT_TRIGGER_DEPTH==(SQLCIPHER_N_LIMIT-1) );
113799
113800
113801   if( limitId<0 || limitId>=SQLCIPHER_N_LIMIT ){
113802     return -1;
113803   }
113804   oldLimit = db->aLimit[limitId];
113805   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
113806     if( newLimit>aHardLimit[limitId] ){
113807       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
113808     }
113809     db->aLimit[limitId] = newLimit;
113810   }
113811   return oldLimit;                     /* IMP: R-53341-35419 */
113812 }
113813
113814 /*
113815 ** This function is used to parse both URIs and non-URI filenames passed by the
113816 ** user to API functions sqlcipher3_open() or sqlcipher3_open_v2(), and for database
113817 ** URIs specified as part of ATTACH statements.
113818 **
113819 ** The first argument to this function is the name of the VFS to use (or
113820 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
113821 ** query parameter. The second argument contains the URI (or non-URI filename)
113822 ** itself. When this function is called the *pFlags variable should contain
113823 ** the default flags to open the database handle with. The value stored in
113824 ** *pFlags may be updated before returning if the URI filename contains 
113825 ** "cache=xxx" or "mode=xxx" query parameters.
113826 **
113827 ** If successful, SQLCIPHER_OK is returned. In this case *ppVfs is set to point to
113828 ** the VFS that should be used to open the database file. *pzFile is set to
113829 ** point to a buffer containing the name of the file to open. It is the 
113830 ** responsibility of the caller to eventually call sqlcipher3_free() to release
113831 ** this buffer.
113832 **
113833 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
113834 ** may be set to point to a buffer containing an English language error 
113835 ** message. It is the responsibility of the caller to eventually release
113836 ** this buffer by calling sqlcipher3_free().
113837 */
113838 SQLCIPHER_PRIVATE int sqlcipher3ParseUri(
113839   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
113840   const char *zUri,               /* Nul-terminated URI to parse */
113841   unsigned int *pFlags,           /* IN/OUT: SQLCIPHER_OPEN_XXX flags */
113842   sqlcipher3_vfs **ppVfs,            /* OUT: VFS to use */ 
113843   char **pzFile,                  /* OUT: Filename component of URI */
113844   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLCIPHER_OK) */
113845 ){
113846   int rc = SQLCIPHER_OK;
113847   unsigned int flags = *pFlags;
113848   const char *zVfs = zDefaultVfs;
113849   char *zFile;
113850   char c;
113851   int nUri = sqlcipher3Strlen30(zUri);
113852
113853   assert( *pzErrMsg==0 );
113854
113855   if( ((flags & SQLCIPHER_OPEN_URI) || sqlcipher3GlobalConfig.bOpenUri) 
113856    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
113857   ){
113858     char *zOpt;
113859     int eState;                   /* Parser state when parsing URI */
113860     int iIn;                      /* Input character index */
113861     int iOut = 0;                 /* Output character index */
113862     int nByte = nUri+2;           /* Bytes of space to allocate */
113863
113864     /* Make sure the SQLCIPHER_OPEN_URI flag is set to indicate to the VFS xOpen 
113865     ** method that there may be extra parameters following the file-name.  */
113866     flags |= SQLCIPHER_OPEN_URI;
113867
113868     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
113869     zFile = sqlcipher3_malloc(nByte);
113870     if( !zFile ) return SQLCIPHER_NOMEM;
113871
113872     /* Discard the scheme and authority segments of the URI. */
113873     if( zUri[5]=='/' && zUri[6]=='/' ){
113874       iIn = 7;
113875       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
113876
113877       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
113878         *pzErrMsg = sqlcipher3_mprintf("invalid uri authority: %.*s", 
113879             iIn-7, &zUri[7]);
113880         rc = SQLCIPHER_ERROR;
113881         goto parse_uri_out;
113882       }
113883     }else{
113884       iIn = 5;
113885     }
113886
113887     /* Copy the filename and any query parameters into the zFile buffer. 
113888     ** Decode %HH escape codes along the way. 
113889     **
113890     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
113891     ** on the parsing context. As follows:
113892     **
113893     **   0: Parsing file-name.
113894     **   1: Parsing name section of a name=value query parameter.
113895     **   2: Parsing value section of a name=value query parameter.
113896     */
113897     eState = 0;
113898     while( (c = zUri[iIn])!=0 && c!='#' ){
113899       iIn++;
113900       if( c=='%' 
113901        && sqlcipher3Isxdigit(zUri[iIn]) 
113902        && sqlcipher3Isxdigit(zUri[iIn+1]) 
113903       ){
113904         int octet = (sqlcipher3HexToInt(zUri[iIn++]) << 4);
113905         octet += sqlcipher3HexToInt(zUri[iIn++]);
113906
113907         assert( octet>=0 && octet<256 );
113908         if( octet==0 ){
113909           /* This branch is taken when "%00" appears within the URI. In this
113910           ** case we ignore all text in the remainder of the path, name or
113911           ** value currently being parsed. So ignore the current character
113912           ** and skip to the next "?", "=" or "&", as appropriate. */
113913           while( (c = zUri[iIn])!=0 && c!='#' 
113914               && (eState!=0 || c!='?')
113915               && (eState!=1 || (c!='=' && c!='&'))
113916               && (eState!=2 || c!='&')
113917           ){
113918             iIn++;
113919           }
113920           continue;
113921         }
113922         c = octet;
113923       }else if( eState==1 && (c=='&' || c=='=') ){
113924         if( zFile[iOut-1]==0 ){
113925           /* An empty option name. Ignore this option altogether. */
113926           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
113927           continue;
113928         }
113929         if( c=='&' ){
113930           zFile[iOut++] = '\0';
113931         }else{
113932           eState = 2;
113933         }
113934         c = 0;
113935       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
113936         c = 0;
113937         eState = 1;
113938       }
113939       zFile[iOut++] = c;
113940     }
113941     if( eState==1 ) zFile[iOut++] = '\0';
113942     zFile[iOut++] = '\0';
113943     zFile[iOut++] = '\0';
113944
113945     /* Check if there were any options specified that should be interpreted 
113946     ** here. Options that are interpreted here include "vfs" and those that
113947     ** correspond to flags that may be passed to the sqlcipher3_open_v2()
113948     ** method. */
113949     zOpt = &zFile[sqlcipher3Strlen30(zFile)+1];
113950     while( zOpt[0] ){
113951       int nOpt = sqlcipher3Strlen30(zOpt);
113952       char *zVal = &zOpt[nOpt+1];
113953       int nVal = sqlcipher3Strlen30(zVal);
113954
113955       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
113956         zVfs = zVal;
113957       }else{
113958         struct OpenMode {
113959           const char *z;
113960           int mode;
113961         } *aMode = 0;
113962         char *zModeType = 0;
113963         int mask = 0;
113964         int limit = 0;
113965
113966         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
113967           static struct OpenMode aCacheMode[] = {
113968             { "shared",  SQLCIPHER_OPEN_SHAREDCACHE },
113969             { "private", SQLCIPHER_OPEN_PRIVATECACHE },
113970             { 0, 0 }
113971           };
113972
113973           mask = SQLCIPHER_OPEN_SHAREDCACHE|SQLCIPHER_OPEN_PRIVATECACHE;
113974           aMode = aCacheMode;
113975           limit = mask;
113976           zModeType = "cache";
113977         }
113978         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
113979           static struct OpenMode aOpenMode[] = {
113980             { "ro",  SQLCIPHER_OPEN_READONLY },
113981             { "rw",  SQLCIPHER_OPEN_READWRITE }, 
113982             { "rwc", SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE },
113983             { 0, 0 }
113984           };
113985
113986           mask = SQLCIPHER_OPEN_READONLY|SQLCIPHER_OPEN_READWRITE|SQLCIPHER_OPEN_CREATE;
113987           aMode = aOpenMode;
113988           limit = mask & flags;
113989           zModeType = "access";
113990         }
113991
113992         if( aMode ){
113993           int i;
113994           int mode = 0;
113995           for(i=0; aMode[i].z; i++){
113996             const char *z = aMode[i].z;
113997             if( nVal==sqlcipher3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
113998               mode = aMode[i].mode;
113999               break;
114000             }
114001           }
114002           if( mode==0 ){
114003             *pzErrMsg = sqlcipher3_mprintf("no such %s mode: %s", zModeType, zVal);
114004             rc = SQLCIPHER_ERROR;
114005             goto parse_uri_out;
114006           }
114007           if( mode>limit ){
114008             *pzErrMsg = sqlcipher3_mprintf("%s mode not allowed: %s",
114009                                         zModeType, zVal);
114010             rc = SQLCIPHER_PERM;
114011             goto parse_uri_out;
114012           }
114013           flags = (flags & ~mask) | mode;
114014         }
114015       }
114016
114017       zOpt = &zVal[nVal+1];
114018     }
114019
114020   }else{
114021     zFile = sqlcipher3_malloc(nUri+2);
114022     if( !zFile ) return SQLCIPHER_NOMEM;
114023     memcpy(zFile, zUri, nUri);
114024     zFile[nUri] = '\0';
114025     zFile[nUri+1] = '\0';
114026   }
114027
114028   *ppVfs = sqlcipher3_vfs_find(zVfs);
114029   if( *ppVfs==0 ){
114030     *pzErrMsg = sqlcipher3_mprintf("no such vfs: %s", zVfs);
114031     rc = SQLCIPHER_ERROR;
114032   }
114033  parse_uri_out:
114034   if( rc!=SQLCIPHER_OK ){
114035     sqlcipher3_free(zFile);
114036     zFile = 0;
114037   }
114038   *pFlags = flags;
114039   *pzFile = zFile;
114040   return rc;
114041 }
114042
114043
114044 /*
114045 ** This routine does the work of opening a database on behalf of
114046 ** sqlcipher3_open() and sqlcipher3_open16(). The database filename "zFilename"  
114047 ** is UTF-8 encoded.
114048 */
114049 static int openDatabase(
114050   const char *zFilename, /* Database filename UTF-8 encoded */
114051   sqlcipher3 **ppDb,        /* OUT: Returned database handle */
114052   unsigned int flags,    /* Operational flags */
114053   const char *zVfs       /* Name of the VFS to use */
114054 ){
114055   sqlcipher3 *db;                    /* Store allocated handle here */
114056   int rc;                         /* Return code */
114057   int isThreadsafe;               /* True for threadsafe connections */
114058   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
114059   char *zErrMsg = 0;              /* Error message from sqlcipher3ParseUri() */
114060
114061   *ppDb = 0;
114062 #ifndef SQLCIPHER_OMIT_AUTOINIT
114063   rc = sqlcipher3_initialize();
114064   if( rc ) return rc;
114065 #endif
114066
114067   /* Only allow sensible combinations of bits in the flags argument.  
114068   ** Throw an error if any non-sense combination is used.  If we
114069   ** do not block illegal combinations here, it could trigger
114070   ** assert() statements in deeper layers.  Sensible combinations
114071   ** are:
114072   **
114073   **  1:  SQLCIPHER_OPEN_READONLY
114074   **  2:  SQLCIPHER_OPEN_READWRITE
114075   **  6:  SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE
114076   */
114077   assert( SQLCIPHER_OPEN_READONLY  == 0x01 );
114078   assert( SQLCIPHER_OPEN_READWRITE == 0x02 );
114079   assert( SQLCIPHER_OPEN_CREATE    == 0x04 );
114080   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
114081   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
114082   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
114083   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLCIPHER_MISUSE_BKPT;
114084
114085   if( sqlcipher3GlobalConfig.bCoreMutex==0 ){
114086     isThreadsafe = 0;
114087   }else if( flags & SQLCIPHER_OPEN_NOMUTEX ){
114088     isThreadsafe = 0;
114089   }else if( flags & SQLCIPHER_OPEN_FULLMUTEX ){
114090     isThreadsafe = 1;
114091   }else{
114092     isThreadsafe = sqlcipher3GlobalConfig.bFullMutex;
114093   }
114094   if( flags & SQLCIPHER_OPEN_PRIVATECACHE ){
114095     flags &= ~SQLCIPHER_OPEN_SHAREDCACHE;
114096   }else if( sqlcipher3GlobalConfig.sharedCacheEnabled ){
114097     flags |= SQLCIPHER_OPEN_SHAREDCACHE;
114098   }
114099
114100   /* Remove harmful bits from the flags parameter
114101   **
114102   ** The SQLCIPHER_OPEN_NOMUTEX and SQLCIPHER_OPEN_FULLMUTEX flags were
114103   ** dealt with in the previous code block.  Besides these, the only
114104   ** valid input flags for sqlcipher3_open_v2() are SQLCIPHER_OPEN_READONLY,
114105   ** SQLCIPHER_OPEN_READWRITE, SQLCIPHER_OPEN_CREATE, SQLCIPHER_OPEN_SHAREDCACHE,
114106   ** SQLCIPHER_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
114107   ** off all other flags.
114108   */
114109   flags &=  ~( SQLCIPHER_OPEN_DELETEONCLOSE |
114110                SQLCIPHER_OPEN_EXCLUSIVE |
114111                SQLCIPHER_OPEN_MAIN_DB |
114112                SQLCIPHER_OPEN_TEMP_DB | 
114113                SQLCIPHER_OPEN_TRANSIENT_DB | 
114114                SQLCIPHER_OPEN_MAIN_JOURNAL | 
114115                SQLCIPHER_OPEN_TEMP_JOURNAL | 
114116                SQLCIPHER_OPEN_SUBJOURNAL | 
114117                SQLCIPHER_OPEN_MASTER_JOURNAL |
114118                SQLCIPHER_OPEN_NOMUTEX |
114119                SQLCIPHER_OPEN_FULLMUTEX |
114120                SQLCIPHER_OPEN_WAL
114121              );
114122
114123   /* Allocate the sqlcipher data structure */
114124   db = sqlcipher3MallocZero( sizeof(sqlcipher3) );
114125   if( db==0 ) goto opendb_out;
114126   if( isThreadsafe ){
114127     db->mutex = sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_RECURSIVE);
114128     if( db->mutex==0 ){
114129       sqlcipher3_free(db);
114130       db = 0;
114131       goto opendb_out;
114132     }
114133   }
114134   sqlcipher3_mutex_enter(db->mutex);
114135   db->errMask = 0xff;
114136   db->nDb = 2;
114137   db->magic = SQLCIPHER_MAGIC_BUSY;
114138   db->aDb = db->aDbStatic;
114139
114140   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
114141   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
114142   db->autoCommit = 1;
114143   db->nextAutovac = -1;
114144   db->nextPagesize = 0;
114145   db->flags |= SQLCIPHER_ShortColNames | SQLCIPHER_AutoIndex | SQLCIPHER_EnableTrigger
114146 #if SQLCIPHER_DEFAULT_FILE_FORMAT<4
114147                  | SQLCIPHER_LegacyFileFmt
114148 #endif
114149 #ifdef SQLCIPHER_ENABLE_LOAD_EXTENSION
114150                  | SQLCIPHER_LoadExtension
114151 #endif
114152 #if SQLCIPHER_DEFAULT_RECURSIVE_TRIGGERS
114153                  | SQLCIPHER_RecTriggers
114154 #endif
114155 #if defined(SQLCIPHER_DEFAULT_FOREIGN_KEYS) && SQLCIPHER_DEFAULT_FOREIGN_KEYS
114156                  | SQLCIPHER_ForeignKeys
114157 #endif
114158       ;
114159   sqlcipher3HashInit(&db->aCollSeq);
114160 #ifndef SQLCIPHER_OMIT_VIRTUALTABLE
114161   sqlcipher3HashInit(&db->aModule);
114162 #endif
114163
114164   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
114165   ** and UTF-16, so add a version for each to avoid any unnecessary
114166   ** conversions. The only error that can occur here is a malloc() failure.
114167   */
114168   createCollation(db, "BINARY", SQLCIPHER_UTF8, SQLCIPHER_COLL_BINARY, 0,
114169                   binCollFunc, 0);
114170   createCollation(db, "BINARY", SQLCIPHER_UTF16BE, SQLCIPHER_COLL_BINARY, 0,
114171                   binCollFunc, 0);
114172   createCollation(db, "BINARY", SQLCIPHER_UTF16LE, SQLCIPHER_COLL_BINARY, 0,
114173                   binCollFunc, 0);
114174   createCollation(db, "RTRIM", SQLCIPHER_UTF8, SQLCIPHER_COLL_USER, (void*)1,
114175                   binCollFunc, 0);
114176   if( db->mallocFailed ){
114177     goto opendb_out;
114178   }
114179   db->pDfltColl = sqlcipher3FindCollSeq(db, SQLCIPHER_UTF8, "BINARY", 0);
114180   assert( db->pDfltColl!=0 );
114181
114182   /* Also add a UTF-8 case-insensitive collation sequence. */
114183   createCollation(db, "NOCASE", SQLCIPHER_UTF8, SQLCIPHER_COLL_NOCASE, 0,
114184                   nocaseCollatingFunc, 0);
114185
114186   /* Parse the filename/URI argument. */
114187   db->openFlags = flags;
114188   rc = sqlcipher3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
114189   if( rc!=SQLCIPHER_OK ){
114190     if( rc==SQLCIPHER_NOMEM ) db->mallocFailed = 1;
114191     sqlcipher3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
114192     sqlcipher3_free(zErrMsg);
114193     goto opendb_out;
114194   }
114195
114196   /* Open the backend database driver */
114197   rc = sqlcipher3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
114198                         flags | SQLCIPHER_OPEN_MAIN_DB);
114199   if( rc!=SQLCIPHER_OK ){
114200     if( rc==SQLCIPHER_IOERR_NOMEM ){
114201       rc = SQLCIPHER_NOMEM;
114202     }
114203     sqlcipher3Error(db, rc, 0);
114204     goto opendb_out;
114205   }
114206   db->aDb[0].pSchema = sqlcipher3SchemaGet(db, db->aDb[0].pBt);
114207   db->aDb[1].pSchema = sqlcipher3SchemaGet(db, 0);
114208
114209
114210   /* The default safety_level for the main database is 'full'; for the temp
114211   ** database it is 'NONE'. This matches the pager layer defaults.  
114212   */
114213   db->aDb[0].zName = "main";
114214   db->aDb[0].safety_level = 3;
114215   db->aDb[1].zName = "temp";
114216   db->aDb[1].safety_level = 1;
114217
114218   db->magic = SQLCIPHER_MAGIC_OPEN;
114219   if( db->mallocFailed ){
114220     goto opendb_out;
114221   }
114222
114223   /* Register all built-in functions, but do not attempt to read the
114224   ** database schema yet. This is delayed until the first time the database
114225   ** is accessed.
114226   */
114227   sqlcipher3Error(db, SQLCIPHER_OK, 0);
114228   sqlcipher3RegisterBuiltinFunctions(db);
114229
114230   /* Load automatic extensions - extensions that have been registered
114231   ** using the sqlcipher3_automatic_extension() API.
114232   */
114233   sqlcipher3AutoLoadExtensions(db);
114234   rc = sqlcipher3_errcode(db);
114235   if( rc!=SQLCIPHER_OK ){
114236     goto opendb_out;
114237   }
114238
114239 #ifdef SQLCIPHER_ENABLE_FTS1
114240   if( !db->mallocFailed ){
114241     extern int sqlcipher3Fts1Init(sqlcipher3*);
114242     rc = sqlcipher3Fts1Init(db);
114243   }
114244 #endif
114245
114246 #ifdef SQLCIPHER_ENABLE_FTS2
114247   if( !db->mallocFailed && rc==SQLCIPHER_OK ){
114248     extern int sqlcipher3Fts2Init(sqlcipher3*);
114249     rc = sqlcipher3Fts2Init(db);
114250   }
114251 #endif
114252
114253 #ifdef SQLCIPHER_ENABLE_FTS3
114254   if( !db->mallocFailed && rc==SQLCIPHER_OK ){
114255     rc = sqlcipher3Fts3Init(db);
114256   }
114257 #endif
114258
114259 #ifdef SQLCIPHER_ENABLE_ICU
114260   if( !db->mallocFailed && rc==SQLCIPHER_OK ){
114261     rc = sqlcipher3IcuInit(db);
114262   }
114263 #endif
114264
114265 #ifdef SQLCIPHER_ENABLE_RTREE
114266   if( !db->mallocFailed && rc==SQLCIPHER_OK){
114267     rc = sqlcipher3RtreeInit(db);
114268   }
114269 #endif
114270
114271   sqlcipher3Error(db, rc, 0);
114272
114273   /* -DSQLCIPHER_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
114274   ** mode.  -DSQLCIPHER_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
114275   ** mode.  Doing nothing at all also makes NORMAL the default.
114276   */
114277 #ifdef SQLCIPHER_DEFAULT_LOCKING_MODE
114278   db->dfltLockMode = SQLCIPHER_DEFAULT_LOCKING_MODE;
114279   sqlcipher3PagerLockingMode(sqlcipher3BtreePager(db->aDb[0].pBt),
114280                           SQLCIPHER_DEFAULT_LOCKING_MODE);
114281 #endif
114282
114283   /* Enable the lookaside-malloc subsystem */
114284   setupLookaside(db, 0, sqlcipher3GlobalConfig.szLookaside,
114285                         sqlcipher3GlobalConfig.nLookaside);
114286
114287   sqlcipher3_wal_autocheckpoint(db, SQLCIPHER_DEFAULT_WAL_AUTOCHECKPOINT);
114288
114289 opendb_out:
114290   sqlcipher3_free(zOpen);
114291   if( db ){
114292     assert( db->mutex!=0 || isThreadsafe==0 || sqlcipher3GlobalConfig.bFullMutex==0 );
114293     sqlcipher3_mutex_leave(db->mutex);
114294   }
114295   rc = sqlcipher3_errcode(db);
114296   assert( db!=0 || rc==SQLCIPHER_NOMEM );
114297   if( rc==SQLCIPHER_NOMEM ){
114298     sqlcipher3_close(db);
114299     db = 0;
114300   }else if( rc!=SQLCIPHER_OK ){
114301     db->magic = SQLCIPHER_MAGIC_SICK;
114302   }
114303   *ppDb = db;
114304   return sqlcipher3ApiExit(0, rc);
114305 }
114306
114307 /*
114308 ** Open a new database handle.
114309 */
114310 SQLCIPHER_API int sqlcipher3_open(
114311   const char *zFilename, 
114312   sqlcipher3 **ppDb 
114313 ){
114314   return openDatabase(zFilename, ppDb,
114315                       SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE, 0);
114316 }
114317 SQLCIPHER_API int sqlcipher3_open_v2(
114318   const char *filename,   /* Database filename (UTF-8) */
114319   sqlcipher3 **ppDb,         /* OUT: SQLite db handle */
114320   int flags,              /* Flags */
114321   const char *zVfs        /* Name of VFS module to use */
114322 ){
114323   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
114324 }
114325
114326 #ifndef SQLCIPHER_OMIT_UTF16
114327 /*
114328 ** Open a new database handle.
114329 */
114330 SQLCIPHER_API int sqlcipher3_open16(
114331   const void *zFilename, 
114332   sqlcipher3 **ppDb
114333 ){
114334   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
114335   sqlcipher3_value *pVal;
114336   int rc;
114337
114338   assert( zFilename );
114339   assert( ppDb );
114340   *ppDb = 0;
114341 #ifndef SQLCIPHER_OMIT_AUTOINIT
114342   rc = sqlcipher3_initialize();
114343   if( rc ) return rc;
114344 #endif
114345   pVal = sqlcipher3ValueNew(0);
114346   sqlcipher3ValueSetStr(pVal, -1, zFilename, SQLCIPHER_UTF16NATIVE, SQLCIPHER_STATIC);
114347   zFilename8 = sqlcipher3ValueText(pVal, SQLCIPHER_UTF8);
114348   if( zFilename8 ){
114349     rc = openDatabase(zFilename8, ppDb,
114350                       SQLCIPHER_OPEN_READWRITE | SQLCIPHER_OPEN_CREATE, 0);
114351     assert( *ppDb || rc==SQLCIPHER_NOMEM );
114352     if( rc==SQLCIPHER_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
114353       ENC(*ppDb) = SQLCIPHER_UTF16NATIVE;
114354     }
114355   }else{
114356     rc = SQLCIPHER_NOMEM;
114357   }
114358   sqlcipher3ValueFree(pVal);
114359
114360   return sqlcipher3ApiExit(0, rc);
114361 }
114362 #endif /* SQLCIPHER_OMIT_UTF16 */
114363
114364 /*
114365 ** Register a new collation sequence with the database handle db.
114366 */
114367 SQLCIPHER_API int sqlcipher3_create_collation(
114368   sqlcipher3* db, 
114369   const char *zName, 
114370   int enc, 
114371   void* pCtx,
114372   int(*xCompare)(void*,int,const void*,int,const void*)
114373 ){
114374   int rc;
114375   sqlcipher3_mutex_enter(db->mutex);
114376   assert( !db->mallocFailed );
114377   rc = createCollation(db, zName, (u8)enc, SQLCIPHER_COLL_USER, pCtx, xCompare, 0);
114378   rc = sqlcipher3ApiExit(db, rc);
114379   sqlcipher3_mutex_leave(db->mutex);
114380   return rc;
114381 }
114382
114383 /*
114384 ** Register a new collation sequence with the database handle db.
114385 */
114386 SQLCIPHER_API int sqlcipher3_create_collation_v2(
114387   sqlcipher3* db, 
114388   const char *zName, 
114389   int enc, 
114390   void* pCtx,
114391   int(*xCompare)(void*,int,const void*,int,const void*),
114392   void(*xDel)(void*)
114393 ){
114394   int rc;
114395   sqlcipher3_mutex_enter(db->mutex);
114396   assert( !db->mallocFailed );
114397   rc = createCollation(db, zName, (u8)enc, SQLCIPHER_COLL_USER, pCtx, xCompare, xDel);
114398   rc = sqlcipher3ApiExit(db, rc);
114399   sqlcipher3_mutex_leave(db->mutex);
114400   return rc;
114401 }
114402
114403 #ifndef SQLCIPHER_OMIT_UTF16
114404 /*
114405 ** Register a new collation sequence with the database handle db.
114406 */
114407 SQLCIPHER_API int sqlcipher3_create_collation16(
114408   sqlcipher3* db, 
114409   const void *zName,
114410   int enc, 
114411   void* pCtx,
114412   int(*xCompare)(void*,int,const void*,int,const void*)
114413 ){
114414   int rc = SQLCIPHER_OK;
114415   char *zName8;
114416   sqlcipher3_mutex_enter(db->mutex);
114417   assert( !db->mallocFailed );
114418   zName8 = sqlcipher3Utf16to8(db, zName, -1, SQLCIPHER_UTF16NATIVE);
114419   if( zName8 ){
114420     rc = createCollation(db, zName8, (u8)enc, SQLCIPHER_COLL_USER, pCtx, xCompare, 0);
114421     sqlcipher3DbFree(db, zName8);
114422   }
114423   rc = sqlcipher3ApiExit(db, rc);
114424   sqlcipher3_mutex_leave(db->mutex);
114425   return rc;
114426 }
114427 #endif /* SQLCIPHER_OMIT_UTF16 */
114428
114429 /*
114430 ** Register a collation sequence factory callback with the database handle
114431 ** db. Replace any previously installed collation sequence factory.
114432 */
114433 SQLCIPHER_API int sqlcipher3_collation_needed(
114434   sqlcipher3 *db, 
114435   void *pCollNeededArg, 
114436   void(*xCollNeeded)(void*,sqlcipher3*,int eTextRep,const char*)
114437 ){
114438   sqlcipher3_mutex_enter(db->mutex);
114439   db->xCollNeeded = xCollNeeded;
114440   db->xCollNeeded16 = 0;
114441   db->pCollNeededArg = pCollNeededArg;
114442   sqlcipher3_mutex_leave(db->mutex);
114443   return SQLCIPHER_OK;
114444 }
114445
114446 #ifndef SQLCIPHER_OMIT_UTF16
114447 /*
114448 ** Register a collation sequence factory callback with the database handle
114449 ** db. Replace any previously installed collation sequence factory.
114450 */
114451 SQLCIPHER_API int sqlcipher3_collation_needed16(
114452   sqlcipher3 *db, 
114453   void *pCollNeededArg, 
114454   void(*xCollNeeded16)(void*,sqlcipher3*,int eTextRep,const void*)
114455 ){
114456   sqlcipher3_mutex_enter(db->mutex);
114457   db->xCollNeeded = 0;
114458   db->xCollNeeded16 = xCollNeeded16;
114459   db->pCollNeededArg = pCollNeededArg;
114460   sqlcipher3_mutex_leave(db->mutex);
114461   return SQLCIPHER_OK;
114462 }
114463 #endif /* SQLCIPHER_OMIT_UTF16 */
114464
114465 #ifndef SQLCIPHER_OMIT_DEPRECATED
114466 /*
114467 ** This function is now an anachronism. It used to be used to recover from a
114468 ** malloc() failure, but SQLite now does this automatically.
114469 */
114470 SQLCIPHER_API int sqlcipher3_global_recover(void){
114471   return SQLCIPHER_OK;
114472 }
114473 #endif
114474
114475 /*
114476 ** Test to see whether or not the database connection is in autocommit
114477 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
114478 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
114479 ** by the next COMMIT or ROLLBACK.
114480 **
114481 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
114482 */
114483 SQLCIPHER_API int sqlcipher3_get_autocommit(sqlcipher3 *db){
114484   return db->autoCommit;
114485 }
114486
114487 /*
114488 ** The following routines are subtitutes for constants SQLCIPHER_CORRUPT,
114489 ** SQLCIPHER_MISUSE, SQLCIPHER_CANTOPEN, SQLCIPHER_IOERR and possibly other error
114490 ** constants.  They server two purposes:
114491 **
114492 **   1.  Serve as a convenient place to set a breakpoint in a debugger
114493 **       to detect when version error conditions occurs.
114494 **
114495 **   2.  Invoke sqlcipher3_log() to provide the source code location where
114496 **       a low-level error is first detected.
114497 */
114498 SQLCIPHER_PRIVATE int sqlcipher3CorruptError(int lineno){
114499   testcase( sqlcipher3GlobalConfig.xLog!=0 );
114500   sqlcipher3_log(SQLCIPHER_CORRUPT,
114501               "database corruption at line %d of [%.10s]",
114502               lineno, 20+sqlcipher3_sourceid());
114503   return SQLCIPHER_CORRUPT;
114504 }
114505 SQLCIPHER_PRIVATE int sqlcipher3MisuseError(int lineno){
114506   testcase( sqlcipher3GlobalConfig.xLog!=0 );
114507   sqlcipher3_log(SQLCIPHER_MISUSE, 
114508               "misuse at line %d of [%.10s]",
114509               lineno, 20+sqlcipher3_sourceid());
114510   return SQLCIPHER_MISUSE;
114511 }
114512 SQLCIPHER_PRIVATE int sqlcipher3CantopenError(int lineno){
114513   testcase( sqlcipher3GlobalConfig.xLog!=0 );
114514   sqlcipher3_log(SQLCIPHER_CANTOPEN, 
114515               "cannot open file at line %d of [%.10s]",
114516               lineno, 20+sqlcipher3_sourceid());
114517   return SQLCIPHER_CANTOPEN;
114518 }
114519
114520
114521 #ifndef SQLCIPHER_OMIT_DEPRECATED
114522 /*
114523 ** This is a convenience routine that makes sure that all thread-specific
114524 ** data for this thread has been deallocated.
114525 **
114526 ** SQLite no longer uses thread-specific data so this routine is now a
114527 ** no-op.  It is retained for historical compatibility.
114528 */
114529 SQLCIPHER_API void sqlcipher3_thread_cleanup(void){
114530 }
114531 #endif
114532
114533 /*
114534 ** Return meta information about a specific column of a database table.
114535 ** See comment in sqlcipher3.h (sqlcipher.h.in) for details.
114536 */
114537 #ifdef SQLCIPHER_ENABLE_COLUMN_METADATA
114538 SQLCIPHER_API int sqlcipher3_table_column_metadata(
114539   sqlcipher3 *db,                /* Connection handle */
114540   const char *zDbName,        /* Database name or NULL */
114541   const char *zTableName,     /* Table name */
114542   const char *zColumnName,    /* Column name */
114543   char const **pzDataType,    /* OUTPUT: Declared data type */
114544   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
114545   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
114546   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
114547   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
114548 ){
114549   int rc;
114550   char *zErrMsg = 0;
114551   Table *pTab = 0;
114552   Column *pCol = 0;
114553   int iCol;
114554
114555   char const *zDataType = 0;
114556   char const *zCollSeq = 0;
114557   int notnull = 0;
114558   int primarykey = 0;
114559   int autoinc = 0;
114560
114561   /* Ensure the database schema has been loaded */
114562   sqlcipher3_mutex_enter(db->mutex);
114563   sqlcipher3BtreeEnterAll(db);
114564   rc = sqlcipher3Init(db, &zErrMsg);
114565   if( SQLCIPHER_OK!=rc ){
114566     goto error_out;
114567   }
114568
114569   /* Locate the table in question */
114570   pTab = sqlcipher3FindTable(db, zTableName, zDbName);
114571   if( !pTab || pTab->pSelect ){
114572     pTab = 0;
114573     goto error_out;
114574   }
114575
114576   /* Find the column for which info is requested */
114577   if( sqlcipher3IsRowid(zColumnName) ){
114578     iCol = pTab->iPKey;
114579     if( iCol>=0 ){
114580       pCol = &pTab->aCol[iCol];
114581     }
114582   }else{
114583     for(iCol=0; iCol<pTab->nCol; iCol++){
114584       pCol = &pTab->aCol[iCol];
114585       if( 0==sqlcipher3StrICmp(pCol->zName, zColumnName) ){
114586         break;
114587       }
114588     }
114589     if( iCol==pTab->nCol ){
114590       pTab = 0;
114591       goto error_out;
114592     }
114593   }
114594
114595   /* The following block stores the meta information that will be returned
114596   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
114597   ** and autoinc. At this point there are two possibilities:
114598   ** 
114599   **     1. The specified column name was rowid", "oid" or "_rowid_" 
114600   **        and there is no explicitly declared IPK column. 
114601   **
114602   **     2. The table is not a view and the column name identified an 
114603   **        explicitly declared column. Copy meta information from *pCol.
114604   */ 
114605   if( pCol ){
114606     zDataType = pCol->zType;
114607     zCollSeq = pCol->zColl;
114608     notnull = pCol->notNull!=0;
114609     primarykey  = pCol->isPrimKey!=0;
114610     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
114611   }else{
114612     zDataType = "INTEGER";
114613     primarykey = 1;
114614   }
114615   if( !zCollSeq ){
114616     zCollSeq = "BINARY";
114617   }
114618
114619 error_out:
114620   sqlcipher3BtreeLeaveAll(db);
114621
114622   /* Whether the function call succeeded or failed, set the output parameters
114623   ** to whatever their local counterparts contain. If an error did occur,
114624   ** this has the effect of zeroing all output parameters.
114625   */
114626   if( pzDataType ) *pzDataType = zDataType;
114627   if( pzCollSeq ) *pzCollSeq = zCollSeq;
114628   if( pNotNull ) *pNotNull = notnull;
114629   if( pPrimaryKey ) *pPrimaryKey = primarykey;
114630   if( pAutoinc ) *pAutoinc = autoinc;
114631
114632   if( SQLCIPHER_OK==rc && !pTab ){
114633     sqlcipher3DbFree(db, zErrMsg);
114634     zErrMsg = sqlcipher3MPrintf(db, "no such table column: %s.%s", zTableName,
114635         zColumnName);
114636     rc = SQLCIPHER_ERROR;
114637   }
114638   sqlcipher3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
114639   sqlcipher3DbFree(db, zErrMsg);
114640   rc = sqlcipher3ApiExit(db, rc);
114641   sqlcipher3_mutex_leave(db->mutex);
114642   return rc;
114643 }
114644 #endif
114645
114646 /*
114647 ** Sleep for a little while.  Return the amount of time slept.
114648 */
114649 SQLCIPHER_API int sqlcipher3_sleep(int ms){
114650   sqlcipher3_vfs *pVfs;
114651   int rc;
114652   pVfs = sqlcipher3_vfs_find(0);
114653   if( pVfs==0 ) return 0;
114654
114655   /* This function works in milliseconds, but the underlying OsSleep() 
114656   ** API uses microseconds. Hence the 1000's.
114657   */
114658   rc = (sqlcipher3OsSleep(pVfs, 1000*ms)/1000);
114659   return rc;
114660 }
114661
114662 /*
114663 ** Enable or disable the extended result codes.
114664 */
114665 SQLCIPHER_API int sqlcipher3_extended_result_codes(sqlcipher3 *db, int onoff){
114666   sqlcipher3_mutex_enter(db->mutex);
114667   db->errMask = onoff ? 0xffffffff : 0xff;
114668   sqlcipher3_mutex_leave(db->mutex);
114669   return SQLCIPHER_OK;
114670 }
114671
114672 /*
114673 ** Invoke the xFileControl method on a particular database.
114674 */
114675 SQLCIPHER_API int sqlcipher3_file_control(sqlcipher3 *db, const char *zDbName, int op, void *pArg){
114676   int rc = SQLCIPHER_ERROR;
114677   int iDb;
114678   sqlcipher3_mutex_enter(db->mutex);
114679   if( zDbName==0 ){
114680     iDb = 0;
114681   }else{
114682     for(iDb=0; iDb<db->nDb; iDb++){
114683       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
114684     }
114685   }
114686   if( iDb<db->nDb ){
114687     Btree *pBtree = db->aDb[iDb].pBt;
114688     if( pBtree ){
114689       Pager *pPager;
114690       sqlcipher3_file *fd;
114691       sqlcipher3BtreeEnter(pBtree);
114692       pPager = sqlcipher3BtreePager(pBtree);
114693       assert( pPager!=0 );
114694       fd = sqlcipher3PagerFile(pPager);
114695       assert( fd!=0 );
114696       if( op==SQLCIPHER_FCNTL_FILE_POINTER ){
114697         *(sqlcipher3_file**)pArg = fd;
114698         rc = SQLCIPHER_OK;
114699       }else if( fd->pMethods ){
114700         rc = sqlcipher3OsFileControl(fd, op, pArg);
114701       }else{
114702         rc = SQLCIPHER_NOTFOUND;
114703       }
114704       sqlcipher3BtreeLeave(pBtree);
114705     }
114706   }
114707   sqlcipher3_mutex_leave(db->mutex);
114708   return rc;   
114709 }
114710
114711 /*
114712 ** Interface to the testing logic.
114713 */
114714 SQLCIPHER_API int sqlcipher3_test_control(int op, ...){
114715   int rc = 0;
114716 #ifndef SQLCIPHER_OMIT_BUILTIN_TEST
114717   va_list ap;
114718   va_start(ap, op);
114719   switch( op ){
114720
114721     /*
114722     ** Save the current state of the PRNG.
114723     */
114724     case SQLCIPHER_TESTCTRL_PRNG_SAVE: {
114725       sqlcipher3PrngSaveState();
114726       break;
114727     }
114728
114729     /*
114730     ** Restore the state of the PRNG to the last state saved using
114731     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
114732     ** this verb acts like PRNG_RESET.
114733     */
114734     case SQLCIPHER_TESTCTRL_PRNG_RESTORE: {
114735       sqlcipher3PrngRestoreState();
114736       break;
114737     }
114738
114739     /*
114740     ** Reset the PRNG back to its uninitialized state.  The next call
114741     ** to sqlcipher3_randomness() will reseed the PRNG using a single call
114742     ** to the xRandomness method of the default VFS.
114743     */
114744     case SQLCIPHER_TESTCTRL_PRNG_RESET: {
114745       sqlcipher3PrngResetState();
114746       break;
114747     }
114748
114749     /*
114750     **  sqlcipher3_test_control(BITVEC_TEST, size, program)
114751     **
114752     ** Run a test against a Bitvec object of size.  The program argument
114753     ** is an array of integers that defines the test.  Return -1 on a
114754     ** memory allocation error, 0 on success, or non-zero for an error.
114755     ** See the sqlcipher3BitvecBuiltinTest() for additional information.
114756     */
114757     case SQLCIPHER_TESTCTRL_BITVEC_TEST: {
114758       int sz = va_arg(ap, int);
114759       int *aProg = va_arg(ap, int*);
114760       rc = sqlcipher3BitvecBuiltinTest(sz, aProg);
114761       break;
114762     }
114763
114764     /*
114765     **  sqlcipher3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
114766     **
114767     ** Register hooks to call to indicate which malloc() failures 
114768     ** are benign.
114769     */
114770     case SQLCIPHER_TESTCTRL_BENIGN_MALLOC_HOOKS: {
114771       typedef void (*void_function)(void);
114772       void_function xBenignBegin;
114773       void_function xBenignEnd;
114774       xBenignBegin = va_arg(ap, void_function);
114775       xBenignEnd = va_arg(ap, void_function);
114776       sqlcipher3BenignMallocHooks(xBenignBegin, xBenignEnd);
114777       break;
114778     }
114779
114780     /*
114781     **  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_PENDING_BYTE, unsigned int X)
114782     **
114783     ** Set the PENDING byte to the value in the argument, if X>0.
114784     ** Make no changes if X==0.  Return the value of the pending byte
114785     ** as it existing before this routine was called.
114786     **
114787     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
114788     ** an incompatible database file format.  Changing the PENDING byte
114789     ** while any database connection is open results in undefined and
114790     ** dileterious behavior.
114791     */
114792     case SQLCIPHER_TESTCTRL_PENDING_BYTE: {
114793       rc = PENDING_BYTE;
114794 #ifndef SQLCIPHER_OMIT_WSD
114795       {
114796         unsigned int newVal = va_arg(ap, unsigned int);
114797         if( newVal ) sqlcipher3PendingByte = newVal;
114798       }
114799 #endif
114800       break;
114801     }
114802
114803     /*
114804     **  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ASSERT, int X)
114805     **
114806     ** This action provides a run-time test to see whether or not
114807     ** assert() was enabled at compile-time.  If X is true and assert()
114808     ** is enabled, then the return value is true.  If X is true and
114809     ** assert() is disabled, then the return value is zero.  If X is
114810     ** false and assert() is enabled, then the assertion fires and the
114811     ** process aborts.  If X is false and assert() is disabled, then the
114812     ** return value is zero.
114813     */
114814     case SQLCIPHER_TESTCTRL_ASSERT: {
114815       volatile int x = 0;
114816       assert( (x = va_arg(ap,int))!=0 );
114817       rc = x;
114818       break;
114819     }
114820
114821
114822     /*
114823     **  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ALWAYS, int X)
114824     **
114825     ** This action provides a run-time test to see how the ALWAYS and
114826     ** NEVER macros were defined at compile-time.
114827     **
114828     ** The return value is ALWAYS(X).  
114829     **
114830     ** The recommended test is X==2.  If the return value is 2, that means
114831     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
114832     ** default setting.  If the return value is 1, then ALWAYS() is either
114833     ** hard-coded to true or else it asserts if its argument is false.
114834     ** The first behavior (hard-coded to true) is the case if
114835     ** SQLCIPHER_TESTCTRL_ASSERT shows that assert() is disabled and the second
114836     ** behavior (assert if the argument to ALWAYS() is false) is the case if
114837     ** SQLCIPHER_TESTCTRL_ASSERT shows that assert() is enabled.
114838     **
114839     ** The run-time test procedure might look something like this:
114840     **
114841     **    if( sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ALWAYS, 2)==2 ){
114842     **      // ALWAYS() and NEVER() are no-op pass-through macros
114843     **    }else if( sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ASSERT, 1) ){
114844     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
114845     **    }else{
114846     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
114847     **    }
114848     */
114849     case SQLCIPHER_TESTCTRL_ALWAYS: {
114850       int x = va_arg(ap,int);
114851       rc = ALWAYS(x);
114852       break;
114853     }
114854
114855     /*   sqlcipher3_test_control(SQLCIPHER_TESTCTRL_RESERVE, sqlcipher3 *db, int N)
114856     **
114857     ** Set the nReserve size to N for the main database on the database
114858     ** connection db.
114859     */
114860     case SQLCIPHER_TESTCTRL_RESERVE: {
114861       sqlcipher3 *db = va_arg(ap, sqlcipher3*);
114862       int x = va_arg(ap,int);
114863       sqlcipher3_mutex_enter(db->mutex);
114864       sqlcipher3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
114865       sqlcipher3_mutex_leave(db->mutex);
114866       break;
114867     }
114868
114869     /*  sqlcipher3_test_control(SQLCIPHER_TESTCTRL_OPTIMIZATIONS, sqlcipher3 *db, int N)
114870     **
114871     ** Enable or disable various optimizations for testing purposes.  The 
114872     ** argument N is a bitmask of optimizations to be disabled.  For normal
114873     ** operation N should be 0.  The idea is that a test program (like the
114874     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
114875     ** with various optimizations disabled to verify that the same answer
114876     ** is obtained in every case.
114877     */
114878     case SQLCIPHER_TESTCTRL_OPTIMIZATIONS: {
114879       sqlcipher3 *db = va_arg(ap, sqlcipher3*);
114880       int x = va_arg(ap,int);
114881       db->flags = (x & SQLCIPHER_OptMask) | (db->flags & ~SQLCIPHER_OptMask);
114882       break;
114883     }
114884
114885 #ifdef SQLCIPHER_N_KEYWORD
114886     /* sqlcipher3_test_control(SQLCIPHER_TESTCTRL_ISKEYWORD, const char *zWord)
114887     **
114888     ** If zWord is a keyword recognized by the parser, then return the
114889     ** number of keywords.  Or if zWord is not a keyword, return 0.
114890     ** 
114891     ** This test feature is only available in the amalgamation since
114892     ** the SQLCIPHER_N_KEYWORD macro is not defined in this file if SQLite
114893     ** is built using separate source files.
114894     */
114895     case SQLCIPHER_TESTCTRL_ISKEYWORD: {
114896       const char *zWord = va_arg(ap, const char*);
114897       int n = sqlcipher3Strlen30(zWord);
114898       rc = (sqlcipher3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLCIPHER_N_KEYWORD : 0;
114899       break;
114900     }
114901 #endif 
114902
114903     /* sqlcipher3_test_control(SQLCIPHER_TESTCTRL_PGHDRSZ)
114904     **
114905     ** Return the size of a pcache header in bytes.
114906     */
114907     case SQLCIPHER_TESTCTRL_PGHDRSZ: {
114908       rc = sizeof(PgHdr);
114909       break;
114910     }
114911
114912     /* sqlcipher3_test_control(SQLCIPHER_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
114913     **
114914     ** Pass pFree into sqlcipher3ScratchFree(). 
114915     ** If sz>0 then allocate a scratch buffer into pNew.  
114916     */
114917     case SQLCIPHER_TESTCTRL_SCRATCHMALLOC: {
114918       void *pFree, **ppNew;
114919       int sz;
114920       sz = va_arg(ap, int);
114921       ppNew = va_arg(ap, void**);
114922       pFree = va_arg(ap, void*);
114923       if( sz ) *ppNew = sqlcipher3ScratchMalloc(sz);
114924       sqlcipher3ScratchFree(pFree);
114925       break;
114926     }
114927
114928     /*   sqlcipher3_test_control(SQLCIPHER_TESTCTRL_LOCALTIME_FAULT, int onoff);
114929     **
114930     ** If parameter onoff is non-zero, configure the wrappers so that all
114931     ** subsequent calls to localtime() and variants fail. If onoff is zero,
114932     ** undo this setting.
114933     */
114934     case SQLCIPHER_TESTCTRL_LOCALTIME_FAULT: {
114935       sqlcipher3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
114936       break;
114937     }
114938
114939   }
114940   va_end(ap);
114941 #endif /* SQLCIPHER_OMIT_BUILTIN_TEST */
114942   return rc;
114943 }
114944
114945 /*
114946 ** This is a utility routine, useful to VFS implementations, that checks
114947 ** to see if a database file was a URI that contained a specific query 
114948 ** parameter, and if so obtains the value of the query parameter.
114949 **
114950 ** The zFilename argument is the filename pointer passed into the xOpen()
114951 ** method of a VFS implementation.  The zParam argument is the name of the
114952 ** query parameter we seek.  This routine returns the value of the zParam
114953 ** parameter if it exists.  If the parameter does not exist, this routine
114954 ** returns a NULL pointer.
114955 */
114956 SQLCIPHER_API const char *sqlcipher3_uri_parameter(const char *zFilename, const char *zParam){
114957   zFilename += sqlcipher3Strlen30(zFilename) + 1;
114958   while( zFilename[0] ){
114959     int x = strcmp(zFilename, zParam);
114960     zFilename += sqlcipher3Strlen30(zFilename) + 1;
114961     if( x==0 ) return zFilename;
114962     zFilename += sqlcipher3Strlen30(zFilename) + 1;
114963   }
114964   return 0;
114965 }
114966
114967 /************** End of main.c ************************************************/
114968 /************** Begin file notify.c ******************************************/
114969 /*
114970 ** 2009 March 3
114971 **
114972 ** The author disclaims copyright to this source code.  In place of
114973 ** a legal notice, here is a blessing:
114974 **
114975 **    May you do good and not evil.
114976 **    May you find forgiveness for yourself and forgive others.
114977 **    May you share freely, never taking more than you give.
114978 **
114979 *************************************************************************
114980 **
114981 ** This file contains the implementation of the sqlcipher3_unlock_notify()
114982 ** API method and its associated functionality.
114983 */
114984
114985 /* Omit this entire file if SQLCIPHER_ENABLE_UNLOCK_NOTIFY is not defined. */
114986 #ifdef SQLCIPHER_ENABLE_UNLOCK_NOTIFY
114987
114988 /*
114989 ** Public interfaces:
114990 **
114991 **   sqlcipher3ConnectionBlocked()
114992 **   sqlcipher3ConnectionUnlocked()
114993 **   sqlcipher3ConnectionClosed()
114994 **   sqlcipher3_unlock_notify()
114995 */
114996
114997 #define assertMutexHeld() \
114998   assert( sqlcipher3_mutex_held(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER)) )
114999
115000 /*
115001 ** Head of a linked list of all sqlcipher3 objects created by this process
115002 ** for which either sqlcipher3.pBlockingConnection or sqlcipher3.pUnlockConnection
115003 ** is not NULL. This variable may only accessed while the STATIC_MASTER
115004 ** mutex is held.
115005 */
115006 static sqlcipher3 *SQLCIPHER_WSD sqlcipher3BlockedList = 0;
115007
115008 #ifndef NDEBUG
115009 /*
115010 ** This function is a complex assert() that verifies the following 
115011 ** properties of the blocked connections list:
115012 **
115013 **   1) Each entry in the list has a non-NULL value for either 
115014 **      pUnlockConnection or pBlockingConnection, or both.
115015 **
115016 **   2) All entries in the list that share a common value for 
115017 **      xUnlockNotify are grouped together.
115018 **
115019 **   3) If the argument db is not NULL, then none of the entries in the
115020 **      blocked connections list have pUnlockConnection or pBlockingConnection
115021 **      set to db. This is used when closing connection db.
115022 */
115023 static void checkListProperties(sqlcipher3 *db){
115024   sqlcipher3 *p;
115025   for(p=sqlcipher3BlockedList; p; p=p->pNextBlocked){
115026     int seen = 0;
115027     sqlcipher3 *p2;
115028
115029     /* Verify property (1) */
115030     assert( p->pUnlockConnection || p->pBlockingConnection );
115031
115032     /* Verify property (2) */
115033     for(p2=sqlcipher3BlockedList; p2!=p; p2=p2->pNextBlocked){
115034       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
115035       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
115036       assert( db==0 || p->pUnlockConnection!=db );
115037       assert( db==0 || p->pBlockingConnection!=db );
115038     }
115039   }
115040 }
115041 #else
115042 # define checkListProperties(x)
115043 #endif
115044
115045 /*
115046 ** Remove connection db from the blocked connections list. If connection
115047 ** db is not currently a part of the list, this function is a no-op.
115048 */
115049 static void removeFromBlockedList(sqlcipher3 *db){
115050   sqlcipher3 **pp;
115051   assertMutexHeld();
115052   for(pp=&sqlcipher3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
115053     if( *pp==db ){
115054       *pp = (*pp)->pNextBlocked;
115055       break;
115056     }
115057   }
115058 }
115059
115060 /*
115061 ** Add connection db to the blocked connections list. It is assumed
115062 ** that it is not already a part of the list.
115063 */
115064 static void addToBlockedList(sqlcipher3 *db){
115065   sqlcipher3 **pp;
115066   assertMutexHeld();
115067   for(
115068     pp=&sqlcipher3BlockedList; 
115069     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
115070     pp=&(*pp)->pNextBlocked
115071   );
115072   db->pNextBlocked = *pp;
115073   *pp = db;
115074 }
115075
115076 /*
115077 ** Obtain the STATIC_MASTER mutex.
115078 */
115079 static void enterMutex(void){
115080   sqlcipher3_mutex_enter(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
115081   checkListProperties(0);
115082 }
115083
115084 /*
115085 ** Release the STATIC_MASTER mutex.
115086 */
115087 static void leaveMutex(void){
115088   assertMutexHeld();
115089   checkListProperties(0);
115090   sqlcipher3_mutex_leave(sqlcipher3MutexAlloc(SQLCIPHER_MUTEX_STATIC_MASTER));
115091 }
115092
115093 /*
115094 ** Register an unlock-notify callback.
115095 **
115096 ** This is called after connection "db" has attempted some operation
115097 ** but has received an SQLCIPHER_LOCKED error because another connection
115098 ** (call it pOther) in the same process was busy using the same shared
115099 ** cache.  pOther is found by looking at db->pBlockingConnection.
115100 **
115101 ** If there is no blocking connection, the callback is invoked immediately,
115102 ** before this routine returns.
115103 **
115104 ** If pOther is already blocked on db, then report SQLCIPHER_LOCKED, to indicate
115105 ** a deadlock.
115106 **
115107 ** Otherwise, make arrangements to invoke xNotify when pOther drops
115108 ** its locks.
115109 **
115110 ** Each call to this routine overrides any prior callbacks registered
115111 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
115112 ** cancelled.
115113 */
115114 SQLCIPHER_API int sqlcipher3_unlock_notify(
115115   sqlcipher3 *db,
115116   void (*xNotify)(void **, int),
115117   void *pArg
115118 ){
115119   int rc = SQLCIPHER_OK;
115120
115121   sqlcipher3_mutex_enter(db->mutex);
115122   enterMutex();
115123
115124   if( xNotify==0 ){
115125     removeFromBlockedList(db);
115126     db->pBlockingConnection = 0;
115127     db->pUnlockConnection = 0;
115128     db->xUnlockNotify = 0;
115129     db->pUnlockArg = 0;
115130   }else if( 0==db->pBlockingConnection ){
115131     /* The blocking transaction has been concluded. Or there never was a 
115132     ** blocking transaction. In either case, invoke the notify callback
115133     ** immediately. 
115134     */
115135     xNotify(&pArg, 1);
115136   }else{
115137     sqlcipher3 *p;
115138
115139     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
115140     if( p ){
115141       rc = SQLCIPHER_LOCKED;              /* Deadlock detected. */
115142     }else{
115143       db->pUnlockConnection = db->pBlockingConnection;
115144       db->xUnlockNotify = xNotify;
115145       db->pUnlockArg = pArg;
115146       removeFromBlockedList(db);
115147       addToBlockedList(db);
115148     }
115149   }
115150
115151   leaveMutex();
115152   assert( !db->mallocFailed );
115153   sqlcipher3Error(db, rc, (rc?"database is deadlocked":0));
115154   sqlcipher3_mutex_leave(db->mutex);
115155   return rc;
115156 }
115157
115158 /*
115159 ** This function is called while stepping or preparing a statement 
115160 ** associated with connection db. The operation will return SQLCIPHER_LOCKED
115161 ** to the user because it requires a lock that will not be available
115162 ** until connection pBlocker concludes its current transaction.
115163 */
115164 SQLCIPHER_PRIVATE void sqlcipher3ConnectionBlocked(sqlcipher3 *db, sqlcipher3 *pBlocker){
115165   enterMutex();
115166   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
115167     addToBlockedList(db);
115168   }
115169   db->pBlockingConnection = pBlocker;
115170   leaveMutex();
115171 }
115172
115173 /*
115174 ** This function is called when
115175 ** the transaction opened by database db has just finished. Locks held 
115176 ** by database connection db have been released.
115177 **
115178 ** This function loops through each entry in the blocked connections
115179 ** list and does the following:
115180 **
115181 **   1) If the sqlcipher3.pBlockingConnection member of a list entry is
115182 **      set to db, then set pBlockingConnection=0.
115183 **
115184 **   2) If the sqlcipher3.pUnlockConnection member of a list entry is
115185 **      set to db, then invoke the configured unlock-notify callback and
115186 **      set pUnlockConnection=0.
115187 **
115188 **   3) If the two steps above mean that pBlockingConnection==0 and
115189 **      pUnlockConnection==0, remove the entry from the blocked connections
115190 **      list.
115191 */
115192 SQLCIPHER_PRIVATE void sqlcipher3ConnectionUnlocked(sqlcipher3 *db){
115193   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
115194   int nArg = 0;                            /* Number of entries in aArg[] */
115195   sqlcipher3 **pp;                            /* Iterator variable */
115196   void **aArg;               /* Arguments to the unlock callback */
115197   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
115198   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
115199
115200   aArg = aStatic;
115201   enterMutex();         /* Enter STATIC_MASTER mutex */
115202
115203   /* This loop runs once for each entry in the blocked-connections list. */
115204   for(pp=&sqlcipher3BlockedList; *pp; /* no-op */ ){
115205     sqlcipher3 *p = *pp;
115206
115207     /* Step 1. */
115208     if( p->pBlockingConnection==db ){
115209       p->pBlockingConnection = 0;
115210     }
115211
115212     /* Step 2. */
115213     if( p->pUnlockConnection==db ){
115214       assert( p->xUnlockNotify );
115215       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
115216         xUnlockNotify(aArg, nArg);
115217         nArg = 0;
115218       }
115219
115220       sqlcipher3BeginBenignMalloc();
115221       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
115222       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
115223       if( (!aDyn && nArg==(int)ArraySize(aStatic))
115224        || (aDyn && nArg==(int)(sqlcipher3MallocSize(aDyn)/sizeof(void*)))
115225       ){
115226         /* The aArg[] array needs to grow. */
115227         void **pNew = (void **)sqlcipher3Malloc(nArg*sizeof(void *)*2);
115228         if( pNew ){
115229           memcpy(pNew, aArg, nArg*sizeof(void *));
115230           sqlcipher3_free(aDyn);
115231           aDyn = aArg = pNew;
115232         }else{
115233           /* This occurs when the array of context pointers that need to
115234           ** be passed to the unlock-notify callback is larger than the
115235           ** aStatic[] array allocated on the stack and the attempt to 
115236           ** allocate a larger array from the heap has failed.
115237           **
115238           ** This is a difficult situation to handle. Returning an error
115239           ** code to the caller is insufficient, as even if an error code
115240           ** is returned the transaction on connection db will still be
115241           ** closed and the unlock-notify callbacks on blocked connections
115242           ** will go unissued. This might cause the application to wait
115243           ** indefinitely for an unlock-notify callback that will never 
115244           ** arrive.
115245           **
115246           ** Instead, invoke the unlock-notify callback with the context
115247           ** array already accumulated. We can then clear the array and
115248           ** begin accumulating any further context pointers without 
115249           ** requiring any dynamic allocation. This is sub-optimal because
115250           ** it means that instead of one callback with a large array of
115251           ** context pointers the application will receive two or more
115252           ** callbacks with smaller arrays of context pointers, which will
115253           ** reduce the applications ability to prioritize multiple 
115254           ** connections. But it is the best that can be done under the
115255           ** circumstances.
115256           */
115257           xUnlockNotify(aArg, nArg);
115258           nArg = 0;
115259         }
115260       }
115261       sqlcipher3EndBenignMalloc();
115262
115263       aArg[nArg++] = p->pUnlockArg;
115264       xUnlockNotify = p->xUnlockNotify;
115265       p->pUnlockConnection = 0;
115266       p->xUnlockNotify = 0;
115267       p->pUnlockArg = 0;
115268     }
115269
115270     /* Step 3. */
115271     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
115272       /* Remove connection p from the blocked connections list. */
115273       *pp = p->pNextBlocked;
115274       p->pNextBlocked = 0;
115275     }else{
115276       pp = &p->pNextBlocked;
115277     }
115278   }
115279
115280   if( nArg!=0 ){
115281     xUnlockNotify(aArg, nArg);
115282   }
115283   sqlcipher3_free(aDyn);
115284   leaveMutex();         /* Leave STATIC_MASTER mutex */
115285 }
115286
115287 /*
115288 ** This is called when the database connection passed as an argument is 
115289 ** being closed. The connection is removed from the blocked list.
115290 */
115291 SQLCIPHER_PRIVATE void sqlcipher3ConnectionClosed(sqlcipher3 *db){
115292   sqlcipher3ConnectionUnlocked(db);
115293   enterMutex();
115294   removeFromBlockedList(db);
115295   checkListProperties(db);
115296   leaveMutex();
115297 }
115298 #endif
115299
115300 /************** End of notify.c **********************************************/
115301 /************** Begin file fts3.c ********************************************/
115302 /*
115303 ** 2006 Oct 10
115304 **
115305 ** The author disclaims copyright to this source code.  In place of
115306 ** a legal notice, here is a blessing:
115307 **
115308 **    May you do good and not evil.
115309 **    May you find forgiveness for yourself and forgive others.
115310 **    May you share freely, never taking more than you give.
115311 **
115312 ******************************************************************************
115313 **
115314 ** This is an SQLite module implementing full-text search.
115315 */
115316
115317 /*
115318 ** The code in this file is only compiled if:
115319 **
115320 **     * The FTS3 module is being built as an extension
115321 **       (in which case SQLCIPHER_CORE is not defined), or
115322 **
115323 **     * The FTS3 module is being built into the core of
115324 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
115325 */
115326
115327 /* The full-text index is stored in a series of b+tree (-like)
115328 ** structures called segments which map terms to doclists.  The
115329 ** structures are like b+trees in layout, but are constructed from the
115330 ** bottom up in optimal fashion and are not updatable.  Since trees
115331 ** are built from the bottom up, things will be described from the
115332 ** bottom up.
115333 **
115334 **
115335 **** Varints ****
115336 ** The basic unit of encoding is a variable-length integer called a
115337 ** varint.  We encode variable-length integers in little-endian order
115338 ** using seven bits * per byte as follows:
115339 **
115340 ** KEY:
115341 **         A = 0xxxxxxx    7 bits of data and one flag bit
115342 **         B = 1xxxxxxx    7 bits of data and one flag bit
115343 **
115344 **  7 bits - A
115345 ** 14 bits - BA
115346 ** 21 bits - BBA
115347 ** and so on.
115348 **
115349 ** This is similar in concept to how sqlcipher encodes "varints" but
115350 ** the encoding is not the same.  SQLite varints are big-endian
115351 ** are are limited to 9 bytes in length whereas FTS3 varints are
115352 ** little-endian and can be up to 10 bytes in length (in theory).
115353 **
115354 ** Example encodings:
115355 **
115356 **     1:    0x01
115357 **   127:    0x7f
115358 **   128:    0x81 0x00
115359 **
115360 **
115361 **** Document lists ****
115362 ** A doclist (document list) holds a docid-sorted list of hits for a
115363 ** given term.  Doclists hold docids and associated token positions.
115364 ** A docid is the unique integer identifier for a single document.
115365 ** A position is the index of a word within the document.  The first 
115366 ** word of the document has a position of 0.
115367 **
115368 ** FTS3 used to optionally store character offsets using a compile-time
115369 ** option.  But that functionality is no longer supported.
115370 **
115371 ** A doclist is stored like this:
115372 **
115373 ** array {
115374 **   varint docid;
115375 **   array {                (position list for column 0)
115376 **     varint position;     (2 more than the delta from previous position)
115377 **   }
115378 **   array {
115379 **     varint POS_COLUMN;   (marks start of position list for new column)
115380 **     varint column;       (index of new column)
115381 **     array {
115382 **       varint position;   (2 more than the delta from previous position)
115383 **     }
115384 **   }
115385 **   varint POS_END;        (marks end of positions for this document.
115386 ** }
115387 **
115388 ** Here, array { X } means zero or more occurrences of X, adjacent in
115389 ** memory.  A "position" is an index of a token in the token stream
115390 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
115391 ** in the same logical place as the position element, and act as sentinals
115392 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
115393 ** The positions numbers are not stored literally but rather as two more
115394 ** than the difference from the prior position, or the just the position plus
115395 ** 2 for the first position.  Example:
115396 **
115397 **   label:       A B C D E  F  G H   I  J K
115398 **   value:     123 5 9 1 1 14 35 0 234 72 0
115399 **
115400 ** The 123 value is the first docid.  For column zero in this document
115401 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
115402 ** at D signals the start of a new column; the 1 at E indicates that the
115403 ** new column is column number 1.  There are two positions at 12 and 45
115404 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
115405 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
115406 ** terminates with the 0 at K.
115407 **
115408 ** A "position-list" is the list of positions for multiple columns for
115409 ** a single docid.  A "column-list" is the set of positions for a single
115410 ** column.  Hence, a position-list consists of one or more column-lists,
115411 ** a document record consists of a docid followed by a position-list and
115412 ** a doclist consists of one or more document records.
115413 **
115414 ** A bare doclist omits the position information, becoming an 
115415 ** array of varint-encoded docids.
115416 **
115417 **** Segment leaf nodes ****
115418 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
115419 ** nodes are written using LeafWriter, and read using LeafReader (to
115420 ** iterate through a single leaf node's data) and LeavesReader (to
115421 ** iterate through a segment's entire leaf layer).  Leaf nodes have
115422 ** the format:
115423 **
115424 ** varint iHeight;             (height from leaf level, always 0)
115425 ** varint nTerm;               (length of first term)
115426 ** char pTerm[nTerm];          (content of first term)
115427 ** varint nDoclist;            (length of term's associated doclist)
115428 ** char pDoclist[nDoclist];    (content of doclist)
115429 ** array {
115430 **                             (further terms are delta-encoded)
115431 **   varint nPrefix;           (length of prefix shared with previous term)
115432 **   varint nSuffix;           (length of unshared suffix)
115433 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
115434 **   varint nDoclist;          (length of term's associated doclist)
115435 **   char pDoclist[nDoclist];  (content of doclist)
115436 ** }
115437 **
115438 ** Here, array { X } means zero or more occurrences of X, adjacent in
115439 ** memory.
115440 **
115441 ** Leaf nodes are broken into blocks which are stored contiguously in
115442 ** the %_segments table in sorted order.  This means that when the end
115443 ** of a node is reached, the next term is in the node with the next
115444 ** greater node id.
115445 **
115446 ** New data is spilled to a new leaf node when the current node
115447 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
115448 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
115449 ** node (a leaf node with a single term and doclist).  The goal of
115450 ** these settings is to pack together groups of small doclists while
115451 ** making it efficient to directly access large doclists.  The
115452 ** assumption is that large doclists represent terms which are more
115453 ** likely to be query targets.
115454 **
115455 ** TODO(shess) It may be useful for blocking decisions to be more
115456 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
115457 ** node rather than splitting into 2k and .5k nodes.  My intuition is
115458 ** that this might extend through 2x or 4x the pagesize.
115459 **
115460 **
115461 **** Segment interior nodes ****
115462 ** Segment interior nodes store blockids for subtree nodes and terms
115463 ** to describe what data is stored by the each subtree.  Interior
115464 ** nodes are written using InteriorWriter, and read using
115465 ** InteriorReader.  InteriorWriters are created as needed when
115466 ** SegmentWriter creates new leaf nodes, or when an interior node
115467 ** itself grows too big and must be split.  The format of interior
115468 ** nodes:
115469 **
115470 ** varint iHeight;           (height from leaf level, always >0)
115471 ** varint iBlockid;          (block id of node's leftmost subtree)
115472 ** optional {
115473 **   varint nTerm;           (length of first term)
115474 **   char pTerm[nTerm];      (content of first term)
115475 **   array {
115476 **                                (further terms are delta-encoded)
115477 **     varint nPrefix;            (length of shared prefix with previous term)
115478 **     varint nSuffix;            (length of unshared suffix)
115479 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
115480 **   }
115481 ** }
115482 **
115483 ** Here, optional { X } means an optional element, while array { X }
115484 ** means zero or more occurrences of X, adjacent in memory.
115485 **
115486 ** An interior node encodes n terms separating n+1 subtrees.  The
115487 ** subtree blocks are contiguous, so only the first subtree's blockid
115488 ** is encoded.  The subtree at iBlockid will contain all terms less
115489 ** than the first term encoded (or all terms if no term is encoded).
115490 ** Otherwise, for terms greater than or equal to pTerm[i] but less
115491 ** than pTerm[i+1], the subtree for that term will be rooted at
115492 ** iBlockid+i.  Interior nodes only store enough term data to
115493 ** distinguish adjacent children (if the rightmost term of the left
115494 ** child is "something", and the leftmost term of the right child is
115495 ** "wicked", only "w" is stored).
115496 **
115497 ** New data is spilled to a new interior node at the same height when
115498 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
115499 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
115500 ** interior nodes and making the tree too skinny.  The interior nodes
115501 ** at a given height are naturally tracked by interior nodes at
115502 ** height+1, and so on.
115503 **
115504 **
115505 **** Segment directory ****
115506 ** The segment directory in table %_segdir stores meta-information for
115507 ** merging and deleting segments, and also the root node of the
115508 ** segment's tree.
115509 **
115510 ** The root node is the top node of the segment's tree after encoding
115511 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
115512 ** This could be either a leaf node or an interior node.  If the top
115513 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
115514 ** and a new root interior node is generated (which should always fit
115515 ** within ROOT_MAX because it only needs space for 2 varints, the
115516 ** height and the blockid of the previous root).
115517 **
115518 ** The meta-information in the segment directory is:
115519 **   level               - segment level (see below)
115520 **   idx                 - index within level
115521 **                       - (level,idx uniquely identify a segment)
115522 **   start_block         - first leaf node
115523 **   leaves_end_block    - last leaf node
115524 **   end_block           - last block (including interior nodes)
115525 **   root                - contents of root node
115526 **
115527 ** If the root node is a leaf node, then start_block,
115528 ** leaves_end_block, and end_block are all 0.
115529 **
115530 **
115531 **** Segment merging ****
115532 ** To amortize update costs, segments are grouped into levels and
115533 ** merged in batches.  Each increase in level represents exponentially
115534 ** more documents.
115535 **
115536 ** New documents (actually, document updates) are tokenized and
115537 ** written individually (using LeafWriter) to a level 0 segment, with
115538 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
115539 ** level 0 segments are merged into a single level 1 segment.  Level 1
115540 ** is populated like level 0, and eventually MERGE_COUNT level 1
115541 ** segments are merged to a single level 2 segment (representing
115542 ** MERGE_COUNT^2 updates), and so on.
115543 **
115544 ** A segment merge traverses all segments at a given level in
115545 ** parallel, performing a straightforward sorted merge.  Since segment
115546 ** leaf nodes are written in to the %_segments table in order, this
115547 ** merge traverses the underlying sqlcipher disk structures efficiently.
115548 ** After the merge, all segment blocks from the merged level are
115549 ** deleted.
115550 **
115551 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
115552 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
115553 ** very similar performance numbers to 16 on insertion, though they're
115554 ** a tiny bit slower (perhaps due to more overhead in merge-time
115555 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
115556 ** 16, 2 about 66% slower than 16.
115557 **
115558 ** At query time, high MERGE_COUNT increases the number of segments
115559 ** which need to be scanned and merged.  For instance, with 100k docs
115560 ** inserted:
115561 **
115562 **    MERGE_COUNT   segments
115563 **       16           25
115564 **        8           12
115565 **        4           10
115566 **        2            6
115567 **
115568 ** This appears to have only a moderate impact on queries for very
115569 ** frequent terms (which are somewhat dominated by segment merge
115570 ** costs), and infrequent and non-existent terms still seem to be fast
115571 ** even with many segments.
115572 **
115573 ** TODO(shess) That said, it would be nice to have a better query-side
115574 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
115575 ** optimizations to things like doclist merging will swing the sweet
115576 ** spot around.
115577 **
115578 **
115579 **
115580 **** Handling of deletions and updates ****
115581 ** Since we're using a segmented structure, with no docid-oriented
115582 ** index into the term index, we clearly cannot simply update the term
115583 ** index when a document is deleted or updated.  For deletions, we
115584 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
115585 ** we simply write the new doclist.  Segment merges overwrite older
115586 ** data for a particular docid with newer data, so deletes or updates
115587 ** will eventually overtake the earlier data and knock it out.  The
115588 ** query logic likewise merges doclists so that newer data knocks out
115589 ** older data.
115590 **
115591 ** TODO(shess) Provide a VACUUM type operation to clear out all
115592 ** deletions and duplications.  This would basically be a forced merge
115593 ** into a single segment.
115594 */
115595
115596 /************** Include fts3Int.h in the middle of fts3.c ********************/
115597 /************** Begin file fts3Int.h *****************************************/
115598 /*
115599 ** 2009 Nov 12
115600 **
115601 ** The author disclaims copyright to this source code.  In place of
115602 ** a legal notice, here is a blessing:
115603 **
115604 **    May you do good and not evil.
115605 **    May you find forgiveness for yourself and forgive others.
115606 **    May you share freely, never taking more than you give.
115607 **
115608 ******************************************************************************
115609 **
115610 */
115611 #ifndef _FTSINT_H
115612 #define _FTSINT_H
115613
115614 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
115615 # define NDEBUG 1
115616 #endif
115617
115618 /*
115619 ** FTS4 is really an extension for FTS3.  It is enabled using the
115620 ** SQLCIPHER_ENABLE_FTS3 macro.  But to avoid confusion we also all
115621 ** the SQLCIPHER_ENABLE_FTS4 macro to serve as an alisse for SQLCIPHER_ENABLE_FTS3.
115622 */
115623 #if defined(SQLCIPHER_ENABLE_FTS4) && !defined(SQLCIPHER_ENABLE_FTS3)
115624 # define SQLCIPHER_ENABLE_FTS3
115625 #endif
115626
115627 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
115628
115629 /* If not building as part of the core, include sqlcipher3ext.h. */
115630 #ifndef SQLCIPHER_CORE
115631 SQLCIPHER_API extern const sqlcipher3_api_routines *sqlcipher3_api;
115632 #endif
115633
115634 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
115635 /************** Begin file fts3_tokenizer.h **********************************/
115636 /*
115637 ** 2006 July 10
115638 **
115639 ** The author disclaims copyright to this source code.
115640 **
115641 *************************************************************************
115642 ** Defines the interface to tokenizers used by fulltext-search.  There
115643 ** are three basic components:
115644 **
115645 ** sqlcipher3_tokenizer_module is a singleton defining the tokenizer
115646 ** interface functions.  This is essentially the class structure for
115647 ** tokenizers.
115648 **
115649 ** sqlcipher3_tokenizer is used to define a particular tokenizer, perhaps
115650 ** including customization information defined at creation time.
115651 **
115652 ** sqlcipher3_tokenizer_cursor is generated by a tokenizer to generate
115653 ** tokens from a particular input.
115654 */
115655 #ifndef _FTS3_TOKENIZER_H_
115656 #define _FTS3_TOKENIZER_H_
115657
115658 /* TODO(shess) Only used for SQLCIPHER_OK and SQLCIPHER_DONE at this time.
115659 ** If tokenizers are to be allowed to call sqlcipher3_*() functions, then
115660 ** we will need a way to register the API consistently.
115661 */
115662
115663 /*
115664 ** Structures used by the tokenizer interface. When a new tokenizer
115665 ** implementation is registered, the caller provides a pointer to
115666 ** an sqlcipher3_tokenizer_module containing pointers to the callback
115667 ** functions that make up an implementation.
115668 **
115669 ** When an fts3 table is created, it passes any arguments passed to
115670 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
115671 ** sqlcipher3_tokenizer_module.xCreate() function of the requested tokenizer
115672 ** implementation. The xCreate() function in turn returns an 
115673 ** sqlcipher3_tokenizer structure representing the specific tokenizer to
115674 ** be used for the fts3 table (customized by the tokenizer clause arguments).
115675 **
115676 ** To tokenize an input buffer, the sqlcipher3_tokenizer_module.xOpen()
115677 ** method is called. It returns an sqlcipher3_tokenizer_cursor object
115678 ** that may be used to tokenize a specific input buffer based on
115679 ** the tokenization rules supplied by a specific sqlcipher3_tokenizer
115680 ** object.
115681 */
115682 typedef struct sqlcipher3_tokenizer_module sqlcipher3_tokenizer_module;
115683 typedef struct sqlcipher3_tokenizer sqlcipher3_tokenizer;
115684 typedef struct sqlcipher3_tokenizer_cursor sqlcipher3_tokenizer_cursor;
115685
115686 struct sqlcipher3_tokenizer_module {
115687
115688   /*
115689   ** Structure version. Should always be set to 0.
115690   */
115691   int iVersion;
115692
115693   /*
115694   ** Create a new tokenizer. The values in the argv[] array are the
115695   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
115696   ** TABLE statement that created the fts3 table. For example, if
115697   ** the following SQL is executed:
115698   **
115699   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
115700   **
115701   ** then argc is set to 2, and the argv[] array contains pointers
115702   ** to the strings "arg1" and "arg2".
115703   **
115704   ** This method should return either SQLCIPHER_OK (0), or an SQLite error 
115705   ** code. If SQLCIPHER_OK is returned, then *ppTokenizer should be set
115706   ** to point at the newly created tokenizer structure. The generic
115707   ** sqlcipher3_tokenizer.pModule variable should not be initialised by
115708   ** this callback. The caller will do so.
115709   */
115710   int (*xCreate)(
115711     int argc,                           /* Size of argv array */
115712     const char *const*argv,             /* Tokenizer argument strings */
115713     sqlcipher3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
115714   );
115715
115716   /*
115717   ** Destroy an existing tokenizer. The fts3 module calls this method
115718   ** exactly once for each successful call to xCreate().
115719   */
115720   int (*xDestroy)(sqlcipher3_tokenizer *pTokenizer);
115721
115722   /*
115723   ** Create a tokenizer cursor to tokenize an input buffer. The caller
115724   ** is responsible for ensuring that the input buffer remains valid
115725   ** until the cursor is closed (using the xClose() method). 
115726   */
115727   int (*xOpen)(
115728     sqlcipher3_tokenizer *pTokenizer,       /* Tokenizer object */
115729     const char *pInput, int nBytes,      /* Input buffer */
115730     sqlcipher3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
115731   );
115732
115733   /*
115734   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
115735   ** method exactly once for each successful call to xOpen().
115736   */
115737   int (*xClose)(sqlcipher3_tokenizer_cursor *pCursor);
115738
115739   /*
115740   ** Retrieve the next token from the tokenizer cursor pCursor. This
115741   ** method should either return SQLCIPHER_OK and set the values of the
115742   ** "OUT" variables identified below, or SQLCIPHER_DONE to indicate that
115743   ** the end of the buffer has been reached, or an SQLite error code.
115744   **
115745   ** *ppToken should be set to point at a buffer containing the 
115746   ** normalized version of the token (i.e. after any case-folding and/or
115747   ** stemming has been performed). *pnBytes should be set to the length
115748   ** of this buffer in bytes. The input text that generated the token is
115749   ** identified by the byte offsets returned in *piStartOffset and
115750   ** *piEndOffset. *piStartOffset should be set to the index of the first
115751   ** byte of the token in the input buffer. *piEndOffset should be set
115752   ** to the index of the first byte just past the end of the token in
115753   ** the input buffer.
115754   **
115755   ** The buffer *ppToken is set to point at is managed by the tokenizer
115756   ** implementation. It is only required to be valid until the next call
115757   ** to xNext() or xClose(). 
115758   */
115759   /* TODO(shess) current implementation requires pInput to be
115760   ** nul-terminated.  This should either be fixed, or pInput/nBytes
115761   ** should be converted to zInput.
115762   */
115763   int (*xNext)(
115764     sqlcipher3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
115765     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
115766     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
115767     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
115768     int *piPosition      /* OUT: Number of tokens returned before this one */
115769   );
115770 };
115771
115772 struct sqlcipher3_tokenizer {
115773   const sqlcipher3_tokenizer_module *pModule;  /* The module for this tokenizer */
115774   /* Tokenizer implementations will typically add additional fields */
115775 };
115776
115777 struct sqlcipher3_tokenizer_cursor {
115778   sqlcipher3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
115779   /* Tokenizer implementations will typically add additional fields */
115780 };
115781
115782 int fts3_global_term_cnt(int iTerm, int iCol);
115783 int fts3_term_cnt(int iTerm, int iCol);
115784
115785
115786 #endif /* _FTS3_TOKENIZER_H_ */
115787
115788 /************** End of fts3_tokenizer.h **************************************/
115789 /************** Continuing where we left off in fts3Int.h ********************/
115790 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
115791 /************** Begin file fts3_hash.h ***************************************/
115792 /*
115793 ** 2001 September 22
115794 **
115795 ** The author disclaims copyright to this source code.  In place of
115796 ** a legal notice, here is a blessing:
115797 **
115798 **    May you do good and not evil.
115799 **    May you find forgiveness for yourself and forgive others.
115800 **    May you share freely, never taking more than you give.
115801 **
115802 *************************************************************************
115803 ** This is the header file for the generic hash-table implemenation
115804 ** used in SQLite.  We've modified it slightly to serve as a standalone
115805 ** hash table implementation for the full-text indexing module.
115806 **
115807 */
115808 #ifndef _FTS3_HASH_H_
115809 #define _FTS3_HASH_H_
115810
115811 /* Forward declarations of structures. */
115812 typedef struct Fts3Hash Fts3Hash;
115813 typedef struct Fts3HashElem Fts3HashElem;
115814
115815 /* A complete hash table is an instance of the following structure.
115816 ** The internals of this structure are intended to be opaque -- client
115817 ** code should not attempt to access or modify the fields of this structure
115818 ** directly.  Change this structure only by using the routines below.
115819 ** However, many of the "procedures" and "functions" for modifying and
115820 ** accessing this structure are really macros, so we can't really make
115821 ** this structure opaque.
115822 */
115823 struct Fts3Hash {
115824   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
115825   char copyKey;           /* True if copy of key made on insert */
115826   int count;              /* Number of entries in this table */
115827   Fts3HashElem *first;    /* The first element of the array */
115828   int htsize;             /* Number of buckets in the hash table */
115829   struct _fts3ht {        /* the hash table */
115830     int count;               /* Number of entries with this hash */
115831     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
115832   } *ht;
115833 };
115834
115835 /* Each element in the hash table is an instance of the following 
115836 ** structure.  All elements are stored on a single doubly-linked list.
115837 **
115838 ** Again, this structure is intended to be opaque, but it can't really
115839 ** be opaque because it is used by macros.
115840 */
115841 struct Fts3HashElem {
115842   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
115843   void *data;                /* Data associated with this element */
115844   void *pKey; int nKey;      /* Key associated with this element */
115845 };
115846
115847 /*
115848 ** There are 2 different modes of operation for a hash table:
115849 **
115850 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
115851 **                           (including the null-terminator, if any).  Case
115852 **                           is respected in comparisons.
115853 **
115854 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
115855 **                           memcmp() is used to compare keys.
115856 **
115857 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
115858 */
115859 #define FTS3_HASH_STRING    1
115860 #define FTS3_HASH_BINARY    2
115861
115862 /*
115863 ** Access routines.  To delete, insert a NULL pointer.
115864 */
115865 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
115866 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
115867 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
115868 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashClear(Fts3Hash*);
115869 SQLCIPHER_PRIVATE Fts3HashElem *sqlcipher3Fts3HashFindElem(const Fts3Hash *, const void *, int);
115870
115871 /*
115872 ** Shorthand for the functions above
115873 */
115874 #define fts3HashInit     sqlcipher3Fts3HashInit
115875 #define fts3HashInsert   sqlcipher3Fts3HashInsert
115876 #define fts3HashFind     sqlcipher3Fts3HashFind
115877 #define fts3HashClear    sqlcipher3Fts3HashClear
115878 #define fts3HashFindElem sqlcipher3Fts3HashFindElem
115879
115880 /*
115881 ** Macros for looping over all elements of a hash table.  The idiom is
115882 ** like this:
115883 **
115884 **   Fts3Hash h;
115885 **   Fts3HashElem *p;
115886 **   ...
115887 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
115888 **     SomeStructure *pData = fts3HashData(p);
115889 **     // do something with pData
115890 **   }
115891 */
115892 #define fts3HashFirst(H)  ((H)->first)
115893 #define fts3HashNext(E)   ((E)->next)
115894 #define fts3HashData(E)   ((E)->data)
115895 #define fts3HashKey(E)    ((E)->pKey)
115896 #define fts3HashKeysize(E) ((E)->nKey)
115897
115898 /*
115899 ** Number of entries in a hash table
115900 */
115901 #define fts3HashCount(H)  ((H)->count)
115902
115903 #endif /* _FTS3_HASH_H_ */
115904
115905 /************** End of fts3_hash.h *******************************************/
115906 /************** Continuing where we left off in fts3Int.h ********************/
115907
115908 /*
115909 ** This constant controls how often segments are merged. Once there are
115910 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
115911 ** segment of level N+1.
115912 */
115913 #define FTS3_MERGE_COUNT 16
115914
115915 /*
115916 ** This is the maximum amount of data (in bytes) to store in the 
115917 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
115918 ** populated as documents are inserted/updated/deleted in a transaction
115919 ** and used to create a new segment when the transaction is committed.
115920 ** However if this limit is reached midway through a transaction, a new 
115921 ** segment is created and the hash table cleared immediately.
115922 */
115923 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
115924
115925 /*
115926 ** Macro to return the number of elements in an array. SQLite has a
115927 ** similar macro called ArraySize(). Use a different name to avoid
115928 ** a collision when building an amalgamation with built-in FTS3.
115929 */
115930 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
115931
115932
115933 #ifndef MIN
115934 # define MIN(x,y) ((x)<(y)?(x):(y))
115935 #endif
115936
115937 /*
115938 ** Maximum length of a varint encoded integer. The varint format is different
115939 ** from that used by SQLite, so the maximum length is 10, not 9.
115940 */
115941 #define FTS3_VARINT_MAX 10
115942
115943 /*
115944 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
115945 ** in the document set and zero or more prefix indexes. All indexes are stored
115946 ** as one or more b+-trees in the %_segments and %_segdir tables. 
115947 **
115948 ** It is possible to determine which index a b+-tree belongs to based on the
115949 ** value stored in the "%_segdir.level" column. Given this value L, the index
115950 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
115951 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
115952 ** between 1024 and 2047 to index 1, and so on.
115953 **
115954 ** It is considered impossible for an index to use more than 1024 levels. In 
115955 ** theory though this may happen, but only after at least 
115956 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
115957 */
115958 #define FTS3_SEGDIR_MAXLEVEL      1024
115959 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
115960
115961 /*
115962 ** The testcase() macro is only used by the amalgamation.  If undefined,
115963 ** make it a no-op.
115964 */
115965 #ifndef testcase
115966 # define testcase(X)
115967 #endif
115968
115969 /*
115970 ** Terminator values for position-lists and column-lists.
115971 */
115972 #define POS_COLUMN  (1)     /* Column-list terminator */
115973 #define POS_END     (0)     /* Position-list terminator */ 
115974
115975 /*
115976 ** This section provides definitions to allow the
115977 ** FTS3 extension to be compiled outside of the 
115978 ** amalgamation.
115979 */
115980 #ifndef SQLCIPHER_AMALGAMATION
115981 /*
115982 ** Macros indicating that conditional expressions are always true or
115983 ** false.
115984 */
115985 #ifdef SQLCIPHER_COVERAGE_TEST
115986 # define ALWAYS(x) (1)
115987 # define NEVER(X)  (0)
115988 #else
115989 # define ALWAYS(x) (x)
115990 # define NEVER(X)  (x)
115991 #endif
115992
115993 /*
115994 ** Internal types used by SQLite.
115995 */
115996 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
115997 typedef short int i16;            /* 2-byte (or larger) signed integer */
115998 typedef unsigned int u32;         /* 4-byte unsigned integer */
115999 typedef sqlcipher3_uint64 u64;       /* 8-byte unsigned integer */
116000
116001 /*
116002 ** Macro used to suppress compiler warnings for unused parameters.
116003 */
116004 #define UNUSED_PARAMETER(x) (void)(x)
116005
116006 /*
116007 ** Activate assert() only if SQLCIPHER_TEST is enabled.
116008 */
116009 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
116010 # define NDEBUG 1
116011 #endif
116012
116013 /*
116014 ** The TESTONLY macro is used to enclose variable declarations or
116015 ** other bits of code that are needed to support the arguments
116016 ** within testcase() and assert() macros.
116017 */
116018 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
116019 # define TESTONLY(X)  X
116020 #else
116021 # define TESTONLY(X)
116022 #endif
116023
116024 #endif /* SQLCIPHER_AMALGAMATION */
116025
116026 #ifdef SQLCIPHER_DEBUG
116027 SQLCIPHER_PRIVATE int sqlcipher3Fts3Corrupt(void);
116028 # define FTS_CORRUPT_VTAB sqlcipher3Fts3Corrupt()
116029 #else
116030 # define FTS_CORRUPT_VTAB SQLCIPHER_CORRUPT_VTAB
116031 #endif
116032
116033 typedef struct Fts3Table Fts3Table;
116034 typedef struct Fts3Cursor Fts3Cursor;
116035 typedef struct Fts3Expr Fts3Expr;
116036 typedef struct Fts3Phrase Fts3Phrase;
116037 typedef struct Fts3PhraseToken Fts3PhraseToken;
116038
116039 typedef struct Fts3Doclist Fts3Doclist;
116040 typedef struct Fts3SegFilter Fts3SegFilter;
116041 typedef struct Fts3DeferredToken Fts3DeferredToken;
116042 typedef struct Fts3SegReader Fts3SegReader;
116043 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
116044
116045 /*
116046 ** A connection to a fulltext index is an instance of the following
116047 ** structure. The xCreate and xConnect methods create an instance
116048 ** of this structure and xDestroy and xDisconnect free that instance.
116049 ** All other methods receive a pointer to the structure as one of their
116050 ** arguments.
116051 */
116052 struct Fts3Table {
116053   sqlcipher3_vtab base;              /* Base class used by SQLite core */
116054   sqlcipher3 *db;                    /* The database connection */
116055   const char *zDb;                /* logical database name */
116056   const char *zName;              /* virtual table name */
116057   int nColumn;                    /* number of named columns in virtual table */
116058   char **azColumn;                /* column names.  malloced */
116059   sqlcipher3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
116060   char *zContentTbl;              /* content=xxx option, or NULL */
116061
116062   /* Precompiled statements used by the implementation. Each of these 
116063   ** statements is run and reset within a single virtual table API call. 
116064   */
116065   sqlcipher3_stmt *aStmt[27];
116066
116067   char *zReadExprlist;
116068   char *zWriteExprlist;
116069
116070   int nNodeSize;                  /* Soft limit for node size */
116071   u8 bHasStat;                    /* True if %_stat table exists */
116072   u8 bHasDocsize;                 /* True if %_docsize table exists */
116073   u8 bDescIdx;                    /* True if doclists are in reverse order */
116074   int nPgsz;                      /* Page size for host database */
116075   char *zSegmentsTbl;             /* Name of %_segments table */
116076   sqlcipher3_blob *pSegments;        /* Blob handle open on %_segments table */
116077
116078   /* TODO: Fix the first paragraph of this comment.
116079   **
116080   ** The following hash table is used to buffer pending index updates during
116081   ** transactions. Variable nPendingData estimates the memory size of the 
116082   ** pending data, including hash table overhead, but not malloc overhead. 
116083   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
116084   ** automatically. Variable iPrevDocid is the docid of the most recently
116085   ** inserted record.
116086   **
116087   ** A single FTS4 table may have multiple full-text indexes. For each index
116088   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
116089   ** terms that appear in the document set. Each subsequent index in aIndex[]
116090   ** is an index of prefixes of a specific length.
116091   */
116092   int nIndex;                     /* Size of aIndex[] */
116093   struct Fts3Index {
116094     int nPrefix;                  /* Prefix length (0 for main terms index) */
116095     Fts3Hash hPending;            /* Pending terms table for this index */
116096   } *aIndex;
116097   int nMaxPendingData;            /* Max pending data before flush to disk */
116098   int nPendingData;               /* Current bytes of pending data */
116099   sqlcipher_int64 iPrevDocid;        /* Docid of most recently inserted document */
116100
116101 #if defined(SQLCIPHER_DEBUG) || defined(SQLCIPHER_COVERAGE_TEST)
116102   /* State variables used for validating that the transaction control
116103   ** methods of the virtual table are called at appropriate times.  These
116104   ** values do not contribution to the FTS computation; they are used for
116105   ** verifying the SQLite core.
116106   */
116107   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
116108   int mxSavepoint;       /* Largest valid xSavepoint integer */
116109 #endif
116110 };
116111
116112 /*
116113 ** When the core wants to read from the virtual table, it creates a
116114 ** virtual table cursor (an instance of the following structure) using
116115 ** the xOpen method. Cursors are destroyed using the xClose method.
116116 */
116117 struct Fts3Cursor {
116118   sqlcipher3_vtab_cursor base;       /* Base class used by SQLite core */
116119   i16 eSearch;                    /* Search strategy (see below) */
116120   u8 isEof;                       /* True if at End Of Results */
116121   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
116122   sqlcipher3_stmt *pStmt;            /* Prepared statement in use by the cursor */
116123   Fts3Expr *pExpr;                /* Parsed MATCH query string */
116124   int nPhrase;                    /* Number of matchable phrases in query */
116125   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
116126   sqlcipher3_int64 iPrevId;          /* Previous id read from aDoclist */
116127   char *pNextId;                  /* Pointer into the body of aDoclist */
116128   char *aDoclist;                 /* List of docids for full-text queries */
116129   int nDoclist;                   /* Size of buffer at aDoclist */
116130   u8 bDesc;                       /* True to sort in descending order */
116131   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
116132   int nRowAvg;                    /* Average size of database rows, in pages */
116133   sqlcipher3_int64 nDoc;             /* Documents in table */
116134
116135   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
116136   u32 *aMatchinfo;                /* Information about most recent match */
116137   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
116138   char *zMatchinfo;               /* Matchinfo specification */
116139 };
116140
116141 #define FTS3_EVAL_FILTER    0
116142 #define FTS3_EVAL_NEXT      1
116143 #define FTS3_EVAL_MATCHINFO 2
116144
116145 /*
116146 ** The Fts3Cursor.eSearch member is always set to one of the following.
116147 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
116148 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
116149 ** of the column to be searched.  For example, in
116150 **
116151 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
116152 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
116153 ** 
116154 ** Because the LHS of the MATCH operator is 2nd column "b",
116155 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
116156 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
116157 ** indicating that all columns should be searched,
116158 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
116159 */
116160 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
116161 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
116162 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
116163
116164
116165 struct Fts3Doclist {
116166   char *aAll;                    /* Array containing doclist (or NULL) */
116167   int nAll;                      /* Size of a[] in bytes */
116168   char *pNextDocid;              /* Pointer to next docid */
116169
116170   sqlcipher3_int64 iDocid;          /* Current docid (if pList!=0) */
116171   int bFreeList;                 /* True if pList should be sqlcipher3_free()d */
116172   char *pList;                   /* Pointer to position list following iDocid */
116173   int nList;                     /* Length of position list */
116174 };
116175
116176 /*
116177 ** A "phrase" is a sequence of one or more tokens that must match in
116178 ** sequence.  A single token is the base case and the most common case.
116179 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
116180 ** nToken will be the number of tokens in the string.
116181 */
116182 struct Fts3PhraseToken {
116183   char *z;                        /* Text of the token */
116184   int n;                          /* Number of bytes in buffer z */
116185   int isPrefix;                   /* True if token ends with a "*" character */
116186   int bFirst;                     /* True if token must appear at position 0 */
116187
116188   /* Variables above this point are populated when the expression is
116189   ** parsed (by code in fts3_expr.c). Below this point the variables are
116190   ** used when evaluating the expression. */
116191   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
116192   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
116193 };
116194
116195 struct Fts3Phrase {
116196   /* Cache of doclist for this phrase. */
116197   Fts3Doclist doclist;
116198   int bIncr;                 /* True if doclist is loaded incrementally */
116199   int iDoclistToken;
116200
116201   /* Variables below this point are populated by fts3_expr.c when parsing 
116202   ** a MATCH expression. Everything above is part of the evaluation phase. 
116203   */
116204   int nToken;                /* Number of tokens in the phrase */
116205   int iColumn;               /* Index of column this phrase must match */
116206   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
116207 };
116208
116209 /*
116210 ** A tree of these objects forms the RHS of a MATCH operator.
116211 **
116212 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
116213 ** points to a malloced buffer, size nDoclist bytes, containing the results 
116214 ** of this phrase query in FTS3 doclist format. As usual, the initial 
116215 ** "Length" field found in doclists stored on disk is omitted from this 
116216 ** buffer.
116217 **
116218 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
116219 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
116220 ** where nCol is the number of columns in the queried FTS table. The array
116221 ** is populated as follows:
116222 **
116223 **   aMI[iCol*3 + 0] = Undefined
116224 **   aMI[iCol*3 + 1] = Number of occurrences
116225 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
116226 **
116227 ** The aMI array is allocated using sqlcipher3_malloc(). It should be freed 
116228 ** when the expression node is.
116229 */
116230 struct Fts3Expr {
116231   int eType;                 /* One of the FTSQUERY_XXX values defined below */
116232   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
116233   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
116234   Fts3Expr *pLeft;           /* Left operand */
116235   Fts3Expr *pRight;          /* Right operand */
116236   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
116237
116238   /* The following are used by the fts3_eval.c module. */
116239   sqlcipher3_int64 iDocid;      /* Current docid */
116240   u8 bEof;                   /* True this expression is at EOF already */
116241   u8 bStart;                 /* True if iDocid is valid */
116242   u8 bDeferred;              /* True if this expression is entirely deferred */
116243
116244   u32 *aMI;
116245 };
116246
116247 /*
116248 ** Candidate values for Fts3Query.eType. Note that the order of the first
116249 ** four values is in order of precedence when parsing expressions. For 
116250 ** example, the following:
116251 **
116252 **   "a OR b AND c NOT d NEAR e"
116253 **
116254 ** is equivalent to:
116255 **
116256 **   "a OR (b AND (c NOT (d NEAR e)))"
116257 */
116258 #define FTSQUERY_NEAR   1
116259 #define FTSQUERY_NOT    2
116260 #define FTSQUERY_AND    3
116261 #define FTSQUERY_OR     4
116262 #define FTSQUERY_PHRASE 5
116263
116264
116265 /* fts3_write.c */
116266 SQLCIPHER_PRIVATE int sqlcipher3Fts3UpdateMethod(sqlcipher3_vtab*,int,sqlcipher3_value**,sqlcipher3_int64*);
116267 SQLCIPHER_PRIVATE int sqlcipher3Fts3PendingTermsFlush(Fts3Table *);
116268 SQLCIPHER_PRIVATE void sqlcipher3Fts3PendingTermsClear(Fts3Table *);
116269 SQLCIPHER_PRIVATE int sqlcipher3Fts3Optimize(Fts3Table *);
116270 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderNew(int, sqlcipher3_int64,
116271   sqlcipher3_int64, sqlcipher3_int64, const char *, int, Fts3SegReader**);
116272 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderPending(
116273   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
116274 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFree(Fts3SegReader *);
116275 SQLCIPHER_PRIVATE int sqlcipher3Fts3AllSegdirs(Fts3Table*, int, int, sqlcipher3_stmt **);
116276 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadLock(Fts3Table *);
116277 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadBlock(Fts3Table*, sqlcipher3_int64, char **, int*, int*);
116278
116279 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDoctotal(Fts3Table *, sqlcipher3_stmt **);
116280 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDocsize(Fts3Table *, sqlcipher3_int64, sqlcipher3_stmt **);
116281
116282 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredTokens(Fts3Cursor *);
116283 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
116284 SQLCIPHER_PRIVATE int sqlcipher3Fts3CacheDeferredDoclists(Fts3Cursor *);
116285 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredDoclists(Fts3Cursor *);
116286 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegmentsClose(Fts3Table *);
116287
116288 /* Special values interpreted by sqlcipher3SegReaderCursor() */
116289 #define FTS3_SEGCURSOR_PENDING        -1
116290 #define FTS3_SEGCURSOR_ALL            -2
116291
116292 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
116293 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
116294 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFinish(Fts3MultiSegReader *);
116295
116296 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderCursor(
116297     Fts3Table *, int, int, const char *, int, int, int, Fts3MultiSegReader *);
116298
116299 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
116300 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
116301 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
116302 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
116303 #define FTS3_SEGMENT_PREFIX        0x00000008
116304 #define FTS3_SEGMENT_SCAN          0x00000010
116305 #define FTS3_SEGMENT_FIRST         0x00000020
116306
116307 /* Type passed as 4th argument to SegmentReaderIterate() */
116308 struct Fts3SegFilter {
116309   const char *zTerm;
116310   int nTerm;
116311   int iCol;
116312   int flags;
116313 };
116314
116315 struct Fts3MultiSegReader {
116316   /* Used internally by sqlcipher3Fts3SegReaderXXX() calls */
116317   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
116318   int nSegment;                   /* Size of apSegment array */
116319   int nAdvance;                   /* How many seg-readers to advance */
116320   Fts3SegFilter *pFilter;         /* Pointer to filter object */
116321   char *aBuffer;                  /* Buffer to merge doclists in */
116322   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
116323
116324   int iColFilter;                 /* If >=0, filter for this column */
116325   int bRestart;
116326
116327   /* Used by fts3.c only. */
116328   int nCost;                      /* Cost of running iterator */
116329   int bLookup;                    /* True if a lookup of a single entry. */
116330
116331   /* Output values. Valid only after Fts3SegReaderStep() returns SQLCIPHER_ROW. */
116332   char *zTerm;                    /* Pointer to term buffer */
116333   int nTerm;                      /* Size of zTerm in bytes */
116334   char *aDoclist;                 /* Pointer to doclist buffer */
116335   int nDoclist;                   /* Size of aDoclist[] in bytes */
116336 };
116337
116338 /* fts3.c */
116339 SQLCIPHER_PRIVATE int sqlcipher3Fts3PutVarint(char *, sqlcipher3_int64);
116340 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint(const char *, sqlcipher_int64 *);
116341 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint32(const char *, int *);
116342 SQLCIPHER_PRIVATE int sqlcipher3Fts3VarintLen(sqlcipher3_uint64);
116343 SQLCIPHER_PRIVATE void sqlcipher3Fts3Dequote(char *);
116344 SQLCIPHER_PRIVATE void sqlcipher3Fts3DoclistPrev(int,char*,int,char**,sqlcipher3_int64*,int*,u8*);
116345 SQLCIPHER_PRIVATE int sqlcipher3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
116346 SQLCIPHER_PRIVATE int sqlcipher3Fts3FirstFilter(sqlcipher3_int64, char *, int, char *);
116347
116348 /* fts3_tokenizer.c */
116349 SQLCIPHER_PRIVATE const char *sqlcipher3Fts3NextToken(const char *, int *);
116350 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitHashTable(sqlcipher3 *, Fts3Hash *, const char *);
116351 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
116352     sqlcipher3_tokenizer **, char **
116353 );
116354 SQLCIPHER_PRIVATE int sqlcipher3Fts3IsIdChar(char);
116355
116356 /* fts3_snippet.c */
116357 SQLCIPHER_PRIVATE void sqlcipher3Fts3Offsets(sqlcipher3_context*, Fts3Cursor*);
116358 SQLCIPHER_PRIVATE void sqlcipher3Fts3Snippet(sqlcipher3_context *, Fts3Cursor *, const char *,
116359   const char *, const char *, int, int
116360 );
116361 SQLCIPHER_PRIVATE void sqlcipher3Fts3Matchinfo(sqlcipher3_context *, Fts3Cursor *, const char *);
116362
116363 /* fts3_expr.c */
116364 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprParse(sqlcipher3_tokenizer *, 
116365   char **, int, int, int, const char *, int, Fts3Expr **
116366 );
116367 SQLCIPHER_PRIVATE void sqlcipher3Fts3ExprFree(Fts3Expr *);
116368 #ifdef SQLCIPHER_TEST
116369 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprInitTestInterface(sqlcipher3 *db);
116370 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitTerm(sqlcipher3 *db);
116371 #endif
116372
116373 /* fts3_aux.c */
116374 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitAux(sqlcipher3 *db);
116375
116376 SQLCIPHER_PRIVATE void sqlcipher3Fts3EvalPhraseCleanup(Fts3Phrase *);
116377
116378 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrStart(
116379     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
116380 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrNext(
116381     Fts3Table *, Fts3MultiSegReader *, sqlcipher3_int64 *, char **, int *);
116382 SQLCIPHER_PRIVATE char *sqlcipher3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol); 
116383 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
116384 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
116385
116386 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
116387
116388 #endif /* !SQLCIPHER_CORE || SQLCIPHER_ENABLE_FTS3 */
116389 #endif /* _FTSINT_H */
116390
116391 /************** End of fts3Int.h *********************************************/
116392 /************** Continuing where we left off in fts3.c ***********************/
116393 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
116394
116395 #if defined(SQLCIPHER_ENABLE_FTS3) && !defined(SQLCIPHER_CORE)
116396 # define SQLCIPHER_CORE 1
116397 #endif
116398
116399 /* #include <assert.h> */
116400 /* #include <stdlib.h> */
116401 /* #include <stddef.h> */
116402 /* #include <stdio.h> */
116403 /* #include <string.h> */
116404 /* #include <stdarg.h> */
116405
116406 #ifndef SQLCIPHER_CORE 
116407   SQLCIPHER_EXTENSION_INIT1
116408 #endif
116409
116410 static int fts3EvalNext(Fts3Cursor *pCsr);
116411 static int fts3EvalStart(Fts3Cursor *pCsr);
116412 static int fts3TermSegReaderCursor(
116413     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
116414
116415 /* 
116416 ** Write a 64-bit variable-length integer to memory starting at p[0].
116417 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
116418 ** The number of bytes written is returned.
116419 */
116420 SQLCIPHER_PRIVATE int sqlcipher3Fts3PutVarint(char *p, sqlcipher_int64 v){
116421   unsigned char *q = (unsigned char *) p;
116422   sqlcipher_uint64 vu = v;
116423   do{
116424     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
116425     vu >>= 7;
116426   }while( vu!=0 );
116427   q[-1] &= 0x7f;  /* turn off high bit in final byte */
116428   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
116429   return (int) (q - (unsigned char *)p);
116430 }
116431
116432 /* 
116433 ** Read a 64-bit variable-length integer from memory starting at p[0].
116434 ** Return the number of bytes read, or 0 on error.
116435 ** The value is stored in *v.
116436 */
116437 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint(const char *p, sqlcipher_int64 *v){
116438   const unsigned char *q = (const unsigned char *) p;
116439   sqlcipher_uint64 x = 0, y = 1;
116440   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
116441     x += y * (*q++ & 0x7f);
116442     y <<= 7;
116443   }
116444   x += y * (*q++);
116445   *v = (sqlcipher_int64) x;
116446   return (int) (q - (unsigned char *)p);
116447 }
116448
116449 /*
116450 ** Similar to sqlcipher3Fts3GetVarint(), except that the output is truncated to a
116451 ** 32-bit integer before it is returned.
116452 */
116453 SQLCIPHER_PRIVATE int sqlcipher3Fts3GetVarint32(const char *p, int *pi){
116454  sqlcipher_int64 i;
116455  int ret = sqlcipher3Fts3GetVarint(p, &i);
116456  *pi = (int) i;
116457  return ret;
116458 }
116459
116460 /*
116461 ** Return the number of bytes required to encode v as a varint
116462 */
116463 SQLCIPHER_PRIVATE int sqlcipher3Fts3VarintLen(sqlcipher3_uint64 v){
116464   int i = 0;
116465   do{
116466     i++;
116467     v >>= 7;
116468   }while( v!=0 );
116469   return i;
116470 }
116471
116472 /*
116473 ** Convert an SQL-style quoted string into a normal string by removing
116474 ** the quote characters.  The conversion is done in-place.  If the
116475 ** input does not begin with a quote character, then this routine
116476 ** is a no-op.
116477 **
116478 ** Examples:
116479 **
116480 **     "abc"   becomes   abc
116481 **     'xyz'   becomes   xyz
116482 **     [pqr]   becomes   pqr
116483 **     `mno`   becomes   mno
116484 **
116485 */
116486 SQLCIPHER_PRIVATE void sqlcipher3Fts3Dequote(char *z){
116487   char quote;                     /* Quote character (if any ) */
116488
116489   quote = z[0];
116490   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
116491     int iIn = 1;                  /* Index of next byte to read from input */
116492     int iOut = 0;                 /* Index of next byte to write to output */
116493
116494     /* If the first byte was a '[', then the close-quote character is a ']' */
116495     if( quote=='[' ) quote = ']';  
116496
116497     while( ALWAYS(z[iIn]) ){
116498       if( z[iIn]==quote ){
116499         if( z[iIn+1]!=quote ) break;
116500         z[iOut++] = quote;
116501         iIn += 2;
116502       }else{
116503         z[iOut++] = z[iIn++];
116504       }
116505     }
116506     z[iOut] = '\0';
116507   }
116508 }
116509
116510 /*
116511 ** Read a single varint from the doclist at *pp and advance *pp to point
116512 ** to the first byte past the end of the varint.  Add the value of the varint
116513 ** to *pVal.
116514 */
116515 static void fts3GetDeltaVarint(char **pp, sqlcipher3_int64 *pVal){
116516   sqlcipher3_int64 iVal;
116517   *pp += sqlcipher3Fts3GetVarint(*pp, &iVal);
116518   *pVal += iVal;
116519 }
116520
116521 /*
116522 ** When this function is called, *pp points to the first byte following a
116523 ** varint that is part of a doclist (or position-list, or any other list
116524 ** of varints). This function moves *pp to point to the start of that varint,
116525 ** and sets *pVal by the varint value.
116526 **
116527 ** Argument pStart points to the first byte of the doclist that the
116528 ** varint is part of.
116529 */
116530 static void fts3GetReverseVarint(
116531   char **pp, 
116532   char *pStart, 
116533   sqlcipher3_int64 *pVal
116534 ){
116535   sqlcipher3_int64 iVal;
116536   char *p;
116537
116538   /* Pointer p now points at the first byte past the varint we are 
116539   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
116540   ** clear on character p[-1]. */
116541   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
116542   p++;
116543   *pp = p;
116544
116545   sqlcipher3Fts3GetVarint(p, &iVal);
116546   *pVal = iVal;
116547 }
116548
116549 /*
116550 ** The xDisconnect() virtual table method.
116551 */
116552 static int fts3DisconnectMethod(sqlcipher3_vtab *pVtab){
116553   Fts3Table *p = (Fts3Table *)pVtab;
116554   int i;
116555
116556   assert( p->nPendingData==0 );
116557   assert( p->pSegments==0 );
116558
116559   /* Free any prepared statements held */
116560   for(i=0; i<SizeofArray(p->aStmt); i++){
116561     sqlcipher3_finalize(p->aStmt[i]);
116562   }
116563   sqlcipher3_free(p->zSegmentsTbl);
116564   sqlcipher3_free(p->zReadExprlist);
116565   sqlcipher3_free(p->zWriteExprlist);
116566   sqlcipher3_free(p->zContentTbl);
116567
116568   /* Invoke the tokenizer destructor to free the tokenizer. */
116569   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
116570
116571   sqlcipher3_free(p);
116572   return SQLCIPHER_OK;
116573 }
116574
116575 /*
116576 ** Construct one or more SQL statements from the format string given
116577 ** and then evaluate those statements. The success code is written
116578 ** into *pRc.
116579 **
116580 ** If *pRc is initially non-zero then this routine is a no-op.
116581 */
116582 static void fts3DbExec(
116583   int *pRc,              /* Success code */
116584   sqlcipher3 *db,           /* Database in which to run SQL */
116585   const char *zFormat,   /* Format string for SQL */
116586   ...                    /* Arguments to the format string */
116587 ){
116588   va_list ap;
116589   char *zSql;
116590   if( *pRc ) return;
116591   va_start(ap, zFormat);
116592   zSql = sqlcipher3_vmprintf(zFormat, ap);
116593   va_end(ap);
116594   if( zSql==0 ){
116595     *pRc = SQLCIPHER_NOMEM;
116596   }else{
116597     *pRc = sqlcipher3_exec(db, zSql, 0, 0, 0);
116598     sqlcipher3_free(zSql);
116599   }
116600 }
116601
116602 /*
116603 ** The xDestroy() virtual table method.
116604 */
116605 static int fts3DestroyMethod(sqlcipher3_vtab *pVtab){
116606   Fts3Table *p = (Fts3Table *)pVtab;
116607   int rc = SQLCIPHER_OK;              /* Return code */
116608   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
116609   sqlcipher3 *db = p->db;             /* Database handle */
116610
116611   /* Drop the shadow tables */
116612   if( p->zContentTbl==0 ){
116613     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
116614   }
116615   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
116616   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
116617   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
116618   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
116619
116620   /* If everything has worked, invoke fts3DisconnectMethod() to free the
116621   ** memory associated with the Fts3Table structure and return SQLCIPHER_OK.
116622   ** Otherwise, return an SQLite error code.
116623   */
116624   return (rc==SQLCIPHER_OK ? fts3DisconnectMethod(pVtab) : rc);
116625 }
116626
116627
116628 /*
116629 ** Invoke sqlcipher3_declare_vtab() to declare the schema for the FTS3 table
116630 ** passed as the first argument. This is done as part of the xConnect()
116631 ** and xCreate() methods.
116632 **
116633 ** If *pRc is non-zero when this function is called, it is a no-op. 
116634 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
116635 ** before returning.
116636 */
116637 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
116638   if( *pRc==SQLCIPHER_OK ){
116639     int i;                        /* Iterator variable */
116640     int rc;                       /* Return code */
116641     char *zSql;                   /* SQL statement passed to declare_vtab() */
116642     char *zCols;                  /* List of user defined columns */
116643
116644     sqlcipher3_vtab_config(p->db, SQLCIPHER_VTAB_CONSTRAINT_SUPPORT, 1);
116645
116646     /* Create a list of user columns for the virtual table */
116647     zCols = sqlcipher3_mprintf("%Q, ", p->azColumn[0]);
116648     for(i=1; zCols && i<p->nColumn; i++){
116649       zCols = sqlcipher3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
116650     }
116651
116652     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
116653     zSql = sqlcipher3_mprintf(
116654         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
116655     );
116656     if( !zCols || !zSql ){
116657       rc = SQLCIPHER_NOMEM;
116658     }else{
116659       rc = sqlcipher3_declare_vtab(p->db, zSql);
116660     }
116661
116662     sqlcipher3_free(zSql);
116663     sqlcipher3_free(zCols);
116664     *pRc = rc;
116665   }
116666 }
116667
116668 /*
116669 ** Create the backing store tables (%_content, %_segments and %_segdir)
116670 ** required by the FTS3 table passed as the only argument. This is done
116671 ** as part of the vtab xCreate() method.
116672 **
116673 ** If the p->bHasDocsize boolean is true (indicating that this is an
116674 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
116675 ** %_stat tables required by FTS4.
116676 */
116677 static int fts3CreateTables(Fts3Table *p){
116678   int rc = SQLCIPHER_OK;             /* Return code */
116679   int i;                          /* Iterator variable */
116680   sqlcipher3 *db = p->db;            /* The database connection */
116681
116682   if( p->zContentTbl==0 ){
116683     char *zContentCols;           /* Columns of %_content table */
116684
116685     /* Create a list of user columns for the content table */
116686     zContentCols = sqlcipher3_mprintf("docid INTEGER PRIMARY KEY");
116687     for(i=0; zContentCols && i<p->nColumn; i++){
116688       char *z = p->azColumn[i];
116689       zContentCols = sqlcipher3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
116690     }
116691     if( zContentCols==0 ) rc = SQLCIPHER_NOMEM;
116692   
116693     /* Create the content table */
116694     fts3DbExec(&rc, db, 
116695        "CREATE TABLE %Q.'%q_content'(%s)",
116696        p->zDb, p->zName, zContentCols
116697     );
116698     sqlcipher3_free(zContentCols);
116699   }
116700
116701   /* Create other tables */
116702   fts3DbExec(&rc, db, 
116703       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
116704       p->zDb, p->zName
116705   );
116706   fts3DbExec(&rc, db, 
116707       "CREATE TABLE %Q.'%q_segdir'("
116708         "level INTEGER,"
116709         "idx INTEGER,"
116710         "start_block INTEGER,"
116711         "leaves_end_block INTEGER,"
116712         "end_block INTEGER,"
116713         "root BLOB,"
116714         "PRIMARY KEY(level, idx)"
116715       ");",
116716       p->zDb, p->zName
116717   );
116718   if( p->bHasDocsize ){
116719     fts3DbExec(&rc, db, 
116720         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
116721         p->zDb, p->zName
116722     );
116723   }
116724   if( p->bHasStat ){
116725     fts3DbExec(&rc, db, 
116726         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
116727         p->zDb, p->zName
116728     );
116729   }
116730   return rc;
116731 }
116732
116733 /*
116734 ** Store the current database page-size in bytes in p->nPgsz.
116735 **
116736 ** If *pRc is non-zero when this function is called, it is a no-op. 
116737 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
116738 ** before returning.
116739 */
116740 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
116741   if( *pRc==SQLCIPHER_OK ){
116742     int rc;                       /* Return code */
116743     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
116744     sqlcipher3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
116745   
116746     zSql = sqlcipher3_mprintf("PRAGMA %Q.page_size", p->zDb);
116747     if( !zSql ){
116748       rc = SQLCIPHER_NOMEM;
116749     }else{
116750       rc = sqlcipher3_prepare(p->db, zSql, -1, &pStmt, 0);
116751       if( rc==SQLCIPHER_OK ){
116752         sqlcipher3_step(pStmt);
116753         p->nPgsz = sqlcipher3_column_int(pStmt, 0);
116754         rc = sqlcipher3_finalize(pStmt);
116755       }else if( rc==SQLCIPHER_AUTH ){
116756         p->nPgsz = 1024;
116757         rc = SQLCIPHER_OK;
116758       }
116759     }
116760     assert( p->nPgsz>0 || rc!=SQLCIPHER_OK );
116761     sqlcipher3_free(zSql);
116762     *pRc = rc;
116763   }
116764 }
116765
116766 /*
116767 ** "Special" FTS4 arguments are column specifications of the following form:
116768 **
116769 **   <key> = <value>
116770 **
116771 ** There may not be whitespace surrounding the "=" character. The <value> 
116772 ** term may be quoted, but the <key> may not.
116773 */
116774 static int fts3IsSpecialColumn(
116775   const char *z, 
116776   int *pnKey,
116777   char **pzValue
116778 ){
116779   char *zValue;
116780   const char *zCsr = z;
116781
116782   while( *zCsr!='=' ){
116783     if( *zCsr=='\0' ) return 0;
116784     zCsr++;
116785   }
116786
116787   *pnKey = (int)(zCsr-z);
116788   zValue = sqlcipher3_mprintf("%s", &zCsr[1]);
116789   if( zValue ){
116790     sqlcipher3Fts3Dequote(zValue);
116791   }
116792   *pzValue = zValue;
116793   return 1;
116794 }
116795
116796 /*
116797 ** Append the output of a printf() style formatting to an existing string.
116798 */
116799 static void fts3Appendf(
116800   int *pRc,                       /* IN/OUT: Error code */
116801   char **pz,                      /* IN/OUT: Pointer to string buffer */
116802   const char *zFormat,            /* Printf format string to append */
116803   ...                             /* Arguments for printf format string */
116804 ){
116805   if( *pRc==SQLCIPHER_OK ){
116806     va_list ap;
116807     char *z;
116808     va_start(ap, zFormat);
116809     z = sqlcipher3_vmprintf(zFormat, ap);
116810     if( z && *pz ){
116811       char *z2 = sqlcipher3_mprintf("%s%s", *pz, z);
116812       sqlcipher3_free(z);
116813       z = z2;
116814     }
116815     if( z==0 ) *pRc = SQLCIPHER_NOMEM;
116816     sqlcipher3_free(*pz);
116817     *pz = z;
116818   }
116819 }
116820
116821 /*
116822 ** Return a copy of input string zInput enclosed in double-quotes (") and
116823 ** with all double quote characters escaped. For example:
116824 **
116825 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
116826 **
116827 ** The pointer returned points to memory obtained from sqlcipher3_malloc(). It
116828 ** is the callers responsibility to call sqlcipher3_free() to release this
116829 ** memory.
116830 */
116831 static char *fts3QuoteId(char const *zInput){
116832   int nRet;
116833   char *zRet;
116834   nRet = 2 + strlen(zInput)*2 + 1;
116835   zRet = sqlcipher3_malloc(nRet);
116836   if( zRet ){
116837     int i;
116838     char *z = zRet;
116839     *(z++) = '"';
116840     for(i=0; zInput[i]; i++){
116841       if( zInput[i]=='"' ) *(z++) = '"';
116842       *(z++) = zInput[i];
116843     }
116844     *(z++) = '"';
116845     *(z++) = '\0';
116846   }
116847   return zRet;
116848 }
116849
116850 /*
116851 ** Return a list of comma separated SQL expressions and a FROM clause that 
116852 ** could be used in a SELECT statement such as the following:
116853 **
116854 **     SELECT <list of expressions> FROM %_content AS x ...
116855 **
116856 ** to return the docid, followed by each column of text data in order
116857 ** from left to write. If parameter zFunc is not NULL, then instead of
116858 ** being returned directly each column of text data is passed to an SQL
116859 ** function named zFunc first. For example, if zFunc is "unzip" and the
116860 ** table has the three user-defined columns "a", "b", and "c", the following
116861 ** string is returned:
116862 **
116863 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
116864 **
116865 ** The pointer returned points to a buffer allocated by sqlcipher3_malloc(). It
116866 ** is the responsibility of the caller to eventually free it.
116867 **
116868 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op (and
116869 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
116870 ** by this function, NULL is returned and *pRc is set to SQLCIPHER_NOMEM. If
116871 ** no error occurs, *pRc is left unmodified.
116872 */
116873 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
116874   char *zRet = 0;
116875   char *zFree = 0;
116876   char *zFunction;
116877   int i;
116878
116879   if( p->zContentTbl==0 ){
116880     if( !zFunc ){
116881       zFunction = "";
116882     }else{
116883       zFree = zFunction = fts3QuoteId(zFunc);
116884     }
116885     fts3Appendf(pRc, &zRet, "docid");
116886     for(i=0; i<p->nColumn; i++){
116887       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
116888     }
116889     sqlcipher3_free(zFree);
116890   }else{
116891     fts3Appendf(pRc, &zRet, "rowid");
116892     for(i=0; i<p->nColumn; i++){
116893       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
116894     }
116895   }
116896   fts3Appendf(pRc, &zRet, "FROM '%q'.'%q%s' AS x", 
116897       p->zDb,
116898       (p->zContentTbl ? p->zContentTbl : p->zName),
116899       (p->zContentTbl ? "" : "_content")
116900   );
116901   return zRet;
116902 }
116903
116904 /*
116905 ** Return a list of N comma separated question marks, where N is the number
116906 ** of columns in the %_content table (one for the docid plus one for each
116907 ** user-defined text column).
116908 **
116909 ** If argument zFunc is not NULL, then all but the first question mark
116910 ** is preceded by zFunc and an open bracket, and followed by a closed
116911 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
116912 ** user-defined text columns, the following string is returned:
116913 **
116914 **     "?, zip(?), zip(?), zip(?)"
116915 **
116916 ** The pointer returned points to a buffer allocated by sqlcipher3_malloc(). It
116917 ** is the responsibility of the caller to eventually free it.
116918 **
116919 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op (and
116920 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
116921 ** by this function, NULL is returned and *pRc is set to SQLCIPHER_NOMEM. If
116922 ** no error occurs, *pRc is left unmodified.
116923 */
116924 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
116925   char *zRet = 0;
116926   char *zFree = 0;
116927   char *zFunction;
116928   int i;
116929
116930   if( !zFunc ){
116931     zFunction = "";
116932   }else{
116933     zFree = zFunction = fts3QuoteId(zFunc);
116934   }
116935   fts3Appendf(pRc, &zRet, "?");
116936   for(i=0; i<p->nColumn; i++){
116937     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
116938   }
116939   sqlcipher3_free(zFree);
116940   return zRet;
116941 }
116942
116943 /*
116944 ** This function interprets the string at (*pp) as a non-negative integer
116945 ** value. It reads the integer and sets *pnOut to the value read, then 
116946 ** sets *pp to point to the byte immediately following the last byte of
116947 ** the integer value.
116948 **
116949 ** Only decimal digits ('0'..'9') may be part of an integer value. 
116950 **
116951 ** If *pp does not being with a decimal digit SQLCIPHER_ERROR is returned and
116952 ** the output value undefined. Otherwise SQLCIPHER_OK is returned.
116953 **
116954 ** This function is used when parsing the "prefix=" FTS4 parameter.
116955 */
116956 static int fts3GobbleInt(const char **pp, int *pnOut){
116957   const char *p;                  /* Iterator pointer */
116958   int nInt = 0;                   /* Output value */
116959
116960   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
116961     nInt = nInt * 10 + (p[0] - '0');
116962   }
116963   if( p==*pp ) return SQLCIPHER_ERROR;
116964   *pnOut = nInt;
116965   *pp = p;
116966   return SQLCIPHER_OK;
116967 }
116968
116969 /*
116970 ** This function is called to allocate an array of Fts3Index structures
116971 ** representing the indexes maintained by the current FTS table. FTS tables
116972 ** always maintain the main "terms" index, but may also maintain one or
116973 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
116974 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
116975 **
116976 ** Argument zParam is passed the value of the "prefix=" option if one was
116977 ** specified, or NULL otherwise.
116978 **
116979 ** If no error occurs, SQLCIPHER_OK is returned and *apIndex set to point to
116980 ** the allocated array. *pnIndex is set to the number of elements in the
116981 ** array. If an error does occur, an SQLite error code is returned.
116982 **
116983 ** Regardless of whether or not an error is returned, it is the responsibility
116984 ** of the caller to call sqlcipher3_free() on the output array to free it.
116985 */
116986 static int fts3PrefixParameter(
116987   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
116988   int *pnIndex,                   /* OUT: size of *apIndex[] array */
116989   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
116990 ){
116991   struct Fts3Index *aIndex;       /* Allocated array */
116992   int nIndex = 1;                 /* Number of entries in array */
116993
116994   if( zParam && zParam[0] ){
116995     const char *p;
116996     nIndex++;
116997     for(p=zParam; *p; p++){
116998       if( *p==',' ) nIndex++;
116999     }
117000   }
117001
117002   aIndex = sqlcipher3_malloc(sizeof(struct Fts3Index) * nIndex);
117003   *apIndex = aIndex;
117004   *pnIndex = nIndex;
117005   if( !aIndex ){
117006     return SQLCIPHER_NOMEM;
117007   }
117008
117009   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
117010   if( zParam ){
117011     const char *p = zParam;
117012     int i;
117013     for(i=1; i<nIndex; i++){
117014       int nPrefix;
117015       if( fts3GobbleInt(&p, &nPrefix) ) return SQLCIPHER_ERROR;
117016       aIndex[i].nPrefix = nPrefix;
117017       p++;
117018     }
117019   }
117020
117021   return SQLCIPHER_OK;
117022 }
117023
117024 /*
117025 ** This function is called when initializing an FTS4 table that uses the
117026 ** content=xxx option. It determines the number of and names of the columns
117027 ** of the new FTS4 table.
117028 **
117029 ** The third argument passed to this function is the value passed to the
117030 ** config=xxx option (i.e. "xxx"). This function queries the database for
117031 ** a table of that name. If found, the output variables are populated
117032 ** as follows:
117033 **
117034 **   *pnCol:   Set to the number of columns table xxx has,
117035 **
117036 **   *pnStr:   Set to the total amount of space required to store a copy
117037 **             of each columns name, including the nul-terminator.
117038 **
117039 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
117040 **             the name of the corresponding column in table xxx. The array
117041 **             and its contents are allocated using a single allocation. It
117042 **             is the responsibility of the caller to free this allocation
117043 **             by eventually passing the *pazCol value to sqlcipher3_free().
117044 **
117045 ** If the table cannot be found, an error code is returned and the output
117046 ** variables are undefined. Or, if an OOM is encountered, SQLCIPHER_NOMEM is
117047 ** returned (and the output variables are undefined).
117048 */
117049 static int fts3ContentColumns(
117050   sqlcipher3 *db,                    /* Database handle */
117051   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
117052   const char *zTbl,               /* Name of content table */
117053   const char ***pazCol,           /* OUT: Malloc'd array of column names */
117054   int *pnCol,                     /* OUT: Size of array *pazCol */
117055   int *pnStr                      /* OUT: Bytes of string content */
117056 ){
117057   int rc = SQLCIPHER_OK;             /* Return code */
117058   char *zSql;                     /* "SELECT *" statement on zTbl */  
117059   sqlcipher3_stmt *pStmt = 0;        /* Compiled version of zSql */
117060
117061   zSql = sqlcipher3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
117062   if( !zSql ){
117063     rc = SQLCIPHER_NOMEM;
117064   }else{
117065     rc = sqlcipher3_prepare(db, zSql, -1, &pStmt, 0);
117066   }
117067   sqlcipher3_free(zSql);
117068
117069   if( rc==SQLCIPHER_OK ){
117070     const char **azCol;           /* Output array */
117071     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
117072     int nCol;                     /* Number of table columns */
117073     int i;                        /* Used to iterate through columns */
117074
117075     /* Loop through the returned columns. Set nStr to the number of bytes of
117076     ** space required to store a copy of each column name, including the
117077     ** nul-terminator byte.  */
117078     nCol = sqlcipher3_column_count(pStmt);
117079     for(i=0; i<nCol; i++){
117080       const char *zCol = sqlcipher3_column_name(pStmt, i);
117081       nStr += strlen(zCol) + 1;
117082     }
117083
117084     /* Allocate and populate the array to return. */
117085     azCol = (const char **)sqlcipher3_malloc(sizeof(char *) * nCol + nStr);
117086     if( azCol==0 ){
117087       rc = SQLCIPHER_NOMEM;
117088     }else{
117089       char *p = (char *)&azCol[nCol];
117090       for(i=0; i<nCol; i++){
117091         const char *zCol = sqlcipher3_column_name(pStmt, i);
117092         int n = strlen(zCol)+1;
117093         memcpy(p, zCol, n);
117094         azCol[i] = p;
117095         p += n;
117096       }
117097     }
117098     sqlcipher3_finalize(pStmt);
117099
117100     /* Set the output variables. */
117101     *pnCol = nCol;
117102     *pnStr = nStr;
117103     *pazCol = azCol;
117104   }
117105
117106   return rc;
117107 }
117108
117109 /*
117110 ** This function is the implementation of both the xConnect and xCreate
117111 ** methods of the FTS3 virtual table.
117112 **
117113 ** The argv[] array contains the following:
117114 **
117115 **   argv[0]   -> module name  ("fts3" or "fts4")
117116 **   argv[1]   -> database name
117117 **   argv[2]   -> table name
117118 **   argv[...] -> "column name" and other module argument fields.
117119 */
117120 static int fts3InitVtab(
117121   int isCreate,                   /* True for xCreate, false for xConnect */
117122   sqlcipher3 *db,                    /* The SQLite database connection */
117123   void *pAux,                     /* Hash table containing tokenizers */
117124   int argc,                       /* Number of elements in argv array */
117125   const char * const *argv,       /* xCreate/xConnect argument array */
117126   sqlcipher3_vtab **ppVTab,          /* Write the resulting vtab structure here */
117127   char **pzErr                    /* Write any error message here */
117128 ){
117129   Fts3Hash *pHash = (Fts3Hash *)pAux;
117130   Fts3Table *p = 0;               /* Pointer to allocated vtab */
117131   int rc = SQLCIPHER_OK;             /* Return code */
117132   int i;                          /* Iterator variable */
117133   int nByte;                      /* Size of allocation used for *p */
117134   int iCol;                       /* Column index */
117135   int nString = 0;                /* Bytes required to hold all column names */
117136   int nCol = 0;                   /* Number of columns in the FTS table */
117137   char *zCsr;                     /* Space for holding column names */
117138   int nDb;                        /* Bytes required to hold database name */
117139   int nName;                      /* Bytes required to hold table name */
117140   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
117141   const char **aCol;              /* Array of column names */
117142   sqlcipher3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
117143
117144   int nIndex;                     /* Size of aIndex[] array */
117145   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
117146
117147   /* The results of parsing supported FTS4 key=value options: */
117148   int bNoDocsize = 0;             /* True to omit %_docsize table */
117149   int bDescIdx = 0;               /* True to store descending indexes */
117150   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
117151   char *zCompress = 0;            /* compress=? parameter (or NULL) */
117152   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
117153   char *zContent = 0;             /* content=? parameter (or NULL) */
117154
117155   assert( strlen(argv[0])==4 );
117156   assert( (sqlcipher3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
117157        || (sqlcipher3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
117158   );
117159
117160   nDb = (int)strlen(argv[1]) + 1;
117161   nName = (int)strlen(argv[2]) + 1;
117162
117163   aCol = (const char **)sqlcipher3_malloc(sizeof(const char *) * (argc-2) );
117164   if( !aCol ) return SQLCIPHER_NOMEM;
117165   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
117166
117167   /* Loop through all of the arguments passed by the user to the FTS3/4
117168   ** module (i.e. all the column names and special arguments). This loop
117169   ** does the following:
117170   **
117171   **   + Figures out the number of columns the FTSX table will have, and
117172   **     the number of bytes of space that must be allocated to store copies
117173   **     of the column names.
117174   **
117175   **   + If there is a tokenizer specification included in the arguments,
117176   **     initializes the tokenizer pTokenizer.
117177   */
117178   for(i=3; rc==SQLCIPHER_OK && i<argc; i++){
117179     char const *z = argv[i];
117180     int nKey;
117181     char *zVal;
117182
117183     /* Check if this is a tokenizer specification */
117184     if( !pTokenizer 
117185      && strlen(z)>8
117186      && 0==sqlcipher3_strnicmp(z, "tokenize", 8) 
117187      && 0==sqlcipher3Fts3IsIdChar(z[8])
117188     ){
117189       rc = sqlcipher3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
117190     }
117191
117192     /* Check if it is an FTS4 special argument. */
117193     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
117194       struct Fts4Option {
117195         const char *zOpt;
117196         int nOpt;
117197       } aFts4Opt[] = {
117198         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
117199         { "prefix",      6 },     /* 1 -> PREFIX */
117200         { "compress",    8 },     /* 2 -> COMPRESS */
117201         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
117202         { "order",       5 },     /* 4 -> ORDER */
117203         { "content",     7 }      /* 5 -> CONTENT */
117204       };
117205
117206       int iOpt;
117207       if( !zVal ){
117208         rc = SQLCIPHER_NOMEM;
117209       }else{
117210         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
117211           struct Fts4Option *pOp = &aFts4Opt[iOpt];
117212           if( nKey==pOp->nOpt && !sqlcipher3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
117213             break;
117214           }
117215         }
117216         if( iOpt==SizeofArray(aFts4Opt) ){
117217           *pzErr = sqlcipher3_mprintf("unrecognized parameter: %s", z);
117218           rc = SQLCIPHER_ERROR;
117219         }else{
117220           switch( iOpt ){
117221             case 0:               /* MATCHINFO */
117222               if( strlen(zVal)!=4 || sqlcipher3_strnicmp(zVal, "fts3", 4) ){
117223                 *pzErr = sqlcipher3_mprintf("unrecognized matchinfo: %s", zVal);
117224                 rc = SQLCIPHER_ERROR;
117225               }
117226               bNoDocsize = 1;
117227               break;
117228
117229             case 1:               /* PREFIX */
117230               sqlcipher3_free(zPrefix);
117231               zPrefix = zVal;
117232               zVal = 0;
117233               break;
117234
117235             case 2:               /* COMPRESS */
117236               sqlcipher3_free(zCompress);
117237               zCompress = zVal;
117238               zVal = 0;
117239               break;
117240
117241             case 3:               /* UNCOMPRESS */
117242               sqlcipher3_free(zUncompress);
117243               zUncompress = zVal;
117244               zVal = 0;
117245               break;
117246
117247             case 4:               /* ORDER */
117248               if( (strlen(zVal)!=3 || sqlcipher3_strnicmp(zVal, "asc", 3)) 
117249                && (strlen(zVal)!=4 || sqlcipher3_strnicmp(zVal, "desc", 4)) 
117250               ){
117251                 *pzErr = sqlcipher3_mprintf("unrecognized order: %s", zVal);
117252                 rc = SQLCIPHER_ERROR;
117253               }
117254               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
117255               break;
117256
117257             default:              /* CONTENT */
117258               assert( iOpt==5 );
117259               sqlcipher3_free(zUncompress);
117260               zContent = zVal;
117261               zVal = 0;
117262               break;
117263           }
117264         }
117265         sqlcipher3_free(zVal);
117266       }
117267     }
117268
117269     /* Otherwise, the argument is a column name. */
117270     else {
117271       nString += (int)(strlen(z) + 1);
117272       aCol[nCol++] = z;
117273     }
117274   }
117275
117276   /* If a content=xxx option was specified, the following:
117277   **
117278   **   1. Ignore any compress= and uncompress= options.
117279   **
117280   **   2. If no column names were specified as part of the CREATE VIRTUAL
117281   **      TABLE statement, use all columns from the content table.
117282   */
117283   if( rc==SQLCIPHER_OK && zContent ){
117284     sqlcipher3_free(zCompress); 
117285     sqlcipher3_free(zUncompress); 
117286     zCompress = 0;
117287     zUncompress = 0;
117288     if( nCol==0 ){
117289       sqlcipher3_free((void*)aCol); 
117290       aCol = 0;
117291       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
117292     }
117293     assert( rc!=SQLCIPHER_OK || nCol>0 );
117294   }
117295   if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117296
117297   if( nCol==0 ){
117298     assert( nString==0 );
117299     aCol[0] = "content";
117300     nString = 8;
117301     nCol = 1;
117302   }
117303
117304   if( pTokenizer==0 ){
117305     rc = sqlcipher3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
117306     if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117307   }
117308   assert( pTokenizer );
117309
117310   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
117311   if( rc==SQLCIPHER_ERROR ){
117312     assert( zPrefix );
117313     *pzErr = sqlcipher3_mprintf("error parsing prefix parameter: %s", zPrefix);
117314   }
117315   if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117316
117317   /* Allocate and populate the Fts3Table structure. */
117318   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
117319           nCol * sizeof(char *) +              /* azColumn */
117320           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
117321           nName +                              /* zName */
117322           nDb +                                /* zDb */
117323           nString;                             /* Space for azColumn strings */
117324   p = (Fts3Table*)sqlcipher3_malloc(nByte);
117325   if( p==0 ){
117326     rc = SQLCIPHER_NOMEM;
117327     goto fts3_init_out;
117328   }
117329   memset(p, 0, nByte);
117330   p->db = db;
117331   p->nColumn = nCol;
117332   p->nPendingData = 0;
117333   p->azColumn = (char **)&p[1];
117334   p->pTokenizer = pTokenizer;
117335   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
117336   p->bHasDocsize = (isFts4 && bNoDocsize==0);
117337   p->bHasStat = isFts4;
117338   p->bDescIdx = bDescIdx;
117339   p->zContentTbl = zContent;
117340   zContent = 0;
117341   TESTONLY( p->inTransaction = -1 );
117342   TESTONLY( p->mxSavepoint = -1 );
117343
117344   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
117345   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
117346   p->nIndex = nIndex;
117347   for(i=0; i<nIndex; i++){
117348     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
117349   }
117350
117351   /* Fill in the zName and zDb fields of the vtab structure. */
117352   zCsr = (char *)&p->aIndex[nIndex];
117353   p->zName = zCsr;
117354   memcpy(zCsr, argv[2], nName);
117355   zCsr += nName;
117356   p->zDb = zCsr;
117357   memcpy(zCsr, argv[1], nDb);
117358   zCsr += nDb;
117359
117360   /* Fill in the azColumn array */
117361   for(iCol=0; iCol<nCol; iCol++){
117362     char *z; 
117363     int n = 0;
117364     z = (char *)sqlcipher3Fts3NextToken(aCol[iCol], &n);
117365     memcpy(zCsr, z, n);
117366     zCsr[n] = '\0';
117367     sqlcipher3Fts3Dequote(zCsr);
117368     p->azColumn[iCol] = zCsr;
117369     zCsr += n+1;
117370     assert( zCsr <= &((char *)p)[nByte] );
117371   }
117372
117373   if( (zCompress==0)!=(zUncompress==0) ){
117374     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
117375     rc = SQLCIPHER_ERROR;
117376     *pzErr = sqlcipher3_mprintf("missing %s parameter in fts4 constructor", zMiss);
117377   }
117378   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
117379   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
117380   if( rc!=SQLCIPHER_OK ) goto fts3_init_out;
117381
117382   /* If this is an xCreate call, create the underlying tables in the 
117383   ** database. TODO: For xConnect(), it could verify that said tables exist.
117384   */
117385   if( isCreate ){
117386     rc = fts3CreateTables(p);
117387   }
117388
117389   /* Figure out the page-size for the database. This is required in order to
117390   ** estimate the cost of loading large doclists from the database.  */
117391   fts3DatabasePageSize(&rc, p);
117392   p->nNodeSize = p->nPgsz-35;
117393
117394   /* Declare the table schema to SQLite. */
117395   fts3DeclareVtab(&rc, p);
117396
117397 fts3_init_out:
117398   sqlcipher3_free(zPrefix);
117399   sqlcipher3_free(aIndex);
117400   sqlcipher3_free(zCompress);
117401   sqlcipher3_free(zUncompress);
117402   sqlcipher3_free(zContent);
117403   sqlcipher3_free((void *)aCol);
117404   if( rc!=SQLCIPHER_OK ){
117405     if( p ){
117406       fts3DisconnectMethod((sqlcipher3_vtab *)p);
117407     }else if( pTokenizer ){
117408       pTokenizer->pModule->xDestroy(pTokenizer);
117409     }
117410   }else{
117411     assert( p->pSegments==0 );
117412     *ppVTab = &p->base;
117413   }
117414   return rc;
117415 }
117416
117417 /*
117418 ** The xConnect() and xCreate() methods for the virtual table. All the
117419 ** work is done in function fts3InitVtab().
117420 */
117421 static int fts3ConnectMethod(
117422   sqlcipher3 *db,                    /* Database connection */
117423   void *pAux,                     /* Pointer to tokenizer hash table */
117424   int argc,                       /* Number of elements in argv array */
117425   const char * const *argv,       /* xCreate/xConnect argument array */
117426   sqlcipher3_vtab **ppVtab,          /* OUT: New sqlcipher3_vtab object */
117427   char **pzErr                    /* OUT: sqlcipher3_malloc'd error message */
117428 ){
117429   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
117430 }
117431 static int fts3CreateMethod(
117432   sqlcipher3 *db,                    /* Database connection */
117433   void *pAux,                     /* Pointer to tokenizer hash table */
117434   int argc,                       /* Number of elements in argv array */
117435   const char * const *argv,       /* xCreate/xConnect argument array */
117436   sqlcipher3_vtab **ppVtab,          /* OUT: New sqlcipher3_vtab object */
117437   char **pzErr                    /* OUT: sqlcipher3_malloc'd error message */
117438 ){
117439   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
117440 }
117441
117442 /* 
117443 ** Implementation of the xBestIndex method for FTS3 tables. There
117444 ** are three possible strategies, in order of preference:
117445 **
117446 **   1. Direct lookup by rowid or docid. 
117447 **   2. Full-text search using a MATCH operator on a non-docid column.
117448 **   3. Linear scan of %_content table.
117449 */
117450 static int fts3BestIndexMethod(sqlcipher3_vtab *pVTab, sqlcipher3_index_info *pInfo){
117451   Fts3Table *p = (Fts3Table *)pVTab;
117452   int i;                          /* Iterator variable */
117453   int iCons = -1;                 /* Index of constraint to use */
117454
117455   /* By default use a full table scan. This is an expensive option,
117456   ** so search through the constraints to see if a more efficient 
117457   ** strategy is possible.
117458   */
117459   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
117460   pInfo->estimatedCost = 500000;
117461   for(i=0; i<pInfo->nConstraint; i++){
117462     struct sqlcipher3_index_constraint *pCons = &pInfo->aConstraint[i];
117463     if( pCons->usable==0 ) continue;
117464
117465     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
117466     if( pCons->op==SQLCIPHER_INDEX_CONSTRAINT_EQ 
117467      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
117468     ){
117469       pInfo->idxNum = FTS3_DOCID_SEARCH;
117470       pInfo->estimatedCost = 1.0;
117471       iCons = i;
117472     }
117473
117474     /* A MATCH constraint. Use a full-text search.
117475     **
117476     ** If there is more than one MATCH constraint available, use the first
117477     ** one encountered. If there is both a MATCH constraint and a direct
117478     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
117479     ** though the rowid/docid lookup is faster than a MATCH query, selecting
117480     ** it would lead to an "unable to use function MATCH in the requested 
117481     ** context" error.
117482     */
117483     if( pCons->op==SQLCIPHER_INDEX_CONSTRAINT_MATCH 
117484      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
117485     ){
117486       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
117487       pInfo->estimatedCost = 2.0;
117488       iCons = i;
117489       break;
117490     }
117491   }
117492
117493   if( iCons>=0 ){
117494     pInfo->aConstraintUsage[iCons].argvIndex = 1;
117495     pInfo->aConstraintUsage[iCons].omit = 1;
117496   } 
117497
117498   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
117499   ** docid) order. Both ascending and descending are possible. 
117500   */
117501   if( pInfo->nOrderBy==1 ){
117502     struct sqlcipher3_index_orderby *pOrder = &pInfo->aOrderBy[0];
117503     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
117504       if( pOrder->desc ){
117505         pInfo->idxStr = "DESC";
117506       }else{
117507         pInfo->idxStr = "ASC";
117508       }
117509       pInfo->orderByConsumed = 1;
117510     }
117511   }
117512
117513   assert( p->pSegments==0 );
117514   return SQLCIPHER_OK;
117515 }
117516
117517 /*
117518 ** Implementation of xOpen method.
117519 */
117520 static int fts3OpenMethod(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCsr){
117521   sqlcipher3_vtab_cursor *pCsr;               /* Allocated cursor */
117522
117523   UNUSED_PARAMETER(pVTab);
117524
117525   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
117526   ** allocation succeeds, zero it and return SQLCIPHER_OK. Otherwise, 
117527   ** if the allocation fails, return SQLCIPHER_NOMEM.
117528   */
117529   *ppCsr = pCsr = (sqlcipher3_vtab_cursor *)sqlcipher3_malloc(sizeof(Fts3Cursor));
117530   if( !pCsr ){
117531     return SQLCIPHER_NOMEM;
117532   }
117533   memset(pCsr, 0, sizeof(Fts3Cursor));
117534   return SQLCIPHER_OK;
117535 }
117536
117537 /*
117538 ** Close the cursor.  For additional information see the documentation
117539 ** on the xClose method of the virtual table interface.
117540 */
117541 static int fts3CloseMethod(sqlcipher3_vtab_cursor *pCursor){
117542   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
117543   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117544   sqlcipher3_finalize(pCsr->pStmt);
117545   sqlcipher3Fts3ExprFree(pCsr->pExpr);
117546   sqlcipher3Fts3FreeDeferredTokens(pCsr);
117547   sqlcipher3_free(pCsr->aDoclist);
117548   sqlcipher3_free(pCsr->aMatchinfo);
117549   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117550   sqlcipher3_free(pCsr);
117551   return SQLCIPHER_OK;
117552 }
117553
117554 /*
117555 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
117556 ** compose and prepare an SQL statement of the form:
117557 **
117558 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
117559 **
117560 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
117561 ** it. If an error occurs, return an SQLite error code.
117562 **
117563 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLCIPHER_OK.
117564 */
117565 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlcipher3_stmt **ppStmt){
117566   int rc = SQLCIPHER_OK;
117567   if( pCsr->pStmt==0 ){
117568     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
117569     char *zSql;
117570     zSql = sqlcipher3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
117571     if( !zSql ) return SQLCIPHER_NOMEM;
117572     rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
117573     sqlcipher3_free(zSql);
117574   }
117575   *ppStmt = pCsr->pStmt;
117576   return rc;
117577 }
117578
117579 /*
117580 ** Position the pCsr->pStmt statement so that it is on the row
117581 ** of the %_content table that contains the last match.  Return
117582 ** SQLCIPHER_OK on success.  
117583 */
117584 static int fts3CursorSeek(sqlcipher3_context *pContext, Fts3Cursor *pCsr){
117585   int rc = SQLCIPHER_OK;
117586   if( pCsr->isRequireSeek ){
117587     sqlcipher3_stmt *pStmt = 0;
117588
117589     rc = fts3CursorSeekStmt(pCsr, &pStmt);
117590     if( rc==SQLCIPHER_OK ){
117591       sqlcipher3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
117592       pCsr->isRequireSeek = 0;
117593       if( SQLCIPHER_ROW==sqlcipher3_step(pCsr->pStmt) ){
117594         return SQLCIPHER_OK;
117595       }else{
117596         rc = sqlcipher3_reset(pCsr->pStmt);
117597         if( rc==SQLCIPHER_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
117598           /* If no row was found and no error has occured, then the %_content
117599           ** table is missing a row that is present in the full-text index.
117600           ** The data structures are corrupt.  */
117601           rc = FTS_CORRUPT_VTAB;
117602           pCsr->isEof = 1;
117603         }
117604       }
117605     }
117606   }
117607
117608   if( rc!=SQLCIPHER_OK && pContext ){
117609     sqlcipher3_result_error_code(pContext, rc);
117610   }
117611   return rc;
117612 }
117613
117614 /*
117615 ** This function is used to process a single interior node when searching
117616 ** a b-tree for a term or term prefix. The node data is passed to this 
117617 ** function via the zNode/nNode parameters. The term to search for is
117618 ** passed in zTerm/nTerm.
117619 **
117620 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
117621 ** of the child node that heads the sub-tree that may contain the term.
117622 **
117623 ** If piLast is not NULL, then *piLast is set to the right-most child node
117624 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
117625 ** a prefix.
117626 **
117627 ** If an OOM error occurs, SQLCIPHER_NOMEM is returned. Otherwise, SQLCIPHER_OK.
117628 */
117629 static int fts3ScanInteriorNode(
117630   const char *zTerm,              /* Term to select leaves for */
117631   int nTerm,                      /* Size of term zTerm in bytes */
117632   const char *zNode,              /* Buffer containing segment interior node */
117633   int nNode,                      /* Size of buffer at zNode */
117634   sqlcipher3_int64 *piFirst,         /* OUT: Selected child node */
117635   sqlcipher3_int64 *piLast           /* OUT: Selected child node */
117636 ){
117637   int rc = SQLCIPHER_OK;             /* Return code */
117638   const char *zCsr = zNode;       /* Cursor to iterate through node */
117639   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
117640   char *zBuffer = 0;              /* Buffer to load terms into */
117641   int nAlloc = 0;                 /* Size of allocated buffer */
117642   int isFirstTerm = 1;            /* True when processing first term on page */
117643   sqlcipher3_int64 iChild;           /* Block id of child node to descend to */
117644
117645   /* Skip over the 'height' varint that occurs at the start of every 
117646   ** interior node. Then load the blockid of the left-child of the b-tree
117647   ** node into variable iChild.  
117648   **
117649   ** Even if the data structure on disk is corrupted, this (reading two
117650   ** varints from the buffer) does not risk an overread. If zNode is a
117651   ** root node, then the buffer comes from a SELECT statement. SQLite does
117652   ** not make this guarantee explicitly, but in practice there are always
117653   ** either more than 20 bytes of allocated space following the nNode bytes of
117654   ** contents, or two zero bytes. Or, if the node is read from the %_segments
117655   ** table, then there are always 20 bytes of zeroed padding following the
117656   ** nNode bytes of content (see sqlcipher3Fts3ReadBlock() for details).
117657   */
117658   zCsr += sqlcipher3Fts3GetVarint(zCsr, &iChild);
117659   zCsr += sqlcipher3Fts3GetVarint(zCsr, &iChild);
117660   if( zCsr>zEnd ){
117661     return FTS_CORRUPT_VTAB;
117662   }
117663   
117664   while( zCsr<zEnd && (piFirst || piLast) ){
117665     int cmp;                      /* memcmp() result */
117666     int nSuffix;                  /* Size of term suffix */
117667     int nPrefix = 0;              /* Size of term prefix */
117668     int nBuffer;                  /* Total term size */
117669   
117670     /* Load the next term on the node into zBuffer. Use realloc() to expand
117671     ** the size of zBuffer if required.  */
117672     if( !isFirstTerm ){
117673       zCsr += sqlcipher3Fts3GetVarint32(zCsr, &nPrefix);
117674     }
117675     isFirstTerm = 0;
117676     zCsr += sqlcipher3Fts3GetVarint32(zCsr, &nSuffix);
117677     
117678     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
117679       rc = FTS_CORRUPT_VTAB;
117680       goto finish_scan;
117681     }
117682     if( nPrefix+nSuffix>nAlloc ){
117683       char *zNew;
117684       nAlloc = (nPrefix+nSuffix) * 2;
117685       zNew = (char *)sqlcipher3_realloc(zBuffer, nAlloc);
117686       if( !zNew ){
117687         rc = SQLCIPHER_NOMEM;
117688         goto finish_scan;
117689       }
117690       zBuffer = zNew;
117691     }
117692     assert( zBuffer );
117693     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
117694     nBuffer = nPrefix + nSuffix;
117695     zCsr += nSuffix;
117696
117697     /* Compare the term we are searching for with the term just loaded from
117698     ** the interior node. If the specified term is greater than or equal
117699     ** to the term from the interior node, then all terms on the sub-tree 
117700     ** headed by node iChild are smaller than zTerm. No need to search 
117701     ** iChild.
117702     **
117703     ** If the interior node term is larger than the specified term, then
117704     ** the tree headed by iChild may contain the specified term.
117705     */
117706     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
117707     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
117708       *piFirst = iChild;
117709       piFirst = 0;
117710     }
117711
117712     if( piLast && cmp<0 ){
117713       *piLast = iChild;
117714       piLast = 0;
117715     }
117716
117717     iChild++;
117718   };
117719
117720   if( piFirst ) *piFirst = iChild;
117721   if( piLast ) *piLast = iChild;
117722
117723  finish_scan:
117724   sqlcipher3_free(zBuffer);
117725   return rc;
117726 }
117727
117728
117729 /*
117730 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
117731 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
117732 ** contains a term. This function searches the sub-tree headed by the zNode
117733 ** node for the range of leaf nodes that may contain the specified term
117734 ** or terms for which the specified term is a prefix.
117735 **
117736 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
117737 ** left-most leaf node in the tree that may contain the specified term.
117738 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
117739 ** right-most leaf node that may contain a term for which the specified
117740 ** term is a prefix.
117741 **
117742 ** It is possible that the range of returned leaf nodes does not contain 
117743 ** the specified term or any terms for which it is a prefix. However, if the 
117744 ** segment does contain any such terms, they are stored within the identified
117745 ** range. Because this function only inspects interior segment nodes (and
117746 ** never loads leaf nodes into memory), it is not possible to be sure.
117747 **
117748 ** If an error occurs, an error code other than SQLCIPHER_OK is returned.
117749 */ 
117750 static int fts3SelectLeaf(
117751   Fts3Table *p,                   /* Virtual table handle */
117752   const char *zTerm,              /* Term to select leaves for */
117753   int nTerm,                      /* Size of term zTerm in bytes */
117754   const char *zNode,              /* Buffer containing segment interior node */
117755   int nNode,                      /* Size of buffer at zNode */
117756   sqlcipher3_int64 *piLeaf,          /* Selected leaf node */
117757   sqlcipher3_int64 *piLeaf2          /* Selected leaf node */
117758 ){
117759   int rc;                         /* Return code */
117760   int iHeight;                    /* Height of this node in tree */
117761
117762   assert( piLeaf || piLeaf2 );
117763
117764   sqlcipher3Fts3GetVarint32(zNode, &iHeight);
117765   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
117766   assert( !piLeaf2 || !piLeaf || rc!=SQLCIPHER_OK || (*piLeaf<=*piLeaf2) );
117767
117768   if( rc==SQLCIPHER_OK && iHeight>1 ){
117769     char *zBlob = 0;              /* Blob read from %_segments table */
117770     int nBlob;                    /* Size of zBlob in bytes */
117771
117772     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
117773       rc = sqlcipher3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
117774       if( rc==SQLCIPHER_OK ){
117775         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
117776       }
117777       sqlcipher3_free(zBlob);
117778       piLeaf = 0;
117779       zBlob = 0;
117780     }
117781
117782     if( rc==SQLCIPHER_OK ){
117783       rc = sqlcipher3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
117784     }
117785     if( rc==SQLCIPHER_OK ){
117786       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
117787     }
117788     sqlcipher3_free(zBlob);
117789   }
117790
117791   return rc;
117792 }
117793
117794 /*
117795 ** This function is used to create delta-encoded serialized lists of FTS3 
117796 ** varints. Each call to this function appends a single varint to a list.
117797 */
117798 static void fts3PutDeltaVarint(
117799   char **pp,                      /* IN/OUT: Output pointer */
117800   sqlcipher3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
117801   sqlcipher3_int64 iVal              /* Write this value to the list */
117802 ){
117803   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
117804   *pp += sqlcipher3Fts3PutVarint(*pp, iVal-*piPrev);
117805   *piPrev = iVal;
117806 }
117807
117808 /*
117809 ** When this function is called, *ppPoslist is assumed to point to the 
117810 ** start of a position-list. After it returns, *ppPoslist points to the
117811 ** first byte after the position-list.
117812 **
117813 ** A position list is list of positions (delta encoded) and columns for 
117814 ** a single document record of a doclist.  So, in other words, this
117815 ** routine advances *ppPoslist so that it points to the next docid in
117816 ** the doclist, or to the first byte past the end of the doclist.
117817 **
117818 ** If pp is not NULL, then the contents of the position list are copied
117819 ** to *pp. *pp is set to point to the first byte past the last byte copied
117820 ** before this function returns.
117821 */
117822 static void fts3PoslistCopy(char **pp, char **ppPoslist){
117823   char *pEnd = *ppPoslist;
117824   char c = 0;
117825
117826   /* The end of a position list is marked by a zero encoded as an FTS3 
117827   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
117828   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
117829   ** of some other, multi-byte, value.
117830   **
117831   ** The following while-loop moves pEnd to point to the first byte that is not 
117832   ** immediately preceded by a byte with the 0x80 bit set. Then increments
117833   ** pEnd once more so that it points to the byte immediately following the
117834   ** last byte in the position-list.
117835   */
117836   while( *pEnd | c ){
117837     c = *pEnd++ & 0x80;
117838     testcase( c!=0 && (*pEnd)==0 );
117839   }
117840   pEnd++;  /* Advance past the POS_END terminator byte */
117841
117842   if( pp ){
117843     int n = (int)(pEnd - *ppPoslist);
117844     char *p = *pp;
117845     memcpy(p, *ppPoslist, n);
117846     p += n;
117847     *pp = p;
117848   }
117849   *ppPoslist = pEnd;
117850 }
117851
117852 /*
117853 ** When this function is called, *ppPoslist is assumed to point to the 
117854 ** start of a column-list. After it returns, *ppPoslist points to the
117855 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
117856 **
117857 ** A column-list is list of delta-encoded positions for a single column
117858 ** within a single document within a doclist.
117859 **
117860 ** The column-list is terminated either by a POS_COLUMN varint (1) or
117861 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
117862 ** the POS_COLUMN or POS_END that terminates the column-list.
117863 **
117864 ** If pp is not NULL, then the contents of the column-list are copied
117865 ** to *pp. *pp is set to point to the first byte past the last byte copied
117866 ** before this function returns.  The POS_COLUMN or POS_END terminator
117867 ** is not copied into *pp.
117868 */
117869 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
117870   char *pEnd = *ppPoslist;
117871   char c = 0;
117872
117873   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
117874   ** not part of a multi-byte varint.
117875   */
117876   while( 0xFE & (*pEnd | c) ){
117877     c = *pEnd++ & 0x80;
117878     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
117879   }
117880   if( pp ){
117881     int n = (int)(pEnd - *ppPoslist);
117882     char *p = *pp;
117883     memcpy(p, *ppPoslist, n);
117884     p += n;
117885     *pp = p;
117886   }
117887   *ppPoslist = pEnd;
117888 }
117889
117890 /*
117891 ** Value used to signify the end of an position-list. This is safe because
117892 ** it is not possible to have a document with 2^31 terms.
117893 */
117894 #define POSITION_LIST_END 0x7fffffff
117895
117896 /*
117897 ** This function is used to help parse position-lists. When this function is
117898 ** called, *pp may point to the start of the next varint in the position-list
117899 ** being parsed, or it may point to 1 byte past the end of the position-list
117900 ** (in which case **pp will be a terminator bytes POS_END (0) or
117901 ** (1)).
117902 **
117903 ** If *pp points past the end of the current position-list, set *pi to 
117904 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
117905 ** increment the current value of *pi by the value read, and set *pp to
117906 ** point to the next value before returning.
117907 **
117908 ** Before calling this routine *pi must be initialized to the value of
117909 ** the previous position, or zero if we are reading the first position
117910 ** in the position-list.  Because positions are delta-encoded, the value
117911 ** of the previous position is needed in order to compute the value of
117912 ** the next position.
117913 */
117914 static void fts3ReadNextPos(
117915   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
117916   sqlcipher3_int64 *pi             /* IN/OUT: Value read from position-list */
117917 ){
117918   if( (**pp)&0xFE ){
117919     fts3GetDeltaVarint(pp, pi);
117920     *pi -= 2;
117921   }else{
117922     *pi = POSITION_LIST_END;
117923   }
117924 }
117925
117926 /*
117927 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
117928 ** the value of iCol encoded as a varint to *pp.   This will start a new
117929 ** column list.
117930 **
117931 ** Set *pp to point to the byte just after the last byte written before 
117932 ** returning (do not modify it if iCol==0). Return the total number of bytes
117933 ** written (0 if iCol==0).
117934 */
117935 static int fts3PutColNumber(char **pp, int iCol){
117936   int n = 0;                      /* Number of bytes written */
117937   if( iCol ){
117938     char *p = *pp;                /* Output pointer */
117939     n = 1 + sqlcipher3Fts3PutVarint(&p[1], iCol);
117940     *p = 0x01;
117941     *pp = &p[n];
117942   }
117943   return n;
117944 }
117945
117946 /*
117947 ** Compute the union of two position lists.  The output written
117948 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
117949 ** order and with any duplicates removed.  All pointers are
117950 ** updated appropriately.   The caller is responsible for insuring
117951 ** that there is enough space in *pp to hold the complete output.
117952 */
117953 static void fts3PoslistMerge(
117954   char **pp,                      /* Output buffer */
117955   char **pp1,                     /* Left input list */
117956   char **pp2                      /* Right input list */
117957 ){
117958   char *p = *pp;
117959   char *p1 = *pp1;
117960   char *p2 = *pp2;
117961
117962   while( *p1 || *p2 ){
117963     int iCol1;         /* The current column index in pp1 */
117964     int iCol2;         /* The current column index in pp2 */
117965
117966     if( *p1==POS_COLUMN ) sqlcipher3Fts3GetVarint32(&p1[1], &iCol1);
117967     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
117968     else iCol1 = 0;
117969
117970     if( *p2==POS_COLUMN ) sqlcipher3Fts3GetVarint32(&p2[1], &iCol2);
117971     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
117972     else iCol2 = 0;
117973
117974     if( iCol1==iCol2 ){
117975       sqlcipher3_int64 i1 = 0;       /* Last position from pp1 */
117976       sqlcipher3_int64 i2 = 0;       /* Last position from pp2 */
117977       sqlcipher3_int64 iPrev = 0;
117978       int n = fts3PutColNumber(&p, iCol1);
117979       p1 += n;
117980       p2 += n;
117981
117982       /* At this point, both p1 and p2 point to the start of column-lists
117983       ** for the same column (the column with index iCol1 and iCol2).
117984       ** A column-list is a list of non-negative delta-encoded varints, each 
117985       ** incremented by 2 before being stored. Each list is terminated by a
117986       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
117987       ** and writes the results to buffer p. p is left pointing to the byte
117988       ** after the list written. No terminator (POS_END or POS_COLUMN) is
117989       ** written to the output.
117990       */
117991       fts3GetDeltaVarint(&p1, &i1);
117992       fts3GetDeltaVarint(&p2, &i2);
117993       do {
117994         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
117995         iPrev -= 2;
117996         if( i1==i2 ){
117997           fts3ReadNextPos(&p1, &i1);
117998           fts3ReadNextPos(&p2, &i2);
117999         }else if( i1<i2 ){
118000           fts3ReadNextPos(&p1, &i1);
118001         }else{
118002           fts3ReadNextPos(&p2, &i2);
118003         }
118004       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
118005     }else if( iCol1<iCol2 ){
118006       p1 += fts3PutColNumber(&p, iCol1);
118007       fts3ColumnlistCopy(&p, &p1);
118008     }else{
118009       p2 += fts3PutColNumber(&p, iCol2);
118010       fts3ColumnlistCopy(&p, &p2);
118011     }
118012   }
118013
118014   *p++ = POS_END;
118015   *pp = p;
118016   *pp1 = p1 + 1;
118017   *pp2 = p2 + 1;
118018 }
118019
118020 /*
118021 ** This function is used to merge two position lists into one. When it is
118022 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
118023 ** the part of a doclist that follows each document id. For example, if a row
118024 ** contains:
118025 **
118026 **     'a b c'|'x y z'|'a b b a'
118027 **
118028 ** Then the position list for this row for token 'b' would consist of:
118029 **
118030 **     0x02 0x01 0x02 0x03 0x03 0x00
118031 **
118032 ** When this function returns, both *pp1 and *pp2 are left pointing to the
118033 ** byte following the 0x00 terminator of their respective position lists.
118034 **
118035 ** If isSaveLeft is 0, an entry is added to the output position list for 
118036 ** each position in *pp2 for which there exists one or more positions in
118037 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
118038 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
118039 ** slots before it.
118040 **
118041 ** e.g. nToken==1 searches for adjacent positions.
118042 */
118043 static int fts3PoslistPhraseMerge(
118044   char **pp,                      /* IN/OUT: Preallocated output buffer */
118045   int nToken,                     /* Maximum difference in token positions */
118046   int isSaveLeft,                 /* Save the left position */
118047   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
118048   char **pp1,                     /* IN/OUT: Left input list */
118049   char **pp2                      /* IN/OUT: Right input list */
118050 ){
118051   char *p = *pp;
118052   char *p1 = *pp1;
118053   char *p2 = *pp2;
118054   int iCol1 = 0;
118055   int iCol2 = 0;
118056
118057   /* Never set both isSaveLeft and isExact for the same invocation. */
118058   assert( isSaveLeft==0 || isExact==0 );
118059
118060   assert( p!=0 && *p1!=0 && *p2!=0 );
118061   if( *p1==POS_COLUMN ){ 
118062     p1++;
118063     p1 += sqlcipher3Fts3GetVarint32(p1, &iCol1);
118064   }
118065   if( *p2==POS_COLUMN ){ 
118066     p2++;
118067     p2 += sqlcipher3Fts3GetVarint32(p2, &iCol2);
118068   }
118069
118070   while( 1 ){
118071     if( iCol1==iCol2 ){
118072       char *pSave = p;
118073       sqlcipher3_int64 iPrev = 0;
118074       sqlcipher3_int64 iPos1 = 0;
118075       sqlcipher3_int64 iPos2 = 0;
118076
118077       if( iCol1 ){
118078         *p++ = POS_COLUMN;
118079         p += sqlcipher3Fts3PutVarint(p, iCol1);
118080       }
118081
118082       assert( *p1!=POS_END && *p1!=POS_COLUMN );
118083       assert( *p2!=POS_END && *p2!=POS_COLUMN );
118084       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118085       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118086
118087       while( 1 ){
118088         if( iPos2==iPos1+nToken 
118089          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
118090         ){
118091           sqlcipher3_int64 iSave;
118092           iSave = isSaveLeft ? iPos1 : iPos2;
118093           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
118094           pSave = 0;
118095           assert( p );
118096         }
118097         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
118098           if( (*p2&0xFE)==0 ) break;
118099           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118100         }else{
118101           if( (*p1&0xFE)==0 ) break;
118102           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118103         }
118104       }
118105
118106       if( pSave ){
118107         assert( pp && p );
118108         p = pSave;
118109       }
118110
118111       fts3ColumnlistCopy(0, &p1);
118112       fts3ColumnlistCopy(0, &p2);
118113       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
118114       if( 0==*p1 || 0==*p2 ) break;
118115
118116       p1++;
118117       p1 += sqlcipher3Fts3GetVarint32(p1, &iCol1);
118118       p2++;
118119       p2 += sqlcipher3Fts3GetVarint32(p2, &iCol2);
118120     }
118121
118122     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
118123     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
118124     ** end of the position list, or the 0x01 that precedes the next 
118125     ** column-number in the position list. 
118126     */
118127     else if( iCol1<iCol2 ){
118128       fts3ColumnlistCopy(0, &p1);
118129       if( 0==*p1 ) break;
118130       p1++;
118131       p1 += sqlcipher3Fts3GetVarint32(p1, &iCol1);
118132     }else{
118133       fts3ColumnlistCopy(0, &p2);
118134       if( 0==*p2 ) break;
118135       p2++;
118136       p2 += sqlcipher3Fts3GetVarint32(p2, &iCol2);
118137     }
118138   }
118139
118140   fts3PoslistCopy(0, &p2);
118141   fts3PoslistCopy(0, &p1);
118142   *pp1 = p1;
118143   *pp2 = p2;
118144   if( *pp==p ){
118145     return 0;
118146   }
118147   *p++ = 0x00;
118148   *pp = p;
118149   return 1;
118150 }
118151
118152 /*
118153 ** Merge two position-lists as required by the NEAR operator. The argument
118154 ** position lists correspond to the left and right phrases of an expression 
118155 ** like:
118156 **
118157 **     "phrase 1" NEAR "phrase number 2"
118158 **
118159 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
118160 ** expression and *pp2 to the right. As usual, the indexes in the position 
118161 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
118162 ** in the example above).
118163 **
118164 ** The output position list - written to *pp - is a copy of *pp2 with those
118165 ** entries that are not sufficiently NEAR entries in *pp1 removed.
118166 */
118167 static int fts3PoslistNearMerge(
118168   char **pp,                      /* Output buffer */
118169   char *aTmp,                     /* Temporary buffer space */
118170   int nRight,                     /* Maximum difference in token positions */
118171   int nLeft,                      /* Maximum difference in token positions */
118172   char **pp1,                     /* IN/OUT: Left input list */
118173   char **pp2                      /* IN/OUT: Right input list */
118174 ){
118175   char *p1 = *pp1;
118176   char *p2 = *pp2;
118177
118178   char *pTmp1 = aTmp;
118179   char *pTmp2;
118180   char *aTmp2;
118181   int res = 1;
118182
118183   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
118184   aTmp2 = pTmp2 = pTmp1;
118185   *pp1 = p1;
118186   *pp2 = p2;
118187   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
118188   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
118189     fts3PoslistMerge(pp, &aTmp, &aTmp2);
118190   }else if( pTmp1!=aTmp ){
118191     fts3PoslistCopy(pp, &aTmp);
118192   }else if( pTmp2!=aTmp2 ){
118193     fts3PoslistCopy(pp, &aTmp2);
118194   }else{
118195     res = 0;
118196   }
118197
118198   return res;
118199 }
118200
118201 /* 
118202 ** An instance of this function is used to merge together the (potentially
118203 ** large number of) doclists for each term that matches a prefix query.
118204 ** See function fts3TermSelectMerge() for details.
118205 */
118206 typedef struct TermSelect TermSelect;
118207 struct TermSelect {
118208   char *aaOutput[16];             /* Malloc'd output buffers */
118209   int anOutput[16];               /* Size each output buffer in bytes */
118210 };
118211
118212 /*
118213 ** This function is used to read a single varint from a buffer. Parameter
118214 ** pEnd points 1 byte past the end of the buffer. When this function is
118215 ** called, if *pp points to pEnd or greater, then the end of the buffer
118216 ** has been reached. In this case *pp is set to 0 and the function returns.
118217 **
118218 ** If *pp does not point to or past pEnd, then a single varint is read
118219 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
118220 **
118221 ** If bDescIdx is false, the value read is added to *pVal before returning.
118222 ** If it is true, the value read is subtracted from *pVal before this 
118223 ** function returns.
118224 */
118225 static void fts3GetDeltaVarint3(
118226   char **pp,                      /* IN/OUT: Point to read varint from */
118227   char *pEnd,                     /* End of buffer */
118228   int bDescIdx,                   /* True if docids are descending */
118229   sqlcipher3_int64 *pVal             /* IN/OUT: Integer value */
118230 ){
118231   if( *pp>=pEnd ){
118232     *pp = 0;
118233   }else{
118234     sqlcipher3_int64 iVal;
118235     *pp += sqlcipher3Fts3GetVarint(*pp, &iVal);
118236     if( bDescIdx ){
118237       *pVal -= iVal;
118238     }else{
118239       *pVal += iVal;
118240     }
118241   }
118242 }
118243
118244 /*
118245 ** This function is used to write a single varint to a buffer. The varint
118246 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
118247 ** end of the value written.
118248 **
118249 ** If *pbFirst is zero when this function is called, the value written to
118250 ** the buffer is that of parameter iVal. 
118251 **
118252 ** If *pbFirst is non-zero when this function is called, then the value 
118253 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
118254 ** (if bDescIdx is non-zero).
118255 **
118256 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
118257 ** to the value of parameter iVal.
118258 */
118259 static void fts3PutDeltaVarint3(
118260   char **pp,                      /* IN/OUT: Output pointer */
118261   int bDescIdx,                   /* True for descending docids */
118262   sqlcipher3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118263   int *pbFirst,                   /* IN/OUT: True after first int written */
118264   sqlcipher3_int64 iVal              /* Write this value to the list */
118265 ){
118266   sqlcipher3_int64 iWrite;
118267   if( bDescIdx==0 || *pbFirst==0 ){
118268     iWrite = iVal - *piPrev;
118269   }else{
118270     iWrite = *piPrev - iVal;
118271   }
118272   assert( *pbFirst || *piPrev==0 );
118273   assert( *pbFirst==0 || iWrite>0 );
118274   *pp += sqlcipher3Fts3PutVarint(*pp, iWrite);
118275   *piPrev = iVal;
118276   *pbFirst = 1;
118277 }
118278
118279
118280 /*
118281 ** This macro is used by various functions that merge doclists. The two
118282 ** arguments are 64-bit docid values. If the value of the stack variable
118283 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
118284 ** Otherwise, (i2-i1).
118285 **
118286 ** Using this makes it easier to write code that can merge doclists that are
118287 ** sorted in either ascending or descending order.
118288 */
118289 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
118290
118291 /*
118292 ** This function does an "OR" merge of two doclists (output contains all
118293 ** positions contained in either argument doclist). If the docids in the 
118294 ** input doclists are sorted in ascending order, parameter bDescDoclist
118295 ** should be false. If they are sorted in ascending order, it should be
118296 ** passed a non-zero value.
118297 **
118298 ** If no error occurs, *paOut is set to point at an sqlcipher3_malloc'd buffer
118299 ** containing the output doclist and SQLCIPHER_OK is returned. In this case
118300 ** *pnOut is set to the number of bytes in the output doclist.
118301 **
118302 ** If an error occurs, an SQLite error code is returned. The output values
118303 ** are undefined in this case.
118304 */
118305 static int fts3DoclistOrMerge(
118306   int bDescDoclist,               /* True if arguments are desc */
118307   char *a1, int n1,               /* First doclist */
118308   char *a2, int n2,               /* Second doclist */
118309   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
118310 ){
118311   sqlcipher3_int64 i1 = 0;
118312   sqlcipher3_int64 i2 = 0;
118313   sqlcipher3_int64 iPrev = 0;
118314   char *pEnd1 = &a1[n1];
118315   char *pEnd2 = &a2[n2];
118316   char *p1 = a1;
118317   char *p2 = a2;
118318   char *p;
118319   char *aOut;
118320   int bFirstOut = 0;
118321
118322   *paOut = 0;
118323   *pnOut = 0;
118324
118325   /* Allocate space for the output. Both the input and output doclists
118326   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
118327   ** then the first docid in each list is simply encoded as a varint. For
118328   ** each subsequent docid, the varint stored is the difference between the
118329   ** current and previous docid (a positive number - since the list is in
118330   ** ascending order).
118331   **
118332   ** The first docid written to the output is therefore encoded using the 
118333   ** same number of bytes as it is in whichever of the input lists it is
118334   ** read from. And each subsequent docid read from the same input list 
118335   ** consumes either the same or less bytes as it did in the input (since
118336   ** the difference between it and the previous value in the output must
118337   ** be a positive value less than or equal to the delta value read from 
118338   ** the input list). The same argument applies to all but the first docid
118339   ** read from the 'other' list. And to the contents of all position lists
118340   ** that will be copied and merged from the input to the output.
118341   **
118342   ** However, if the first docid copied to the output is a negative number,
118343   ** then the encoding of the first docid from the 'other' input list may
118344   ** be larger in the output than it was in the input (since the delta value
118345   ** may be a larger positive integer than the actual docid).
118346   **
118347   ** The space required to store the output is therefore the sum of the
118348   ** sizes of the two inputs, plus enough space for exactly one of the input
118349   ** docids to grow. 
118350   **
118351   ** A symetric argument may be made if the doclists are in descending 
118352   ** order.
118353   */
118354   aOut = sqlcipher3_malloc(n1+n2+FTS3_VARINT_MAX-1);
118355   if( !aOut ) return SQLCIPHER_NOMEM;
118356
118357   p = aOut;
118358   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118359   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118360   while( p1 || p2 ){
118361     sqlcipher3_int64 iDiff = DOCID_CMP(i1, i2);
118362
118363     if( p2 && p1 && iDiff==0 ){
118364       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118365       fts3PoslistMerge(&p, &p1, &p2);
118366       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118367       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118368     }else if( !p2 || (p1 && iDiff<0) ){
118369       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118370       fts3PoslistCopy(&p, &p1);
118371       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118372     }else{
118373       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
118374       fts3PoslistCopy(&p, &p2);
118375       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118376     }
118377   }
118378
118379   *paOut = aOut;
118380   *pnOut = (p-aOut);
118381   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
118382   return SQLCIPHER_OK;
118383 }
118384
118385 /*
118386 ** This function does a "phrase" merge of two doclists. In a phrase merge,
118387 ** the output contains a copy of each position from the right-hand input
118388 ** doclist for which there is a position in the left-hand input doclist
118389 ** exactly nDist tokens before it.
118390 **
118391 ** If the docids in the input doclists are sorted in ascending order,
118392 ** parameter bDescDoclist should be false. If they are sorted in ascending 
118393 ** order, it should be passed a non-zero value.
118394 **
118395 ** The right-hand input doclist is overwritten by this function.
118396 */
118397 static void fts3DoclistPhraseMerge(
118398   int bDescDoclist,               /* True if arguments are desc */
118399   int nDist,                      /* Distance from left to right (1=adjacent) */
118400   char *aLeft, int nLeft,         /* Left doclist */
118401   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
118402 ){
118403   sqlcipher3_int64 i1 = 0;
118404   sqlcipher3_int64 i2 = 0;
118405   sqlcipher3_int64 iPrev = 0;
118406   char *pEnd1 = &aLeft[nLeft];
118407   char *pEnd2 = &aRight[*pnRight];
118408   char *p1 = aLeft;
118409   char *p2 = aRight;
118410   char *p;
118411   int bFirstOut = 0;
118412   char *aOut = aRight;
118413
118414   assert( nDist>0 );
118415
118416   p = aOut;
118417   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118418   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118419
118420   while( p1 && p2 ){
118421     sqlcipher3_int64 iDiff = DOCID_CMP(i1, i2);
118422     if( iDiff==0 ){
118423       char *pSave = p;
118424       sqlcipher3_int64 iPrevSave = iPrev;
118425       int bFirstOutSave = bFirstOut;
118426
118427       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118428       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
118429         p = pSave;
118430         iPrev = iPrevSave;
118431         bFirstOut = bFirstOutSave;
118432       }
118433       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118434       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118435     }else if( iDiff<0 ){
118436       fts3PoslistCopy(0, &p1);
118437       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118438     }else{
118439       fts3PoslistCopy(0, &p2);
118440       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118441     }
118442   }
118443
118444   *pnRight = p - aOut;
118445 }
118446
118447 /*
118448 ** Argument pList points to a position list nList bytes in size. This
118449 ** function checks to see if the position list contains any entries for
118450 ** a token in position 0 (of any column). If so, it writes argument iDelta
118451 ** to the output buffer pOut, followed by a position list consisting only
118452 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
118453 ** The value returned is the number of bytes written to pOut (if any).
118454 */
118455 SQLCIPHER_PRIVATE int sqlcipher3Fts3FirstFilter(
118456   sqlcipher3_int64 iDelta,           /* Varint that may be written to pOut */
118457   char *pList,                    /* Position list (no 0x00 term) */
118458   int nList,                      /* Size of pList in bytes */
118459   char *pOut                      /* Write output here */
118460 ){
118461   int nOut = 0;
118462   int bWritten = 0;               /* True once iDelta has been written */
118463   char *p = pList;
118464   char *pEnd = &pList[nList];
118465
118466   if( *p!=0x01 ){
118467     if( *p==0x02 ){
118468       nOut += sqlcipher3Fts3PutVarint(&pOut[nOut], iDelta);
118469       pOut[nOut++] = 0x02;
118470       bWritten = 1;
118471     }
118472     fts3ColumnlistCopy(0, &p);
118473   }
118474
118475   while( p<pEnd && *p==0x01 ){
118476     sqlcipher3_int64 iCol;
118477     p++;
118478     p += sqlcipher3Fts3GetVarint(p, &iCol);
118479     if( *p==0x02 ){
118480       if( bWritten==0 ){
118481         nOut += sqlcipher3Fts3PutVarint(&pOut[nOut], iDelta);
118482         bWritten = 1;
118483       }
118484       pOut[nOut++] = 0x01;
118485       nOut += sqlcipher3Fts3PutVarint(&pOut[nOut], iCol);
118486       pOut[nOut++] = 0x02;
118487     }
118488     fts3ColumnlistCopy(0, &p);
118489   }
118490   if( bWritten ){
118491     pOut[nOut++] = 0x00;
118492   }
118493
118494   return nOut;
118495 }
118496
118497
118498 /*
118499 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
118500 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
118501 ** other doclists (except the aaOutput[0] one) and return SQLCIPHER_OK.
118502 **
118503 ** If an OOM error occurs, return SQLCIPHER_NOMEM. In this case it is
118504 ** the responsibility of the caller to free any doclists left in the
118505 ** TermSelect.aaOutput[] array.
118506 */
118507 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
118508   char *aOut = 0;
118509   int nOut = 0;
118510   int i;
118511
118512   /* Loop through the doclists in the aaOutput[] array. Merge them all
118513   ** into a single doclist.
118514   */
118515   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
118516     if( pTS->aaOutput[i] ){
118517       if( !aOut ){
118518         aOut = pTS->aaOutput[i];
118519         nOut = pTS->anOutput[i];
118520         pTS->aaOutput[i] = 0;
118521       }else{
118522         int nNew;
118523         char *aNew;
118524
118525         int rc = fts3DoclistOrMerge(p->bDescIdx, 
118526             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
118527         );
118528         if( rc!=SQLCIPHER_OK ){
118529           sqlcipher3_free(aOut);
118530           return rc;
118531         }
118532
118533         sqlcipher3_free(pTS->aaOutput[i]);
118534         sqlcipher3_free(aOut);
118535         pTS->aaOutput[i] = 0;
118536         aOut = aNew;
118537         nOut = nNew;
118538       }
118539     }
118540   }
118541
118542   pTS->aaOutput[0] = aOut;
118543   pTS->anOutput[0] = nOut;
118544   return SQLCIPHER_OK;
118545 }
118546
118547 /*
118548 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
118549 ** as the first argument. The merge is an "OR" merge (see function
118550 ** fts3DoclistOrMerge() for details).
118551 **
118552 ** This function is called with the doclist for each term that matches
118553 ** a queried prefix. It merges all these doclists into one, the doclist
118554 ** for the specified prefix. Since there can be a very large number of
118555 ** doclists to merge, the merging is done pair-wise using the TermSelect
118556 ** object.
118557 **
118558 ** This function returns SQLCIPHER_OK if the merge is successful, or an
118559 ** SQLite error code (SQLCIPHER_NOMEM) if an error occurs.
118560 */
118561 static int fts3TermSelectMerge(
118562   Fts3Table *p,                   /* FTS table handle */
118563   TermSelect *pTS,                /* TermSelect object to merge into */
118564   char *aDoclist,                 /* Pointer to doclist */
118565   int nDoclist                    /* Size of aDoclist in bytes */
118566 ){
118567   if( pTS->aaOutput[0]==0 ){
118568     /* If this is the first term selected, copy the doclist to the output
118569     ** buffer using memcpy(). */
118570     pTS->aaOutput[0] = sqlcipher3_malloc(nDoclist);
118571     pTS->anOutput[0] = nDoclist;
118572     if( pTS->aaOutput[0] ){
118573       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
118574     }else{
118575       return SQLCIPHER_NOMEM;
118576     }
118577   }else{
118578     char *aMerge = aDoclist;
118579     int nMerge = nDoclist;
118580     int iOut;
118581
118582     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
118583       if( pTS->aaOutput[iOut]==0 ){
118584         assert( iOut>0 );
118585         pTS->aaOutput[iOut] = aMerge;
118586         pTS->anOutput[iOut] = nMerge;
118587         break;
118588       }else{
118589         char *aNew;
118590         int nNew;
118591
118592         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
118593             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
118594         );
118595         if( rc!=SQLCIPHER_OK ){
118596           if( aMerge!=aDoclist ) sqlcipher3_free(aMerge);
118597           return rc;
118598         }
118599
118600         if( aMerge!=aDoclist ) sqlcipher3_free(aMerge);
118601         sqlcipher3_free(pTS->aaOutput[iOut]);
118602         pTS->aaOutput[iOut] = 0;
118603   
118604         aMerge = aNew;
118605         nMerge = nNew;
118606         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
118607           pTS->aaOutput[iOut] = aMerge;
118608           pTS->anOutput[iOut] = nMerge;
118609         }
118610       }
118611     }
118612   }
118613   return SQLCIPHER_OK;
118614 }
118615
118616 /*
118617 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
118618 */
118619 static int fts3SegReaderCursorAppend(
118620   Fts3MultiSegReader *pCsr, 
118621   Fts3SegReader *pNew
118622 ){
118623   if( (pCsr->nSegment%16)==0 ){
118624     Fts3SegReader **apNew;
118625     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
118626     apNew = (Fts3SegReader **)sqlcipher3_realloc(pCsr->apSegment, nByte);
118627     if( !apNew ){
118628       sqlcipher3Fts3SegReaderFree(pNew);
118629       return SQLCIPHER_NOMEM;
118630     }
118631     pCsr->apSegment = apNew;
118632   }
118633   pCsr->apSegment[pCsr->nSegment++] = pNew;
118634   return SQLCIPHER_OK;
118635 }
118636
118637 /*
118638 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
118639 ** 8th argument.
118640 **
118641 ** This function returns SQLCIPHER_OK if successful, or an SQLite error code
118642 ** otherwise.
118643 */
118644 static int fts3SegReaderCursor(
118645   Fts3Table *p,                   /* FTS3 table handle */
118646   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
118647   int iLevel,                     /* Level of segments to scan */
118648   const char *zTerm,              /* Term to query for */
118649   int nTerm,                      /* Size of zTerm in bytes */
118650   int isPrefix,                   /* True for a prefix search */
118651   int isScan,                     /* True to scan from zTerm to EOF */
118652   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
118653 ){
118654   int rc = SQLCIPHER_OK;             /* Error code */
118655   sqlcipher3_stmt *pStmt = 0;        /* Statement to iterate through segments */
118656   int rc2;                        /* Result of sqlcipher3_reset() */
118657
118658   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
118659   ** for the pending-terms. If this is a scan, then this call must be being
118660   ** made by an fts4aux module, not an FTS table. In this case calling
118661   ** Fts3SegReaderPending might segfault, as the data structures used by 
118662   ** fts4aux are not completely populated. So it's easiest to filter these
118663   ** calls out here.  */
118664   if( iLevel<0 && p->aIndex ){
118665     Fts3SegReader *pSeg = 0;
118666     rc = sqlcipher3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
118667     if( rc==SQLCIPHER_OK && pSeg ){
118668       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
118669     }
118670   }
118671
118672   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
118673     if( rc==SQLCIPHER_OK ){
118674       rc = sqlcipher3Fts3AllSegdirs(p, iIndex, iLevel, &pStmt);
118675     }
118676
118677     while( rc==SQLCIPHER_OK && SQLCIPHER_ROW==(rc = sqlcipher3_step(pStmt)) ){
118678       Fts3SegReader *pSeg = 0;
118679
118680       /* Read the values returned by the SELECT into local variables. */
118681       sqlcipher3_int64 iStartBlock = sqlcipher3_column_int64(pStmt, 1);
118682       sqlcipher3_int64 iLeavesEndBlock = sqlcipher3_column_int64(pStmt, 2);
118683       sqlcipher3_int64 iEndBlock = sqlcipher3_column_int64(pStmt, 3);
118684       int nRoot = sqlcipher3_column_bytes(pStmt, 4);
118685       char const *zRoot = sqlcipher3_column_blob(pStmt, 4);
118686
118687       /* If zTerm is not NULL, and this segment is not stored entirely on its
118688       ** root node, the range of leaves scanned can be reduced. Do this. */
118689       if( iStartBlock && zTerm ){
118690         sqlcipher3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
118691         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
118692         if( rc!=SQLCIPHER_OK ) goto finished;
118693         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
118694       }
118695  
118696       rc = sqlcipher3Fts3SegReaderNew(pCsr->nSegment+1, 
118697           iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg
118698       );
118699       if( rc!=SQLCIPHER_OK ) goto finished;
118700       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
118701     }
118702   }
118703
118704  finished:
118705   rc2 = sqlcipher3_reset(pStmt);
118706   if( rc==SQLCIPHER_DONE ) rc = rc2;
118707
118708   return rc;
118709 }
118710
118711 /*
118712 ** Set up a cursor object for iterating through a full-text index or a 
118713 ** single level therein.
118714 */
118715 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderCursor(
118716   Fts3Table *p,                   /* FTS3 table handle */
118717   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
118718   int iLevel,                     /* Level of segments to scan */
118719   const char *zTerm,              /* Term to query for */
118720   int nTerm,                      /* Size of zTerm in bytes */
118721   int isPrefix,                   /* True for a prefix search */
118722   int isScan,                     /* True to scan from zTerm to EOF */
118723   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
118724 ){
118725   assert( iIndex>=0 && iIndex<p->nIndex );
118726   assert( iLevel==FTS3_SEGCURSOR_ALL
118727       ||  iLevel==FTS3_SEGCURSOR_PENDING 
118728       ||  iLevel>=0
118729   );
118730   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
118731   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
118732   assert( isPrefix==0 || isScan==0 );
118733
118734   /* "isScan" is only set to true by the ft4aux module, an ordinary
118735   ** full-text tables. */
118736   assert( isScan==0 || p->aIndex==0 );
118737
118738   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
118739
118740   return fts3SegReaderCursor(
118741       p, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
118742   );
118743 }
118744
118745 /*
118746 ** In addition to its current configuration, have the Fts3MultiSegReader
118747 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
118748 **
118749 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
118750 */
118751 static int fts3SegReaderCursorAddZero(
118752   Fts3Table *p,                   /* FTS virtual table handle */
118753   const char *zTerm,              /* Term to scan doclist of */
118754   int nTerm,                      /* Number of bytes in zTerm */
118755   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
118756 ){
118757   return fts3SegReaderCursor(p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr);
118758 }
118759
118760 /*
118761 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
118762 ** if isPrefix is true, to scan the doclist for all terms for which 
118763 ** zTerm/nTerm is a prefix. If successful, return SQLCIPHER_OK and write
118764 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
118765 ** an SQLite error code.
118766 **
118767 ** It is the responsibility of the caller to free this object by eventually
118768 ** passing it to fts3SegReaderCursorFree() 
118769 **
118770 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
118771 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
118772 */
118773 static int fts3TermSegReaderCursor(
118774   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
118775   const char *zTerm,              /* Term to query for */
118776   int nTerm,                      /* Size of zTerm in bytes */
118777   int isPrefix,                   /* True for a prefix search */
118778   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
118779 ){
118780   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
118781   int rc = SQLCIPHER_NOMEM;          /* Return code */
118782
118783   pSegcsr = sqlcipher3_malloc(sizeof(Fts3MultiSegReader));
118784   if( pSegcsr ){
118785     int i;
118786     int bFound = 0;               /* True once an index has been found */
118787     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
118788
118789     if( isPrefix ){
118790       for(i=1; bFound==0 && i<p->nIndex; i++){
118791         if( p->aIndex[i].nPrefix==nTerm ){
118792           bFound = 1;
118793           rc = sqlcipher3Fts3SegReaderCursor(
118794               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr);
118795           pSegcsr->bLookup = 1;
118796         }
118797       }
118798
118799       for(i=1; bFound==0 && i<p->nIndex; i++){
118800         if( p->aIndex[i].nPrefix==nTerm+1 ){
118801           bFound = 1;
118802           rc = sqlcipher3Fts3SegReaderCursor(
118803               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
118804           );
118805           if( rc==SQLCIPHER_OK ){
118806             rc = fts3SegReaderCursorAddZero(p, zTerm, nTerm, pSegcsr);
118807           }
118808         }
118809       }
118810     }
118811
118812     if( bFound==0 ){
118813       rc = sqlcipher3Fts3SegReaderCursor(
118814           p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
118815       );
118816       pSegcsr->bLookup = !isPrefix;
118817     }
118818   }
118819
118820   *ppSegcsr = pSegcsr;
118821   return rc;
118822 }
118823
118824 /*
118825 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
118826 */
118827 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
118828   sqlcipher3Fts3SegReaderFinish(pSegcsr);
118829   sqlcipher3_free(pSegcsr);
118830 }
118831
118832 /*
118833 ** This function retreives the doclist for the specified term (or term
118834 ** prefix) from the database.
118835 */
118836 static int fts3TermSelect(
118837   Fts3Table *p,                   /* Virtual table handle */
118838   Fts3PhraseToken *pTok,          /* Token to query for */
118839   int iColumn,                    /* Column to query (or -ve for all columns) */
118840   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
118841   char **ppOut                    /* OUT: Malloced result buffer */
118842 ){
118843   int rc;                         /* Return code */
118844   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
118845   TermSelect tsc;                 /* Object for pair-wise doclist merging */
118846   Fts3SegFilter filter;           /* Segment term filter configuration */
118847
118848   pSegcsr = pTok->pSegcsr;
118849   memset(&tsc, 0, sizeof(TermSelect));
118850
118851   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
118852         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
118853         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
118854         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
118855   filter.iCol = iColumn;
118856   filter.zTerm = pTok->z;
118857   filter.nTerm = pTok->n;
118858
118859   rc = sqlcipher3Fts3SegReaderStart(p, pSegcsr, &filter);
118860   while( SQLCIPHER_OK==rc
118861       && SQLCIPHER_ROW==(rc = sqlcipher3Fts3SegReaderStep(p, pSegcsr)) 
118862   ){
118863     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
118864   }
118865
118866   if( rc==SQLCIPHER_OK ){
118867     rc = fts3TermSelectFinishMerge(p, &tsc);
118868   }
118869   if( rc==SQLCIPHER_OK ){
118870     *ppOut = tsc.aaOutput[0];
118871     *pnOut = tsc.anOutput[0];
118872   }else{
118873     int i;
118874     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
118875       sqlcipher3_free(tsc.aaOutput[i]);
118876     }
118877   }
118878
118879   fts3SegReaderCursorFree(pSegcsr);
118880   pTok->pSegcsr = 0;
118881   return rc;
118882 }
118883
118884 /*
118885 ** This function counts the total number of docids in the doclist stored
118886 ** in buffer aList[], size nList bytes.
118887 **
118888 ** If the isPoslist argument is true, then it is assumed that the doclist
118889 ** contains a position-list following each docid. Otherwise, it is assumed
118890 ** that the doclist is simply a list of docids stored as delta encoded 
118891 ** varints.
118892 */
118893 static int fts3DoclistCountDocids(char *aList, int nList){
118894   int nDoc = 0;                   /* Return value */
118895   if( aList ){
118896     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
118897     char *p = aList;              /* Cursor */
118898     while( p<aEnd ){
118899       nDoc++;
118900       while( (*p++)&0x80 );     /* Skip docid varint */
118901       fts3PoslistCopy(0, &p);   /* Skip over position list */
118902     }
118903   }
118904
118905   return nDoc;
118906 }
118907
118908 /*
118909 ** Advance the cursor to the next row in the %_content table that
118910 ** matches the search criteria.  For a MATCH search, this will be
118911 ** the next row that matches. For a full-table scan, this will be
118912 ** simply the next row in the %_content table.  For a docid lookup,
118913 ** this routine simply sets the EOF flag.
118914 **
118915 ** Return SQLCIPHER_OK if nothing goes wrong.  SQLCIPHER_OK is returned
118916 ** even if we reach end-of-file.  The fts3EofMethod() will be called
118917 ** subsequently to determine whether or not an EOF was hit.
118918 */
118919 static int fts3NextMethod(sqlcipher3_vtab_cursor *pCursor){
118920   int rc;
118921   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118922   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
118923     if( SQLCIPHER_ROW!=sqlcipher3_step(pCsr->pStmt) ){
118924       pCsr->isEof = 1;
118925       rc = sqlcipher3_reset(pCsr->pStmt);
118926     }else{
118927       pCsr->iPrevId = sqlcipher3_column_int64(pCsr->pStmt, 0);
118928       rc = SQLCIPHER_OK;
118929     }
118930   }else{
118931     rc = fts3EvalNext((Fts3Cursor *)pCursor);
118932   }
118933   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118934   return rc;
118935 }
118936
118937 /*
118938 ** This is the xFilter interface for the virtual table.  See
118939 ** the virtual table xFilter method documentation for additional
118940 ** information.
118941 **
118942 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
118943 ** the %_content table.
118944 **
118945 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
118946 ** in the %_content table.
118947 **
118948 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
118949 ** column on the left-hand side of the MATCH operator is column
118950 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
118951 ** side of the MATCH operator.
118952 */
118953 static int fts3FilterMethod(
118954   sqlcipher3_vtab_cursor *pCursor,   /* The cursor used for this query */
118955   int idxNum,                     /* Strategy index */
118956   const char *idxStr,             /* Unused */
118957   int nVal,                       /* Number of elements in apVal */
118958   sqlcipher3_value **apVal           /* Arguments for the indexing scheme */
118959 ){
118960   int rc;
118961   char *zSql;                     /* SQL statement used to access %_content */
118962   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
118963   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118964
118965   UNUSED_PARAMETER(idxStr);
118966   UNUSED_PARAMETER(nVal);
118967
118968   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
118969   assert( nVal==0 || nVal==1 );
118970   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
118971   assert( p->pSegments==0 );
118972
118973   /* In case the cursor has been used before, clear it now. */
118974   sqlcipher3_finalize(pCsr->pStmt);
118975   sqlcipher3_free(pCsr->aDoclist);
118976   sqlcipher3Fts3ExprFree(pCsr->pExpr);
118977   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlcipher3_vtab_cursor));
118978
118979   if( idxStr ){
118980     pCsr->bDesc = (idxStr[0]=='D');
118981   }else{
118982     pCsr->bDesc = p->bDescIdx;
118983   }
118984   pCsr->eSearch = (i16)idxNum;
118985
118986   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
118987     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
118988     const char *zQuery = (const char *)sqlcipher3_value_text(apVal[0]);
118989
118990     if( zQuery==0 && sqlcipher3_value_type(apVal[0])!=SQLCIPHER_NULL ){
118991       return SQLCIPHER_NOMEM;
118992     }
118993
118994     rc = sqlcipher3Fts3ExprParse(p->pTokenizer, p->azColumn, p->bHasStat, 
118995         p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
118996     );
118997     if( rc!=SQLCIPHER_OK ){
118998       if( rc==SQLCIPHER_ERROR ){
118999         static const char *zErr = "malformed MATCH expression: [%s]";
119000         p->base.zErrMsg = sqlcipher3_mprintf(zErr, zQuery);
119001       }
119002       return rc;
119003     }
119004
119005     rc = sqlcipher3Fts3ReadLock(p);
119006     if( rc!=SQLCIPHER_OK ) return rc;
119007
119008     rc = fts3EvalStart(pCsr);
119009
119010     sqlcipher3Fts3SegmentsClose(p);
119011     if( rc!=SQLCIPHER_OK ) return rc;
119012     pCsr->pNextId = pCsr->aDoclist;
119013     pCsr->iPrevId = 0;
119014   }
119015
119016   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
119017   ** statement loops through all rows of the %_content table. For a
119018   ** full-text query or docid lookup, the statement retrieves a single
119019   ** row by docid.
119020   */
119021   if( idxNum==FTS3_FULLSCAN_SEARCH ){
119022     zSql = sqlcipher3_mprintf(
119023         "SELECT %s ORDER BY rowid %s",
119024         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
119025     );
119026     if( zSql ){
119027       rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
119028       sqlcipher3_free(zSql);
119029     }else{
119030       rc = SQLCIPHER_NOMEM;
119031     }
119032   }else if( idxNum==FTS3_DOCID_SEARCH ){
119033     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
119034     if( rc==SQLCIPHER_OK ){
119035       rc = sqlcipher3_bind_value(pCsr->pStmt, 1, apVal[0]);
119036     }
119037   }
119038   if( rc!=SQLCIPHER_OK ) return rc;
119039
119040   return fts3NextMethod(pCursor);
119041 }
119042
119043 /* 
119044 ** This is the xEof method of the virtual table. SQLite calls this 
119045 ** routine to find out if it has reached the end of a result set.
119046 */
119047 static int fts3EofMethod(sqlcipher3_vtab_cursor *pCursor){
119048   return ((Fts3Cursor *)pCursor)->isEof;
119049 }
119050
119051 /* 
119052 ** This is the xRowid method. The SQLite core calls this routine to
119053 ** retrieve the rowid for the current row of the result set. fts3
119054 ** exposes %_content.docid as the rowid for the virtual table. The
119055 ** rowid should be written to *pRowid.
119056 */
119057 static int fts3RowidMethod(sqlcipher3_vtab_cursor *pCursor, sqlcipher_int64 *pRowid){
119058   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119059   *pRowid = pCsr->iPrevId;
119060   return SQLCIPHER_OK;
119061 }
119062
119063 /* 
119064 ** This is the xColumn method, called by SQLite to request a value from
119065 ** the row that the supplied cursor currently points to.
119066 */
119067 static int fts3ColumnMethod(
119068   sqlcipher3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119069   sqlcipher3_context *pContext,      /* Context for sqlcipher3_result_xxx() calls */
119070   int iCol                        /* Index of column to read value from */
119071 ){
119072   int rc = SQLCIPHER_OK;             /* Return Code */
119073   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119074   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119075
119076   /* The column value supplied by SQLite must be in range. */
119077   assert( iCol>=0 && iCol<=p->nColumn+1 );
119078
119079   if( iCol==p->nColumn+1 ){
119080     /* This call is a request for the "docid" column. Since "docid" is an 
119081     ** alias for "rowid", use the xRowid() method to obtain the value.
119082     */
119083     sqlcipher3_result_int64(pContext, pCsr->iPrevId);
119084   }else if( iCol==p->nColumn ){
119085     /* The extra column whose name is the same as the table.
119086     ** Return a blob which is a pointer to the cursor.
119087     */
119088     sqlcipher3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLCIPHER_TRANSIENT);
119089   }else{
119090     rc = fts3CursorSeek(0, pCsr);
119091     if( rc==SQLCIPHER_OK && sqlcipher3_data_count(pCsr->pStmt)>(iCol+1) ){
119092       sqlcipher3_result_value(pContext, sqlcipher3_column_value(pCsr->pStmt, iCol+1));
119093     }
119094   }
119095
119096   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119097   return rc;
119098 }
119099
119100 /* 
119101 ** This function is the implementation of the xUpdate callback used by 
119102 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
119103 ** inserted, updated or deleted.
119104 */
119105 static int fts3UpdateMethod(
119106   sqlcipher3_vtab *pVtab,            /* Virtual table handle */
119107   int nArg,                       /* Size of argument array */
119108   sqlcipher3_value **apVal,          /* Array of arguments */
119109   sqlcipher_int64 *pRowid            /* OUT: The affected (or effected) rowid */
119110 ){
119111   return sqlcipher3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
119112 }
119113
119114 /*
119115 ** Implementation of xSync() method. Flush the contents of the pending-terms
119116 ** hash-table to the database.
119117 */
119118 static int fts3SyncMethod(sqlcipher3_vtab *pVtab){
119119   int rc = sqlcipher3Fts3PendingTermsFlush((Fts3Table *)pVtab);
119120   sqlcipher3Fts3SegmentsClose((Fts3Table *)pVtab);
119121   return rc;
119122 }
119123
119124 /*
119125 ** Implementation of xBegin() method. This is a no-op.
119126 */
119127 static int fts3BeginMethod(sqlcipher3_vtab *pVtab){
119128   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119129   UNUSED_PARAMETER(pVtab);
119130   assert( p->pSegments==0 );
119131   assert( p->nPendingData==0 );
119132   assert( p->inTransaction!=1 );
119133   TESTONLY( p->inTransaction = 1 );
119134   TESTONLY( p->mxSavepoint = -1; );
119135   return SQLCIPHER_OK;
119136 }
119137
119138 /*
119139 ** Implementation of xCommit() method. This is a no-op. The contents of
119140 ** the pending-terms hash-table have already been flushed into the database
119141 ** by fts3SyncMethod().
119142 */
119143 static int fts3CommitMethod(sqlcipher3_vtab *pVtab){
119144   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119145   UNUSED_PARAMETER(pVtab);
119146   assert( p->nPendingData==0 );
119147   assert( p->inTransaction!=0 );
119148   assert( p->pSegments==0 );
119149   TESTONLY( p->inTransaction = 0 );
119150   TESTONLY( p->mxSavepoint = -1; );
119151   return SQLCIPHER_OK;
119152 }
119153
119154 /*
119155 ** Implementation of xRollback(). Discard the contents of the pending-terms
119156 ** hash-table. Any changes made to the database are reverted by SQLite.
119157 */
119158 static int fts3RollbackMethod(sqlcipher3_vtab *pVtab){
119159   Fts3Table *p = (Fts3Table*)pVtab;
119160   sqlcipher3Fts3PendingTermsClear(p);
119161   assert( p->inTransaction!=0 );
119162   TESTONLY( p->inTransaction = 0 );
119163   TESTONLY( p->mxSavepoint = -1; );
119164   return SQLCIPHER_OK;
119165 }
119166
119167 /*
119168 ** When called, *ppPoslist must point to the byte immediately following the
119169 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
119170 ** moves *ppPoslist so that it instead points to the first byte of the
119171 ** same position list.
119172 */
119173 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
119174   char *p = &(*ppPoslist)[-2];
119175   char c = 0;
119176
119177   while( p>pStart && (c=*p--)==0 );
119178   while( p>pStart && (*p & 0x80) | c ){ 
119179     c = *p--; 
119180   }
119181   if( p>pStart ){ p = &p[2]; }
119182   while( *p++&0x80 );
119183   *ppPoslist = p;
119184 }
119185
119186 /*
119187 ** Helper function used by the implementation of the overloaded snippet(),
119188 ** offsets() and optimize() SQL functions.
119189 **
119190 ** If the value passed as the third argument is a blob of size
119191 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
119192 ** output variable *ppCsr and SQLCIPHER_OK is returned. Otherwise, an error
119193 ** message is written to context pContext and SQLCIPHER_ERROR returned. The
119194 ** string passed via zFunc is used as part of the error message.
119195 */
119196 static int fts3FunctionArg(
119197   sqlcipher3_context *pContext,      /* SQL function call context */
119198   const char *zFunc,              /* Function name */
119199   sqlcipher3_value *pVal,            /* argv[0] passed to function */
119200   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
119201 ){
119202   Fts3Cursor *pRet;
119203   if( sqlcipher3_value_type(pVal)!=SQLCIPHER_BLOB 
119204    || sqlcipher3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
119205   ){
119206     char *zErr = sqlcipher3_mprintf("illegal first argument to %s", zFunc);
119207     sqlcipher3_result_error(pContext, zErr, -1);
119208     sqlcipher3_free(zErr);
119209     return SQLCIPHER_ERROR;
119210   }
119211   memcpy(&pRet, sqlcipher3_value_blob(pVal), sizeof(Fts3Cursor *));
119212   *ppCsr = pRet;
119213   return SQLCIPHER_OK;
119214 }
119215
119216 /*
119217 ** Implementation of the snippet() function for FTS3
119218 */
119219 static void fts3SnippetFunc(
119220   sqlcipher3_context *pContext,      /* SQLite function call context */
119221   int nVal,                       /* Size of apVal[] array */
119222   sqlcipher3_value **apVal           /* Array of arguments */
119223 ){
119224   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119225   const char *zStart = "<b>";
119226   const char *zEnd = "</b>";
119227   const char *zEllipsis = "<b>...</b>";
119228   int iCol = -1;
119229   int nToken = 15;                /* Default number of tokens in snippet */
119230
119231   /* There must be at least one argument passed to this function (otherwise
119232   ** the non-overloaded version would have been called instead of this one).
119233   */
119234   assert( nVal>=1 );
119235
119236   if( nVal>6 ){
119237     sqlcipher3_result_error(pContext, 
119238         "wrong number of arguments to function snippet()", -1);
119239     return;
119240   }
119241   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
119242
119243   switch( nVal ){
119244     case 6: nToken = sqlcipher3_value_int(apVal[5]);
119245     case 5: iCol = sqlcipher3_value_int(apVal[4]);
119246     case 4: zEllipsis = (const char*)sqlcipher3_value_text(apVal[3]);
119247     case 3: zEnd = (const char*)sqlcipher3_value_text(apVal[2]);
119248     case 2: zStart = (const char*)sqlcipher3_value_text(apVal[1]);
119249   }
119250   if( !zEllipsis || !zEnd || !zStart ){
119251     sqlcipher3_result_error_nomem(pContext);
119252   }else if( SQLCIPHER_OK==fts3CursorSeek(pContext, pCsr) ){
119253     sqlcipher3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
119254   }
119255 }
119256
119257 /*
119258 ** Implementation of the offsets() function for FTS3
119259 */
119260 static void fts3OffsetsFunc(
119261   sqlcipher3_context *pContext,      /* SQLite function call context */
119262   int nVal,                       /* Size of argument array */
119263   sqlcipher3_value **apVal           /* Array of arguments */
119264 ){
119265   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119266
119267   UNUSED_PARAMETER(nVal);
119268
119269   assert( nVal==1 );
119270   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
119271   assert( pCsr );
119272   if( SQLCIPHER_OK==fts3CursorSeek(pContext, pCsr) ){
119273     sqlcipher3Fts3Offsets(pContext, pCsr);
119274   }
119275 }
119276
119277 /* 
119278 ** Implementation of the special optimize() function for FTS3. This 
119279 ** function merges all segments in the database to a single segment.
119280 ** Example usage is:
119281 **
119282 **   SELECT optimize(t) FROM t LIMIT 1;
119283 **
119284 ** where 't' is the name of an FTS3 table.
119285 */
119286 static void fts3OptimizeFunc(
119287   sqlcipher3_context *pContext,      /* SQLite function call context */
119288   int nVal,                       /* Size of argument array */
119289   sqlcipher3_value **apVal           /* Array of arguments */
119290 ){
119291   int rc;                         /* Return code */
119292   Fts3Table *p;                   /* Virtual table handle */
119293   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
119294
119295   UNUSED_PARAMETER(nVal);
119296
119297   assert( nVal==1 );
119298   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
119299   p = (Fts3Table *)pCursor->base.pVtab;
119300   assert( p );
119301
119302   rc = sqlcipher3Fts3Optimize(p);
119303
119304   switch( rc ){
119305     case SQLCIPHER_OK:
119306       sqlcipher3_result_text(pContext, "Index optimized", -1, SQLCIPHER_STATIC);
119307       break;
119308     case SQLCIPHER_DONE:
119309       sqlcipher3_result_text(pContext, "Index already optimal", -1, SQLCIPHER_STATIC);
119310       break;
119311     default:
119312       sqlcipher3_result_error_code(pContext, rc);
119313       break;
119314   }
119315 }
119316
119317 /*
119318 ** Implementation of the matchinfo() function for FTS3
119319 */
119320 static void fts3MatchinfoFunc(
119321   sqlcipher3_context *pContext,      /* SQLite function call context */
119322   int nVal,                       /* Size of argument array */
119323   sqlcipher3_value **apVal           /* Array of arguments */
119324 ){
119325   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119326   assert( nVal==1 || nVal==2 );
119327   if( SQLCIPHER_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
119328     const char *zArg = 0;
119329     if( nVal>1 ){
119330       zArg = (const char *)sqlcipher3_value_text(apVal[1]);
119331     }
119332     sqlcipher3Fts3Matchinfo(pContext, pCsr, zArg);
119333   }
119334 }
119335
119336 /*
119337 ** This routine implements the xFindFunction method for the FTS3
119338 ** virtual table.
119339 */
119340 static int fts3FindFunctionMethod(
119341   sqlcipher3_vtab *pVtab,            /* Virtual table handle */
119342   int nArg,                       /* Number of SQL function arguments */
119343   const char *zName,              /* Name of SQL function */
119344   void (**pxFunc)(sqlcipher3_context*,int,sqlcipher3_value**), /* OUT: Result */
119345   void **ppArg                    /* Unused */
119346 ){
119347   struct Overloaded {
119348     const char *zName;
119349     void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**);
119350   } aOverload[] = {
119351     { "snippet", fts3SnippetFunc },
119352     { "offsets", fts3OffsetsFunc },
119353     { "optimize", fts3OptimizeFunc },
119354     { "matchinfo", fts3MatchinfoFunc },
119355   };
119356   int i;                          /* Iterator variable */
119357
119358   UNUSED_PARAMETER(pVtab);
119359   UNUSED_PARAMETER(nArg);
119360   UNUSED_PARAMETER(ppArg);
119361
119362   for(i=0; i<SizeofArray(aOverload); i++){
119363     if( strcmp(zName, aOverload[i].zName)==0 ){
119364       *pxFunc = aOverload[i].xFunc;
119365       return 1;
119366     }
119367   }
119368
119369   /* No function of the specified name was found. Return 0. */
119370   return 0;
119371 }
119372
119373 /*
119374 ** Implementation of FTS3 xRename method. Rename an fts3 table.
119375 */
119376 static int fts3RenameMethod(
119377   sqlcipher3_vtab *pVtab,            /* Virtual table handle */
119378   const char *zName               /* New name of table */
119379 ){
119380   Fts3Table *p = (Fts3Table *)pVtab;
119381   sqlcipher3 *db = p->db;            /* Database connection */
119382   int rc;                         /* Return Code */
119383
119384   /* As it happens, the pending terms table is always empty here. This is
119385   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
119386   ** always opens a savepoint transaction. And the xSavepoint() method 
119387   ** flushes the pending terms table. But leave the (no-op) call to
119388   ** PendingTermsFlush() in in case that changes.
119389   */
119390   assert( p->nPendingData==0 );
119391   rc = sqlcipher3Fts3PendingTermsFlush(p);
119392
119393   if( p->zContentTbl==0 ){
119394     fts3DbExec(&rc, db,
119395       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
119396       p->zDb, p->zName, zName
119397     );
119398   }
119399
119400   if( p->bHasDocsize ){
119401     fts3DbExec(&rc, db,
119402       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
119403       p->zDb, p->zName, zName
119404     );
119405   }
119406   if( p->bHasStat ){
119407     fts3DbExec(&rc, db,
119408       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
119409       p->zDb, p->zName, zName
119410     );
119411   }
119412   fts3DbExec(&rc, db,
119413     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
119414     p->zDb, p->zName, zName
119415   );
119416   fts3DbExec(&rc, db,
119417     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
119418     p->zDb, p->zName, zName
119419   );
119420   return rc;
119421 }
119422
119423 /*
119424 ** The xSavepoint() method.
119425 **
119426 ** Flush the contents of the pending-terms table to disk.
119427 */
119428 static int fts3SavepointMethod(sqlcipher3_vtab *pVtab, int iSavepoint){
119429   UNUSED_PARAMETER(iSavepoint);
119430   assert( ((Fts3Table *)pVtab)->inTransaction );
119431   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
119432   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
119433   return fts3SyncMethod(pVtab);
119434 }
119435
119436 /*
119437 ** The xRelease() method.
119438 **
119439 ** This is a no-op.
119440 */
119441 static int fts3ReleaseMethod(sqlcipher3_vtab *pVtab, int iSavepoint){
119442   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119443   UNUSED_PARAMETER(iSavepoint);
119444   UNUSED_PARAMETER(pVtab);
119445   assert( p->inTransaction );
119446   assert( p->mxSavepoint >= iSavepoint );
119447   TESTONLY( p->mxSavepoint = iSavepoint-1 );
119448   return SQLCIPHER_OK;
119449 }
119450
119451 /*
119452 ** The xRollbackTo() method.
119453 **
119454 ** Discard the contents of the pending terms table.
119455 */
119456 static int fts3RollbackToMethod(sqlcipher3_vtab *pVtab, int iSavepoint){
119457   Fts3Table *p = (Fts3Table*)pVtab;
119458   UNUSED_PARAMETER(iSavepoint);
119459   assert( p->inTransaction );
119460   assert( p->mxSavepoint >= iSavepoint );
119461   TESTONLY( p->mxSavepoint = iSavepoint );
119462   sqlcipher3Fts3PendingTermsClear(p);
119463   return SQLCIPHER_OK;
119464 }
119465
119466 static const sqlcipher3_module fts3Module = {
119467   /* iVersion      */ 2,
119468   /* xCreate       */ fts3CreateMethod,
119469   /* xConnect      */ fts3ConnectMethod,
119470   /* xBestIndex    */ fts3BestIndexMethod,
119471   /* xDisconnect   */ fts3DisconnectMethod,
119472   /* xDestroy      */ fts3DestroyMethod,
119473   /* xOpen         */ fts3OpenMethod,
119474   /* xClose        */ fts3CloseMethod,
119475   /* xFilter       */ fts3FilterMethod,
119476   /* xNext         */ fts3NextMethod,
119477   /* xEof          */ fts3EofMethod,
119478   /* xColumn       */ fts3ColumnMethod,
119479   /* xRowid        */ fts3RowidMethod,
119480   /* xUpdate       */ fts3UpdateMethod,
119481   /* xBegin        */ fts3BeginMethod,
119482   /* xSync         */ fts3SyncMethod,
119483   /* xCommit       */ fts3CommitMethod,
119484   /* xRollback     */ fts3RollbackMethod,
119485   /* xFindFunction */ fts3FindFunctionMethod,
119486   /* xRename */       fts3RenameMethod,
119487   /* xSavepoint    */ fts3SavepointMethod,
119488   /* xRelease      */ fts3ReleaseMethod,
119489   /* xRollbackTo   */ fts3RollbackToMethod,
119490 };
119491
119492 /*
119493 ** This function is registered as the module destructor (called when an
119494 ** FTS3 enabled database connection is closed). It frees the memory
119495 ** allocated for the tokenizer hash table.
119496 */
119497 static void hashDestroy(void *p){
119498   Fts3Hash *pHash = (Fts3Hash *)p;
119499   sqlcipher3Fts3HashClear(pHash);
119500   sqlcipher3_free(pHash);
119501 }
119502
119503 /*
119504 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
119505 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
119506 ** respectively. The following three forward declarations are for functions
119507 ** declared in these files used to retrieve the respective implementations.
119508 **
119509 ** Calling sqlcipher3Fts3SimpleTokenizerModule() sets the value pointed
119510 ** to by the argument to point to the "simple" tokenizer implementation.
119511 ** And so on.
119512 */
119513 SQLCIPHER_PRIVATE void sqlcipher3Fts3SimpleTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
119514 SQLCIPHER_PRIVATE void sqlcipher3Fts3PorterTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
119515 #ifdef SQLCIPHER_ENABLE_ICU
119516 SQLCIPHER_PRIVATE void sqlcipher3Fts3IcuTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
119517 #endif
119518
119519 /*
119520 ** Initialise the fts3 extension. If this extension is built as part
119521 ** of the sqlcipher library, then this function is called directly by
119522 ** SQLite. If fts3 is built as a dynamically loadable extension, this
119523 ** function is called by the sqlcipher3_extension_init() entry point.
119524 */
119525 SQLCIPHER_PRIVATE int sqlcipher3Fts3Init(sqlcipher3 *db){
119526   int rc = SQLCIPHER_OK;
119527   Fts3Hash *pHash = 0;
119528   const sqlcipher3_tokenizer_module *pSimple = 0;
119529   const sqlcipher3_tokenizer_module *pPorter = 0;
119530
119531 #ifdef SQLCIPHER_ENABLE_ICU
119532   const sqlcipher3_tokenizer_module *pIcu = 0;
119533   sqlcipher3Fts3IcuTokenizerModule(&pIcu);
119534 #endif
119535
119536 #ifdef SQLCIPHER_TEST
119537   rc = sqlcipher3Fts3InitTerm(db);
119538   if( rc!=SQLCIPHER_OK ) return rc;
119539 #endif
119540
119541   rc = sqlcipher3Fts3InitAux(db);
119542   if( rc!=SQLCIPHER_OK ) return rc;
119543
119544   sqlcipher3Fts3SimpleTokenizerModule(&pSimple);
119545   sqlcipher3Fts3PorterTokenizerModule(&pPorter);
119546
119547   /* Allocate and initialise the hash-table used to store tokenizers. */
119548   pHash = sqlcipher3_malloc(sizeof(Fts3Hash));
119549   if( !pHash ){
119550     rc = SQLCIPHER_NOMEM;
119551   }else{
119552     sqlcipher3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
119553   }
119554
119555   /* Load the built-in tokenizers into the hash table */
119556   if( rc==SQLCIPHER_OK ){
119557     if( sqlcipher3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
119558      || sqlcipher3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
119559 #ifdef SQLCIPHER_ENABLE_ICU
119560      || (pIcu && sqlcipher3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
119561 #endif
119562     ){
119563       rc = SQLCIPHER_NOMEM;
119564     }
119565   }
119566
119567 #ifdef SQLCIPHER_TEST
119568   if( rc==SQLCIPHER_OK ){
119569     rc = sqlcipher3Fts3ExprInitTestInterface(db);
119570   }
119571 #endif
119572
119573   /* Create the virtual table wrapper around the hash-table and overload 
119574   ** the two scalar functions. If this is successful, register the
119575   ** module with sqlcipher.
119576   */
119577   if( SQLCIPHER_OK==rc 
119578    && SQLCIPHER_OK==(rc = sqlcipher3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
119579    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "snippet", -1))
119580    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "offsets", 1))
119581    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "matchinfo", 1))
119582    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "matchinfo", 2))
119583    && SQLCIPHER_OK==(rc = sqlcipher3_overload_function(db, "optimize", 1))
119584   ){
119585     rc = sqlcipher3_create_module_v2(
119586         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
119587     );
119588     if( rc==SQLCIPHER_OK ){
119589       rc = sqlcipher3_create_module_v2(
119590           db, "fts4", &fts3Module, (void *)pHash, 0
119591       );
119592     }
119593     return rc;
119594   }
119595
119596   /* An error has occurred. Delete the hash table and return the error code. */
119597   assert( rc!=SQLCIPHER_OK );
119598   if( pHash ){
119599     sqlcipher3Fts3HashClear(pHash);
119600     sqlcipher3_free(pHash);
119601   }
119602   return rc;
119603 }
119604
119605 /*
119606 ** Allocate an Fts3MultiSegReader for each token in the expression headed
119607 ** by pExpr. 
119608 **
119609 ** An Fts3SegReader object is a cursor that can seek or scan a range of
119610 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
119611 ** Fts3SegReader objects internally to provide an interface to seek or scan
119612 ** within the union of all segments of a b-tree. Hence the name.
119613 **
119614 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
119615 ** segment b-tree (if the term is not a prefix or it is a prefix for which
119616 ** there exists prefix b-tree of the right length) then it may be traversed
119617 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
119618 ** doclist and then traversed.
119619 */
119620 static void fts3EvalAllocateReaders(
119621   Fts3Cursor *pCsr,               /* FTS cursor handle */
119622   Fts3Expr *pExpr,                /* Allocate readers for this expression */
119623   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
119624   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
119625   int *pRc                        /* IN/OUT: Error code */
119626 ){
119627   if( pExpr && SQLCIPHER_OK==*pRc ){
119628     if( pExpr->eType==FTSQUERY_PHRASE ){
119629       int i;
119630       int nToken = pExpr->pPhrase->nToken;
119631       *pnToken += nToken;
119632       for(i=0; i<nToken; i++){
119633         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
119634         int rc = fts3TermSegReaderCursor(pCsr, 
119635             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
119636         );
119637         if( rc!=SQLCIPHER_OK ){
119638           *pRc = rc;
119639           return;
119640         }
119641       }
119642       assert( pExpr->pPhrase->iDoclistToken==0 );
119643       pExpr->pPhrase->iDoclistToken = -1;
119644     }else{
119645       *pnOr += (pExpr->eType==FTSQUERY_OR);
119646       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
119647       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
119648     }
119649   }
119650 }
119651
119652 /*
119653 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
119654 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
119655 **
119656 ** This function assumes that pList points to a buffer allocated using
119657 ** sqlcipher3_malloc(). This function takes responsibility for eventually
119658 ** freeing the buffer.
119659 */
119660 static void fts3EvalPhraseMergeToken(
119661   Fts3Table *pTab,                /* FTS Table pointer */
119662   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
119663   int iToken,                     /* Token pList/nList corresponds to */
119664   char *pList,                    /* Pointer to doclist */
119665   int nList                       /* Number of bytes in pList */
119666 ){
119667   assert( iToken!=p->iDoclistToken );
119668
119669   if( pList==0 ){
119670     sqlcipher3_free(p->doclist.aAll);
119671     p->doclist.aAll = 0;
119672     p->doclist.nAll = 0;
119673   }
119674
119675   else if( p->iDoclistToken<0 ){
119676     p->doclist.aAll = pList;
119677     p->doclist.nAll = nList;
119678   }
119679
119680   else if( p->doclist.aAll==0 ){
119681     sqlcipher3_free(pList);
119682   }
119683
119684   else {
119685     char *pLeft;
119686     char *pRight;
119687     int nLeft;
119688     int nRight;
119689     int nDiff;
119690
119691     if( p->iDoclistToken<iToken ){
119692       pLeft = p->doclist.aAll;
119693       nLeft = p->doclist.nAll;
119694       pRight = pList;
119695       nRight = nList;
119696       nDiff = iToken - p->iDoclistToken;
119697     }else{
119698       pRight = p->doclist.aAll;
119699       nRight = p->doclist.nAll;
119700       pLeft = pList;
119701       nLeft = nList;
119702       nDiff = p->iDoclistToken - iToken;
119703     }
119704
119705     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
119706     sqlcipher3_free(pLeft);
119707     p->doclist.aAll = pRight;
119708     p->doclist.nAll = nRight;
119709   }
119710
119711   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
119712 }
119713
119714 /*
119715 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
119716 ** does not take deferred tokens into account.
119717 **
119718 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
119719 */
119720 static int fts3EvalPhraseLoad(
119721   Fts3Cursor *pCsr,               /* FTS Cursor handle */
119722   Fts3Phrase *p                   /* Phrase object */
119723 ){
119724   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119725   int iToken;
119726   int rc = SQLCIPHER_OK;
119727
119728   for(iToken=0; rc==SQLCIPHER_OK && iToken<p->nToken; iToken++){
119729     Fts3PhraseToken *pToken = &p->aToken[iToken];
119730     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
119731
119732     if( pToken->pSegcsr ){
119733       int nThis = 0;
119734       char *pThis = 0;
119735       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
119736       if( rc==SQLCIPHER_OK ){
119737         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
119738       }
119739     }
119740     assert( pToken->pSegcsr==0 );
119741   }
119742
119743   return rc;
119744 }
119745
119746 /*
119747 ** This function is called on each phrase after the position lists for
119748 ** any deferred tokens have been loaded into memory. It updates the phrases
119749 ** current position list to include only those positions that are really
119750 ** instances of the phrase (after considering deferred tokens). If this
119751 ** means that the phrase does not appear in the current row, doclist.pList
119752 ** and doclist.nList are both zeroed.
119753 **
119754 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
119755 */
119756 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
119757   int iToken;                     /* Used to iterate through phrase tokens */
119758   char *aPoslist = 0;             /* Position list for deferred tokens */
119759   int nPoslist = 0;               /* Number of bytes in aPoslist */
119760   int iPrev = -1;                 /* Token number of previous deferred token */
119761
119762   assert( pPhrase->doclist.bFreeList==0 );
119763
119764   for(iToken=0; iToken<pPhrase->nToken; iToken++){
119765     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
119766     Fts3DeferredToken *pDeferred = pToken->pDeferred;
119767
119768     if( pDeferred ){
119769       char *pList;
119770       int nList;
119771       int rc = sqlcipher3Fts3DeferredTokenList(pDeferred, &pList, &nList);
119772       if( rc!=SQLCIPHER_OK ) return rc;
119773
119774       if( pList==0 ){
119775         sqlcipher3_free(aPoslist);
119776         pPhrase->doclist.pList = 0;
119777         pPhrase->doclist.nList = 0;
119778         return SQLCIPHER_OK;
119779
119780       }else if( aPoslist==0 ){
119781         aPoslist = pList;
119782         nPoslist = nList;
119783
119784       }else{
119785         char *aOut = pList;
119786         char *p1 = aPoslist;
119787         char *p2 = aOut;
119788
119789         assert( iPrev>=0 );
119790         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
119791         sqlcipher3_free(aPoslist);
119792         aPoslist = pList;
119793         nPoslist = aOut - aPoslist;
119794         if( nPoslist==0 ){
119795           sqlcipher3_free(aPoslist);
119796           pPhrase->doclist.pList = 0;
119797           pPhrase->doclist.nList = 0;
119798           return SQLCIPHER_OK;
119799         }
119800       }
119801       iPrev = iToken;
119802     }
119803   }
119804
119805   if( iPrev>=0 ){
119806     int nMaxUndeferred = pPhrase->iDoclistToken;
119807     if( nMaxUndeferred<0 ){
119808       pPhrase->doclist.pList = aPoslist;
119809       pPhrase->doclist.nList = nPoslist;
119810       pPhrase->doclist.iDocid = pCsr->iPrevId;
119811       pPhrase->doclist.bFreeList = 1;
119812     }else{
119813       int nDistance;
119814       char *p1;
119815       char *p2;
119816       char *aOut;
119817
119818       if( nMaxUndeferred>iPrev ){
119819         p1 = aPoslist;
119820         p2 = pPhrase->doclist.pList;
119821         nDistance = nMaxUndeferred - iPrev;
119822       }else{
119823         p1 = pPhrase->doclist.pList;
119824         p2 = aPoslist;
119825         nDistance = iPrev - nMaxUndeferred;
119826       }
119827
119828       aOut = (char *)sqlcipher3_malloc(nPoslist+8);
119829       if( !aOut ){
119830         sqlcipher3_free(aPoslist);
119831         return SQLCIPHER_NOMEM;
119832       }
119833       
119834       pPhrase->doclist.pList = aOut;
119835       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
119836         pPhrase->doclist.bFreeList = 1;
119837         pPhrase->doclist.nList = (aOut - pPhrase->doclist.pList);
119838       }else{
119839         sqlcipher3_free(aOut);
119840         pPhrase->doclist.pList = 0;
119841         pPhrase->doclist.nList = 0;
119842       }
119843       sqlcipher3_free(aPoslist);
119844     }
119845   }
119846
119847   return SQLCIPHER_OK;
119848 }
119849
119850 /*
119851 ** This function is called for each Fts3Phrase in a full-text query 
119852 ** expression to initialize the mechanism for returning rows. Once this
119853 ** function has been called successfully on an Fts3Phrase, it may be
119854 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
119855 **
119856 ** If parameter bOptOk is true, then the phrase may (or may not) use the
119857 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
119858 ** memory within this call.
119859 **
119860 ** SQLCIPHER_OK is returned if no error occurs, otherwise an SQLite error code.
119861 */
119862 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
119863   int rc;                         /* Error code */
119864   Fts3PhraseToken *pFirst = &p->aToken[0];
119865   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119866
119867   if( pCsr->bDesc==pTab->bDescIdx 
119868    && bOptOk==1 
119869    && p->nToken==1 
119870    && pFirst->pSegcsr 
119871    && pFirst->pSegcsr->bLookup 
119872    && pFirst->bFirst==0
119873   ){
119874     /* Use the incremental approach. */
119875     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
119876     rc = sqlcipher3Fts3MsrIncrStart(
119877         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
119878     p->bIncr = 1;
119879
119880   }else{
119881     /* Load the full doclist for the phrase into memory. */
119882     rc = fts3EvalPhraseLoad(pCsr, p);
119883     p->bIncr = 0;
119884   }
119885
119886   assert( rc!=SQLCIPHER_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
119887   return rc;
119888 }
119889
119890 /*
119891 ** This function is used to iterate backwards (from the end to start) 
119892 ** through doclists. It is used by this module to iterate through phrase
119893 ** doclists in reverse and by the fts3_write.c module to iterate through
119894 ** pending-terms lists when writing to databases with "order=desc".
119895 **
119896 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
119897 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
119898 ** function iterates from the end of the doclist to the beginning.
119899 */
119900 SQLCIPHER_PRIVATE void sqlcipher3Fts3DoclistPrev(
119901   int bDescIdx,                   /* True if the doclist is desc */
119902   char *aDoclist,                 /* Pointer to entire doclist */
119903   int nDoclist,                   /* Length of aDoclist in bytes */
119904   char **ppIter,                  /* IN/OUT: Iterator pointer */
119905   sqlcipher3_int64 *piDocid,         /* IN/OUT: Docid pointer */
119906   int *pnList,                    /* IN/OUT: List length pointer */
119907   u8 *pbEof                       /* OUT: End-of-file flag */
119908 ){
119909   char *p = *ppIter;
119910
119911   assert( nDoclist>0 );
119912   assert( *pbEof==0 );
119913   assert( p || *piDocid==0 );
119914   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
119915
119916   if( p==0 ){
119917     sqlcipher3_int64 iDocid = 0;
119918     char *pNext = 0;
119919     char *pDocid = aDoclist;
119920     char *pEnd = &aDoclist[nDoclist];
119921     int iMul = 1;
119922
119923     while( pDocid<pEnd ){
119924       sqlcipher3_int64 iDelta;
119925       pDocid += sqlcipher3Fts3GetVarint(pDocid, &iDelta);
119926       iDocid += (iMul * iDelta);
119927       pNext = pDocid;
119928       fts3PoslistCopy(0, &pDocid);
119929       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
119930       iMul = (bDescIdx ? -1 : 1);
119931     }
119932
119933     *pnList = pEnd - pNext;
119934     *ppIter = pNext;
119935     *piDocid = iDocid;
119936   }else{
119937     int iMul = (bDescIdx ? -1 : 1);
119938     sqlcipher3_int64 iDelta;
119939     fts3GetReverseVarint(&p, aDoclist, &iDelta);
119940     *piDocid -= (iMul * iDelta);
119941
119942     if( p==aDoclist ){
119943       *pbEof = 1;
119944     }else{
119945       char *pSave = p;
119946       fts3ReversePoslist(aDoclist, &p);
119947       *pnList = (pSave - p);
119948     }
119949     *ppIter = p;
119950   }
119951 }
119952
119953 /*
119954 ** Attempt to move the phrase iterator to point to the next matching docid. 
119955 ** If an error occurs, return an SQLite error code. Otherwise, return 
119956 ** SQLCIPHER_OK.
119957 **
119958 ** If there is no "next" entry and no error occurs, then *pbEof is set to
119959 ** 1 before returning. Otherwise, if no error occurs and the iterator is
119960 ** successfully advanced, *pbEof is set to 0.
119961 */
119962 static int fts3EvalPhraseNext(
119963   Fts3Cursor *pCsr,               /* FTS Cursor handle */
119964   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
119965   u8 *pbEof                       /* OUT: Set to 1 if EOF */
119966 ){
119967   int rc = SQLCIPHER_OK;
119968   Fts3Doclist *pDL = &p->doclist;
119969   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119970
119971   if( p->bIncr ){
119972     assert( p->nToken==1 );
119973     assert( pDL->pNextDocid==0 );
119974     rc = sqlcipher3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
119975         &pDL->iDocid, &pDL->pList, &pDL->nList
119976     );
119977     if( rc==SQLCIPHER_OK && !pDL->pList ){
119978       *pbEof = 1;
119979     }
119980   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
119981     sqlcipher3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
119982         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
119983     );
119984     pDL->pList = pDL->pNextDocid;
119985   }else{
119986     char *pIter;                            /* Used to iterate through aAll */
119987     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
119988     if( pDL->pNextDocid ){
119989       pIter = pDL->pNextDocid;
119990     }else{
119991       pIter = pDL->aAll;
119992     }
119993
119994     if( pIter>=pEnd ){
119995       /* We have already reached the end of this doclist. EOF. */
119996       *pbEof = 1;
119997     }else{
119998       sqlcipher3_int64 iDelta;
119999       pIter += sqlcipher3Fts3GetVarint(pIter, &iDelta);
120000       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
120001         pDL->iDocid += iDelta;
120002       }else{
120003         pDL->iDocid -= iDelta;
120004       }
120005       pDL->pList = pIter;
120006       fts3PoslistCopy(0, &pIter);
120007       pDL->nList = (pIter - pDL->pList);
120008
120009       /* pIter now points just past the 0x00 that terminates the position-
120010       ** list for document pDL->iDocid. However, if this position-list was
120011       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
120012       ** point to the start of the next docid value. The following line deals
120013       ** with this case by advancing pIter past the zero-padding added by
120014       ** fts3EvalNearTrim().  */
120015       while( pIter<pEnd && *pIter==0 ) pIter++;
120016
120017       pDL->pNextDocid = pIter;
120018       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
120019       *pbEof = 0;
120020     }
120021   }
120022
120023   return rc;
120024 }
120025
120026 /*
120027 **
120028 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op.
120029 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
120030 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
120031 ** expressions for which all descendent tokens are deferred.
120032 **
120033 ** If parameter bOptOk is zero, then it is guaranteed that the
120034 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
120035 ** each phrase in the expression (subject to deferred token processing).
120036 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
120037 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
120038 **
120039 ** If an error occurs within this function, *pRc is set to an SQLite error
120040 ** code before returning.
120041 */
120042 static void fts3EvalStartReaders(
120043   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120044   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
120045   int bOptOk,                     /* True to enable incremental loading */
120046   int *pRc                        /* IN/OUT: Error code */
120047 ){
120048   if( pExpr && SQLCIPHER_OK==*pRc ){
120049     if( pExpr->eType==FTSQUERY_PHRASE ){
120050       int i;
120051       int nToken = pExpr->pPhrase->nToken;
120052       for(i=0; i<nToken; i++){
120053         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
120054       }
120055       pExpr->bDeferred = (i==nToken);
120056       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
120057     }else{
120058       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
120059       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
120060       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
120061     }
120062   }
120063 }
120064
120065 /*
120066 ** An array of the following structures is assembled as part of the process
120067 ** of selecting tokens to defer before the query starts executing (as part
120068 ** of the xFilter() method). There is one element in the array for each
120069 ** token in the FTS expression.
120070 **
120071 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
120072 ** to phrases that are connected only by AND and NEAR operators (not OR or
120073 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
120074 ** separately. The root of a tokens AND/NEAR cluster is stored in 
120075 ** Fts3TokenAndCost.pRoot.
120076 */
120077 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
120078 struct Fts3TokenAndCost {
120079   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
120080   int iToken;                     /* Position of token in phrase */
120081   Fts3PhraseToken *pToken;        /* The token itself */
120082   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
120083   int nOvfl;                      /* Number of overflow pages to load doclist */
120084   int iCol;                       /* The column the token must match */
120085 };
120086
120087 /*
120088 ** This function is used to populate an allocated Fts3TokenAndCost array.
120089 **
120090 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op.
120091 ** Otherwise, if an error occurs during execution, *pRc is set to an
120092 ** SQLite error code.
120093 */
120094 static void fts3EvalTokenCosts(
120095   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120096   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
120097   Fts3Expr *pExpr,                /* Expression to consider */
120098   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
120099   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
120100   int *pRc                        /* IN/OUT: Error code */
120101 ){
120102   if( *pRc==SQLCIPHER_OK ){
120103     if( pExpr->eType==FTSQUERY_PHRASE ){
120104       Fts3Phrase *pPhrase = pExpr->pPhrase;
120105       int i;
120106       for(i=0; *pRc==SQLCIPHER_OK && i<pPhrase->nToken; i++){
120107         Fts3TokenAndCost *pTC = (*ppTC)++;
120108         pTC->pPhrase = pPhrase;
120109         pTC->iToken = i;
120110         pTC->pRoot = pRoot;
120111         pTC->pToken = &pPhrase->aToken[i];
120112         pTC->iCol = pPhrase->iColumn;
120113         *pRc = sqlcipher3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
120114       }
120115     }else if( pExpr->eType!=FTSQUERY_NOT ){
120116       assert( pExpr->eType==FTSQUERY_OR
120117            || pExpr->eType==FTSQUERY_AND
120118            || pExpr->eType==FTSQUERY_NEAR
120119       );
120120       assert( pExpr->pLeft && pExpr->pRight );
120121       if( pExpr->eType==FTSQUERY_OR ){
120122         pRoot = pExpr->pLeft;
120123         **ppOr = pRoot;
120124         (*ppOr)++;
120125       }
120126       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
120127       if( pExpr->eType==FTSQUERY_OR ){
120128         pRoot = pExpr->pRight;
120129         **ppOr = pRoot;
120130         (*ppOr)++;
120131       }
120132       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
120133     }
120134   }
120135 }
120136
120137 /*
120138 ** Determine the average document (row) size in pages. If successful,
120139 ** write this value to *pnPage and return SQLCIPHER_OK. Otherwise, return
120140 ** an SQLite error code.
120141 **
120142 ** The average document size in pages is calculated by first calculating 
120143 ** determining the average size in bytes, B. If B is less than the amount
120144 ** of data that will fit on a single leaf page of an intkey table in
120145 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
120146 ** the number of overflow pages consumed by a record B bytes in size.
120147 */
120148 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
120149   if( pCsr->nRowAvg==0 ){
120150     /* The average document size, which is required to calculate the cost
120151     ** of each doclist, has not yet been determined. Read the required 
120152     ** data from the %_stat table to calculate it.
120153     **
120154     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
120155     ** varints, where nCol is the number of columns in the FTS3 table.
120156     ** The first varint is the number of documents currently stored in
120157     ** the table. The following nCol varints contain the total amount of
120158     ** data stored in all rows of each column of the table, from left
120159     ** to right.
120160     */
120161     int rc;
120162     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120163     sqlcipher3_stmt *pStmt;
120164     sqlcipher3_int64 nDoc = 0;
120165     sqlcipher3_int64 nByte = 0;
120166     const char *pEnd;
120167     const char *a;
120168
120169     rc = sqlcipher3Fts3SelectDoctotal(p, &pStmt);
120170     if( rc!=SQLCIPHER_OK ) return rc;
120171     a = sqlcipher3_column_blob(pStmt, 0);
120172     assert( a );
120173
120174     pEnd = &a[sqlcipher3_column_bytes(pStmt, 0)];
120175     a += sqlcipher3Fts3GetVarint(a, &nDoc);
120176     while( a<pEnd ){
120177       a += sqlcipher3Fts3GetVarint(a, &nByte);
120178     }
120179     if( nDoc==0 || nByte==0 ){
120180       sqlcipher3_reset(pStmt);
120181       return FTS_CORRUPT_VTAB;
120182     }
120183
120184     pCsr->nDoc = nDoc;
120185     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
120186     assert( pCsr->nRowAvg>0 ); 
120187     rc = sqlcipher3_reset(pStmt);
120188     if( rc!=SQLCIPHER_OK ) return rc;
120189   }
120190
120191   *pnPage = pCsr->nRowAvg;
120192   return SQLCIPHER_OK;
120193 }
120194
120195 /*
120196 ** This function is called to select the tokens (if any) that will be 
120197 ** deferred. The array aTC[] has already been populated when this is
120198 ** called.
120199 **
120200 ** This function is called once for each AND/NEAR cluster in the 
120201 ** expression. Each invocation determines which tokens to defer within
120202 ** the cluster with root node pRoot. See comments above the definition
120203 ** of struct Fts3TokenAndCost for more details.
120204 **
120205 ** If no error occurs, SQLCIPHER_OK is returned and sqlcipher3Fts3DeferToken()
120206 ** called on each token to defer. Otherwise, an SQLite error code is
120207 ** returned.
120208 */
120209 static int fts3EvalSelectDeferred(
120210   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120211   Fts3Expr *pRoot,                /* Consider tokens with this root node */
120212   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
120213   int nTC                         /* Number of entries in aTC[] */
120214 ){
120215   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120216   int nDocSize = 0;               /* Number of pages per doc loaded */
120217   int rc = SQLCIPHER_OK;             /* Return code */
120218   int ii;                         /* Iterator variable for various purposes */
120219   int nOvfl = 0;                  /* Total overflow pages used by doclists */
120220   int nToken = 0;                 /* Total number of tokens in cluster */
120221
120222   int nMinEst = 0;                /* The minimum count for any phrase so far. */
120223   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
120224
120225   /* Tokens are never deferred for FTS tables created using the content=xxx
120226   ** option. The reason being that it is not guaranteed that the content
120227   ** table actually contains the same data as the index. To prevent this from
120228   ** causing any problems, the deferred token optimization is completely
120229   ** disabled for content=xxx tables. */
120230   if( pTab->zContentTbl ){
120231     return SQLCIPHER_OK;
120232   }
120233
120234   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
120235   ** associated with the tokens spill onto overflow pages, or if there is
120236   ** only 1 token, exit early. No tokens to defer in this case. */
120237   for(ii=0; ii<nTC; ii++){
120238     if( aTC[ii].pRoot==pRoot ){
120239       nOvfl += aTC[ii].nOvfl;
120240       nToken++;
120241     }
120242   }
120243   if( nOvfl==0 || nToken<2 ) return SQLCIPHER_OK;
120244
120245   /* Obtain the average docsize (in pages). */
120246   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
120247   assert( rc!=SQLCIPHER_OK || nDocSize>0 );
120248
120249
120250   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
120251   ** of the number of overflow pages that will be loaded by the pager layer 
120252   ** to retrieve the entire doclist for the token from the full-text index.
120253   ** Load the doclists for tokens that are either:
120254   **
120255   **   a. The cheapest token in the entire query (i.e. the one visited by the
120256   **      first iteration of this loop), or
120257   **
120258   **   b. Part of a multi-token phrase.
120259   **
120260   ** After each token doclist is loaded, merge it with the others from the
120261   ** same phrase and count the number of documents that the merged doclist
120262   ** contains. Set variable "nMinEst" to the smallest number of documents in 
120263   ** any phrase doclist for which 1 or more token doclists have been loaded.
120264   ** Let nOther be the number of other phrases for which it is certain that
120265   ** one or more tokens will not be deferred.
120266   **
120267   ** Then, for each token, defer it if loading the doclist would result in
120268   ** loading N or more overflow pages into memory, where N is computed as:
120269   **
120270   **    (nMinEst + 4^nOther - 1) / (4^nOther)
120271   */
120272   for(ii=0; ii<nToken && rc==SQLCIPHER_OK; ii++){
120273     int iTC;                      /* Used to iterate through aTC[] array. */
120274     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
120275
120276     /* Set pTC to point to the cheapest remaining token. */
120277     for(iTC=0; iTC<nTC; iTC++){
120278       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
120279        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
120280       ){
120281         pTC = &aTC[iTC];
120282       }
120283     }
120284     assert( pTC );
120285
120286     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
120287       /* The number of overflow pages to load for this (and therefore all
120288       ** subsequent) tokens is greater than the estimated number of pages 
120289       ** that will be loaded if all subsequent tokens are deferred.
120290       */
120291       Fts3PhraseToken *pToken = pTC->pToken;
120292       rc = sqlcipher3Fts3DeferToken(pCsr, pToken, pTC->iCol);
120293       fts3SegReaderCursorFree(pToken->pSegcsr);
120294       pToken->pSegcsr = 0;
120295     }else{
120296       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
120297       ** for-loop. Except, limit the value to 2^24 to prevent it from 
120298       ** overflowing the 32-bit integer it is stored in. */
120299       if( ii<12 ) nLoad4 = nLoad4*4;
120300
120301       if( ii==0 || pTC->pPhrase->nToken>1 ){
120302         /* Either this is the cheapest token in the entire query, or it is
120303         ** part of a multi-token phrase. Either way, the entire doclist will
120304         ** (eventually) be loaded into memory. It may as well be now. */
120305         Fts3PhraseToken *pToken = pTC->pToken;
120306         int nList = 0;
120307         char *pList = 0;
120308         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
120309         assert( rc==SQLCIPHER_OK || pList==0 );
120310         if( rc==SQLCIPHER_OK ){
120311           int nCount;
120312           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
120313           nCount = fts3DoclistCountDocids(
120314               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
120315           );
120316           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
120317         }
120318       }
120319     }
120320     pTC->pToken = 0;
120321   }
120322
120323   return rc;
120324 }
120325
120326 /*
120327 ** This function is called from within the xFilter method. It initializes
120328 ** the full-text query currently stored in pCsr->pExpr. To iterate through
120329 ** the results of a query, the caller does:
120330 **
120331 **    fts3EvalStart(pCsr);
120332 **    while( 1 ){
120333 **      fts3EvalNext(pCsr);
120334 **      if( pCsr->bEof ) break;
120335 **      ... return row pCsr->iPrevId to the caller ...
120336 **    }
120337 */
120338 static int fts3EvalStart(Fts3Cursor *pCsr){
120339   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120340   int rc = SQLCIPHER_OK;
120341   int nToken = 0;
120342   int nOr = 0;
120343
120344   /* Allocate a MultiSegReader for each token in the expression. */
120345   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
120346
120347   /* Determine which, if any, tokens in the expression should be deferred. */
120348   if( rc==SQLCIPHER_OK && nToken>1 && pTab->bHasStat ){
120349     Fts3TokenAndCost *aTC;
120350     Fts3Expr **apOr;
120351     aTC = (Fts3TokenAndCost *)sqlcipher3_malloc(
120352         sizeof(Fts3TokenAndCost) * nToken
120353       + sizeof(Fts3Expr *) * nOr * 2
120354     );
120355     apOr = (Fts3Expr **)&aTC[nToken];
120356
120357     if( !aTC ){
120358       rc = SQLCIPHER_NOMEM;
120359     }else{
120360       int ii;
120361       Fts3TokenAndCost *pTC = aTC;
120362       Fts3Expr **ppOr = apOr;
120363
120364       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
120365       nToken = pTC-aTC;
120366       nOr = ppOr-apOr;
120367
120368       if( rc==SQLCIPHER_OK ){
120369         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
120370         for(ii=0; rc==SQLCIPHER_OK && ii<nOr; ii++){
120371           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
120372         }
120373       }
120374
120375       sqlcipher3_free(aTC);
120376     }
120377   }
120378
120379   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
120380   return rc;
120381 }
120382
120383 /*
120384 ** Invalidate the current position list for phrase pPhrase.
120385 */
120386 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
120387   if( pPhrase->doclist.bFreeList ){
120388     sqlcipher3_free(pPhrase->doclist.pList);
120389   }
120390   pPhrase->doclist.pList = 0;
120391   pPhrase->doclist.nList = 0;
120392   pPhrase->doclist.bFreeList = 0;
120393 }
120394
120395 /*
120396 ** This function is called to edit the position list associated with
120397 ** the phrase object passed as the fifth argument according to a NEAR
120398 ** condition. For example:
120399 **
120400 **     abc NEAR/5 "def ghi"
120401 **
120402 ** Parameter nNear is passed the NEAR distance of the expression (5 in
120403 ** the example above). When this function is called, *paPoslist points to
120404 ** the position list, and *pnToken is the number of phrase tokens in, the
120405 ** phrase on the other side of the NEAR operator to pPhrase. For example,
120406 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
120407 ** the position list associated with phrase "abc".
120408 **
120409 ** All positions in the pPhrase position list that are not sufficiently
120410 ** close to a position in the *paPoslist position list are removed. If this
120411 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
120412 **
120413 ** Before returning, *paPoslist is set to point to the position lsit 
120414 ** associated with pPhrase. And *pnToken is set to the number of tokens in
120415 ** pPhrase.
120416 */
120417 static int fts3EvalNearTrim(
120418   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
120419   char *aTmp,                     /* Temporary space to use */
120420   char **paPoslist,               /* IN/OUT: Position list */
120421   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
120422   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
120423 ){
120424   int nParam1 = nNear + pPhrase->nToken;
120425   int nParam2 = nNear + *pnToken;
120426   int nNew;
120427   char *p2; 
120428   char *pOut; 
120429   int res;
120430
120431   assert( pPhrase->doclist.pList );
120432
120433   p2 = pOut = pPhrase->doclist.pList;
120434   res = fts3PoslistNearMerge(
120435     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
120436   );
120437   if( res ){
120438     nNew = (pOut - pPhrase->doclist.pList) - 1;
120439     assert( pPhrase->doclist.pList[nNew]=='\0' );
120440     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
120441     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
120442     pPhrase->doclist.nList = nNew;
120443     *paPoslist = pPhrase->doclist.pList;
120444     *pnToken = pPhrase->nToken;
120445   }
120446
120447   return res;
120448 }
120449
120450 /*
120451 ** This function is a no-op if *pRc is other than SQLCIPHER_OK when it is called.
120452 ** Otherwise, it advances the expression passed as the second argument to
120453 ** point to the next matching row in the database. Expressions iterate through
120454 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
120455 ** or descending if it is non-zero.
120456 **
120457 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
120458 ** successful, the following variables in pExpr are set:
120459 **
120460 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
120461 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
120462 **
120463 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
120464 ** at EOF, then the following variables are populated with the position list
120465 ** for the phrase for the visited row:
120466 **
120467 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
120468 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
120469 **
120470 ** It says above that this function advances the expression to the next
120471 ** matching row. This is usually true, but there are the following exceptions:
120472 **
120473 **   1. Deferred tokens are not taken into account. If a phrase consists
120474 **      entirely of deferred tokens, it is assumed to match every row in
120475 **      the db. In this case the position-list is not populated at all. 
120476 **
120477 **      Or, if a phrase contains one or more deferred tokens and one or
120478 **      more non-deferred tokens, then the expression is advanced to the 
120479 **      next possible match, considering only non-deferred tokens. In other
120480 **      words, if the phrase is "A B C", and "B" is deferred, the expression
120481 **      is advanced to the next row that contains an instance of "A * C", 
120482 **      where "*" may match any single token. The position list in this case
120483 **      is populated as for "A * C" before returning.
120484 **
120485 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
120486 **      advanced to point to the next row that matches "x AND y".
120487 ** 
120488 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
120489 ** really a match, taking into account deferred tokens and NEAR operators.
120490 */
120491 static void fts3EvalNextRow(
120492   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120493   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
120494   int *pRc                        /* IN/OUT: Error code */
120495 ){
120496   if( *pRc==SQLCIPHER_OK ){
120497     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
120498     assert( pExpr->bEof==0 );
120499     pExpr->bStart = 1;
120500
120501     switch( pExpr->eType ){
120502       case FTSQUERY_NEAR:
120503       case FTSQUERY_AND: {
120504         Fts3Expr *pLeft = pExpr->pLeft;
120505         Fts3Expr *pRight = pExpr->pRight;
120506         assert( !pLeft->bDeferred || !pRight->bDeferred );
120507
120508         if( pLeft->bDeferred ){
120509           /* LHS is entirely deferred. So we assume it matches every row.
120510           ** Advance the RHS iterator to find the next row visited. */
120511           fts3EvalNextRow(pCsr, pRight, pRc);
120512           pExpr->iDocid = pRight->iDocid;
120513           pExpr->bEof = pRight->bEof;
120514         }else if( pRight->bDeferred ){
120515           /* RHS is entirely deferred. So we assume it matches every row.
120516           ** Advance the LHS iterator to find the next row visited. */
120517           fts3EvalNextRow(pCsr, pLeft, pRc);
120518           pExpr->iDocid = pLeft->iDocid;
120519           pExpr->bEof = pLeft->bEof;
120520         }else{
120521           /* Neither the RHS or LHS are deferred. */
120522           fts3EvalNextRow(pCsr, pLeft, pRc);
120523           fts3EvalNextRow(pCsr, pRight, pRc);
120524           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLCIPHER_OK ){
120525             sqlcipher3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120526             if( iDiff==0 ) break;
120527             if( iDiff<0 ){
120528               fts3EvalNextRow(pCsr, pLeft, pRc);
120529             }else{
120530               fts3EvalNextRow(pCsr, pRight, pRc);
120531             }
120532           }
120533           pExpr->iDocid = pLeft->iDocid;
120534           pExpr->bEof = (pLeft->bEof || pRight->bEof);
120535         }
120536         break;
120537       }
120538   
120539       case FTSQUERY_OR: {
120540         Fts3Expr *pLeft = pExpr->pLeft;
120541         Fts3Expr *pRight = pExpr->pRight;
120542         sqlcipher3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120543
120544         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
120545         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
120546
120547         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
120548           fts3EvalNextRow(pCsr, pLeft, pRc);
120549         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
120550           fts3EvalNextRow(pCsr, pRight, pRc);
120551         }else{
120552           fts3EvalNextRow(pCsr, pLeft, pRc);
120553           fts3EvalNextRow(pCsr, pRight, pRc);
120554         }
120555
120556         pExpr->bEof = (pLeft->bEof && pRight->bEof);
120557         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
120558         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
120559           pExpr->iDocid = pLeft->iDocid;
120560         }else{
120561           pExpr->iDocid = pRight->iDocid;
120562         }
120563
120564         break;
120565       }
120566
120567       case FTSQUERY_NOT: {
120568         Fts3Expr *pLeft = pExpr->pLeft;
120569         Fts3Expr *pRight = pExpr->pRight;
120570
120571         if( pRight->bStart==0 ){
120572           fts3EvalNextRow(pCsr, pRight, pRc);
120573           assert( *pRc!=SQLCIPHER_OK || pRight->bStart );
120574         }
120575
120576         fts3EvalNextRow(pCsr, pLeft, pRc);
120577         if( pLeft->bEof==0 ){
120578           while( !*pRc 
120579               && !pRight->bEof 
120580               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
120581           ){
120582             fts3EvalNextRow(pCsr, pRight, pRc);
120583           }
120584         }
120585         pExpr->iDocid = pLeft->iDocid;
120586         pExpr->bEof = pLeft->bEof;
120587         break;
120588       }
120589
120590       default: {
120591         Fts3Phrase *pPhrase = pExpr->pPhrase;
120592         fts3EvalInvalidatePoslist(pPhrase);
120593         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
120594         pExpr->iDocid = pPhrase->doclist.iDocid;
120595         break;
120596       }
120597     }
120598   }
120599 }
120600
120601 /*
120602 ** If *pRc is not SQLCIPHER_OK, or if pExpr is not the root node of a NEAR
120603 ** cluster, then this function returns 1 immediately.
120604 **
120605 ** Otherwise, it checks if the current row really does match the NEAR 
120606 ** expression, using the data currently stored in the position lists 
120607 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
120608 **
120609 ** If the current row is a match, the position list associated with each
120610 ** phrase in the NEAR expression is edited in place to contain only those
120611 ** phrase instances sufficiently close to their peers to satisfy all NEAR
120612 ** constraints. In this case it returns 1. If the NEAR expression does not 
120613 ** match the current row, 0 is returned. The position lists may or may not
120614 ** be edited if 0 is returned.
120615 */
120616 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
120617   int res = 1;
120618
120619   /* The following block runs if pExpr is the root of a NEAR query.
120620   ** For example, the query:
120621   **
120622   **         "w" NEAR "x" NEAR "y" NEAR "z"
120623   **
120624   ** which is represented in tree form as:
120625   **
120626   **                               |
120627   **                          +--NEAR--+      <-- root of NEAR query
120628   **                          |        |
120629   **                     +--NEAR--+   "z"
120630   **                     |        |
120631   **                +--NEAR--+   "y"
120632   **                |        |
120633   **               "w"      "x"
120634   **
120635   ** The right-hand child of a NEAR node is always a phrase. The 
120636   ** left-hand child may be either a phrase or a NEAR node. There are
120637   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
120638   */
120639   if( *pRc==SQLCIPHER_OK 
120640    && pExpr->eType==FTSQUERY_NEAR 
120641    && pExpr->bEof==0
120642    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
120643   ){
120644     Fts3Expr *p; 
120645     int nTmp = 0;                 /* Bytes of temp space */
120646     char *aTmp;                   /* Temp space for PoslistNearMerge() */
120647
120648     /* Allocate temporary working space. */
120649     for(p=pExpr; p->pLeft; p=p->pLeft){
120650       nTmp += p->pRight->pPhrase->doclist.nList;
120651     }
120652     nTmp += p->pPhrase->doclist.nList;
120653     aTmp = sqlcipher3_malloc(nTmp*2);
120654     if( !aTmp ){
120655       *pRc = SQLCIPHER_NOMEM;
120656       res = 0;
120657     }else{
120658       char *aPoslist = p->pPhrase->doclist.pList;
120659       int nToken = p->pPhrase->nToken;
120660
120661       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
120662         Fts3Phrase *pPhrase = p->pRight->pPhrase;
120663         int nNear = p->nNear;
120664         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
120665       }
120666   
120667       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
120668       nToken = pExpr->pRight->pPhrase->nToken;
120669       for(p=pExpr->pLeft; p && res; p=p->pLeft){
120670         int nNear;
120671         Fts3Phrase *pPhrase;
120672         assert( p->pParent && p->pParent->pLeft==p );
120673         nNear = p->pParent->nNear;
120674         pPhrase = (
120675             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
120676         );
120677         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
120678       }
120679     }
120680
120681     sqlcipher3_free(aTmp);
120682   }
120683
120684   return res;
120685 }
120686
120687 /*
120688 ** This function is a helper function for fts3EvalTestDeferredAndNear().
120689 ** Assuming no error occurs or has occurred, It returns non-zero if the
120690 ** expression passed as the second argument matches the row that pCsr 
120691 ** currently points to, or zero if it does not.
120692 **
120693 ** If *pRc is not SQLCIPHER_OK when this function is called, it is a no-op.
120694 ** If an error occurs during execution of this function, *pRc is set to 
120695 ** the appropriate SQLite error code. In this case the returned value is 
120696 ** undefined.
120697 */
120698 static int fts3EvalTestExpr(
120699   Fts3Cursor *pCsr,               /* FTS cursor handle */
120700   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
120701   int *pRc                        /* IN/OUT: Error code */
120702 ){
120703   int bHit = 1;                   /* Return value */
120704   if( *pRc==SQLCIPHER_OK ){
120705     switch( pExpr->eType ){
120706       case FTSQUERY_NEAR:
120707       case FTSQUERY_AND:
120708         bHit = (
120709             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
120710          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
120711          && fts3EvalNearTest(pExpr, pRc)
120712         );
120713
120714         /* If the NEAR expression does not match any rows, zero the doclist for 
120715         ** all phrases involved in the NEAR. This is because the snippet(),
120716         ** offsets() and matchinfo() functions are not supposed to recognize 
120717         ** any instances of phrases that are part of unmatched NEAR queries. 
120718         ** For example if this expression:
120719         **
120720         **    ... MATCH 'a OR (b NEAR c)'
120721         **
120722         ** is matched against a row containing:
120723         **
120724         **        'a b d e'
120725         **
120726         ** then any snippet() should ony highlight the "a" term, not the "b"
120727         ** (as "b" is part of a non-matching NEAR clause).
120728         */
120729         if( bHit==0 
120730          && pExpr->eType==FTSQUERY_NEAR 
120731          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
120732         ){
120733           Fts3Expr *p;
120734           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
120735             if( p->pRight->iDocid==pCsr->iPrevId ){
120736               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
120737             }
120738           }
120739           if( p->iDocid==pCsr->iPrevId ){
120740             fts3EvalInvalidatePoslist(p->pPhrase);
120741           }
120742         }
120743
120744         break;
120745
120746       case FTSQUERY_OR: {
120747         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
120748         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
120749         bHit = bHit1 || bHit2;
120750         break;
120751       }
120752
120753       case FTSQUERY_NOT:
120754         bHit = (
120755             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
120756          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
120757         );
120758         break;
120759
120760       default: {
120761         if( pCsr->pDeferred 
120762          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
120763         ){
120764           Fts3Phrase *pPhrase = pExpr->pPhrase;
120765           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
120766           if( pExpr->bDeferred ){
120767             fts3EvalInvalidatePoslist(pPhrase);
120768           }
120769           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
120770           bHit = (pPhrase->doclist.pList!=0);
120771           pExpr->iDocid = pCsr->iPrevId;
120772         }else{
120773           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
120774         }
120775         break;
120776       }
120777     }
120778   }
120779   return bHit;
120780 }
120781
120782 /*
120783 ** This function is called as the second part of each xNext operation when
120784 ** iterating through the results of a full-text query. At this point the
120785 ** cursor points to a row that matches the query expression, with the
120786 ** following caveats:
120787 **
120788 **   * Up until this point, "NEAR" operators in the expression have been
120789 **     treated as "AND".
120790 **
120791 **   * Deferred tokens have not yet been considered.
120792 **
120793 ** If *pRc is not SQLCIPHER_OK when this function is called, it immediately
120794 ** returns 0. Otherwise, it tests whether or not after considering NEAR
120795 ** operators and deferred tokens the current row is still a match for the
120796 ** expression. It returns 1 if both of the following are true:
120797 **
120798 **   1. *pRc is SQLCIPHER_OK when this function returns, and
120799 **
120800 **   2. After scanning the current FTS table row for the deferred tokens,
120801 **      it is determined that the row does *not* match the query.
120802 **
120803 ** Or, if no error occurs and it seems the current row does match the FTS
120804 ** query, return 0.
120805 */
120806 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
120807   int rc = *pRc;
120808   int bMiss = 0;
120809   if( rc==SQLCIPHER_OK ){
120810
120811     /* If there are one or more deferred tokens, load the current row into
120812     ** memory and scan it to determine the position list for each deferred
120813     ** token. Then, see if this row is really a match, considering deferred
120814     ** tokens and NEAR operators (neither of which were taken into account
120815     ** earlier, by fts3EvalNextRow()). 
120816     */
120817     if( pCsr->pDeferred ){
120818       rc = fts3CursorSeek(0, pCsr);
120819       if( rc==SQLCIPHER_OK ){
120820         rc = sqlcipher3Fts3CacheDeferredDoclists(pCsr);
120821       }
120822     }
120823     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
120824
120825     /* Free the position-lists accumulated for each deferred token above. */
120826     sqlcipher3Fts3FreeDeferredDoclists(pCsr);
120827     *pRc = rc;
120828   }
120829   return (rc==SQLCIPHER_OK && bMiss);
120830 }
120831
120832 /*
120833 ** Advance to the next document that matches the FTS expression in
120834 ** Fts3Cursor.pExpr.
120835 */
120836 static int fts3EvalNext(Fts3Cursor *pCsr){
120837   int rc = SQLCIPHER_OK;             /* Return Code */
120838   Fts3Expr *pExpr = pCsr->pExpr;
120839   assert( pCsr->isEof==0 );
120840   if( pExpr==0 ){
120841     pCsr->isEof = 1;
120842   }else{
120843     do {
120844       if( pCsr->isRequireSeek==0 ){
120845         sqlcipher3_reset(pCsr->pStmt);
120846       }
120847       assert( sqlcipher3_data_count(pCsr->pStmt)==0 );
120848       fts3EvalNextRow(pCsr, pExpr, &rc);
120849       pCsr->isEof = pExpr->bEof;
120850       pCsr->isRequireSeek = 1;
120851       pCsr->isMatchinfoNeeded = 1;
120852       pCsr->iPrevId = pExpr->iDocid;
120853     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
120854   }
120855   return rc;
120856 }
120857
120858 /*
120859 ** Restart interation for expression pExpr so that the next call to
120860 ** fts3EvalNext() visits the first row. Do not allow incremental 
120861 ** loading or merging of phrase doclists for this iteration.
120862 **
120863 ** If *pRc is other than SQLCIPHER_OK when this function is called, it is
120864 ** a no-op. If an error occurs within this function, *pRc is set to an
120865 ** SQLite error code before returning.
120866 */
120867 static void fts3EvalRestart(
120868   Fts3Cursor *pCsr,
120869   Fts3Expr *pExpr,
120870   int *pRc
120871 ){
120872   if( pExpr && *pRc==SQLCIPHER_OK ){
120873     Fts3Phrase *pPhrase = pExpr->pPhrase;
120874
120875     if( pPhrase ){
120876       fts3EvalInvalidatePoslist(pPhrase);
120877       if( pPhrase->bIncr ){
120878         assert( pPhrase->nToken==1 );
120879         assert( pPhrase->aToken[0].pSegcsr );
120880         sqlcipher3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
120881         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
120882       }
120883
120884       pPhrase->doclist.pNextDocid = 0;
120885       pPhrase->doclist.iDocid = 0;
120886     }
120887
120888     pExpr->iDocid = 0;
120889     pExpr->bEof = 0;
120890     pExpr->bStart = 0;
120891
120892     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
120893     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
120894   }
120895 }
120896
120897 /*
120898 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
120899 ** expression rooted at pExpr, the cursor iterates through all rows matched
120900 ** by pExpr, calling this function for each row. This function increments
120901 ** the values in Fts3Expr.aMI[] according to the position-list currently
120902 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
120903 ** expression nodes.
120904 */
120905 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
120906   if( pExpr ){
120907     Fts3Phrase *pPhrase = pExpr->pPhrase;
120908     if( pPhrase && pPhrase->doclist.pList ){
120909       int iCol = 0;
120910       char *p = pPhrase->doclist.pList;
120911
120912       assert( *p );
120913       while( 1 ){
120914         u8 c = 0;
120915         int iCnt = 0;
120916         while( 0xFE & (*p | c) ){
120917           if( (c&0x80)==0 ) iCnt++;
120918           c = *p++ & 0x80;
120919         }
120920
120921         /* aMI[iCol*3 + 1] = Number of occurrences
120922         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
120923         */
120924         pExpr->aMI[iCol*3 + 1] += iCnt;
120925         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
120926         if( *p==0x00 ) break;
120927         p++;
120928         p += sqlcipher3Fts3GetVarint32(p, &iCol);
120929       }
120930     }
120931
120932     fts3EvalUpdateCounts(pExpr->pLeft);
120933     fts3EvalUpdateCounts(pExpr->pRight);
120934   }
120935 }
120936
120937 /*
120938 ** Expression pExpr must be of type FTSQUERY_PHRASE.
120939 **
120940 ** If it is not already allocated and populated, this function allocates and
120941 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
120942 ** of a NEAR expression, then it also allocates and populates the same array
120943 ** for all other phrases that are part of the NEAR expression.
120944 **
120945 ** SQLCIPHER_OK is returned if the aMI[] array is successfully allocated and
120946 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
120947 */
120948 static int fts3EvalGatherStats(
120949   Fts3Cursor *pCsr,               /* Cursor object */
120950   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
120951 ){
120952   int rc = SQLCIPHER_OK;             /* Return code */
120953
120954   assert( pExpr->eType==FTSQUERY_PHRASE );
120955   if( pExpr->aMI==0 ){
120956     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120957     Fts3Expr *pRoot;                /* Root of NEAR expression */
120958     Fts3Expr *p;                    /* Iterator used for several purposes */
120959
120960     sqlcipher3_int64 iPrevId = pCsr->iPrevId;
120961     sqlcipher3_int64 iDocid;
120962     u8 bEof;
120963
120964     /* Find the root of the NEAR expression */
120965     pRoot = pExpr;
120966     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
120967       pRoot = pRoot->pParent;
120968     }
120969     iDocid = pRoot->iDocid;
120970     bEof = pRoot->bEof;
120971     assert( pRoot->bStart );
120972
120973     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
120974     for(p=pRoot; p; p=p->pLeft){
120975       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
120976       assert( pE->aMI==0 );
120977       pE->aMI = (u32 *)sqlcipher3_malloc(pTab->nColumn * 3 * sizeof(u32));
120978       if( !pE->aMI ) return SQLCIPHER_NOMEM;
120979       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
120980     }
120981
120982     fts3EvalRestart(pCsr, pRoot, &rc);
120983
120984     while( pCsr->isEof==0 && rc==SQLCIPHER_OK ){
120985
120986       do {
120987         /* Ensure the %_content statement is reset. */
120988         if( pCsr->isRequireSeek==0 ) sqlcipher3_reset(pCsr->pStmt);
120989         assert( sqlcipher3_data_count(pCsr->pStmt)==0 );
120990
120991         /* Advance to the next document */
120992         fts3EvalNextRow(pCsr, pRoot, &rc);
120993         pCsr->isEof = pRoot->bEof;
120994         pCsr->isRequireSeek = 1;
120995         pCsr->isMatchinfoNeeded = 1;
120996         pCsr->iPrevId = pRoot->iDocid;
120997       }while( pCsr->isEof==0 
120998            && pRoot->eType==FTSQUERY_NEAR 
120999            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
121000       );
121001
121002       if( rc==SQLCIPHER_OK && pCsr->isEof==0 ){
121003         fts3EvalUpdateCounts(pRoot);
121004       }
121005     }
121006
121007     pCsr->isEof = 0;
121008     pCsr->iPrevId = iPrevId;
121009
121010     if( bEof ){
121011       pRoot->bEof = bEof;
121012     }else{
121013       /* Caution: pRoot may iterate through docids in ascending or descending
121014       ** order. For this reason, even though it seems more defensive, the 
121015       ** do loop can not be written:
121016       **
121017       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLCIPHER_OK );
121018       */
121019       fts3EvalRestart(pCsr, pRoot, &rc);
121020       do {
121021         fts3EvalNextRow(pCsr, pRoot, &rc);
121022         assert( pRoot->bEof==0 );
121023       }while( pRoot->iDocid!=iDocid && rc==SQLCIPHER_OK );
121024       fts3EvalTestDeferredAndNear(pCsr, &rc);
121025     }
121026   }
121027   return rc;
121028 }
121029
121030 /*
121031 ** This function is used by the matchinfo() module to query a phrase 
121032 ** expression node for the following information:
121033 **
121034 **   1. The total number of occurrences of the phrase in each column of 
121035 **      the FTS table (considering all rows), and
121036 **
121037 **   2. For each column, the number of rows in the table for which the
121038 **      column contains at least one instance of the phrase.
121039 **
121040 ** If no error occurs, SQLCIPHER_OK is returned and the values for each column
121041 ** written into the array aiOut as follows:
121042 **
121043 **   aiOut[iCol*3 + 1] = Number of occurrences
121044 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
121045 **
121046 ** Caveats:
121047 **
121048 **   * If a phrase consists entirely of deferred tokens, then all output 
121049 **     values are set to the number of documents in the table. In other
121050 **     words we assume that very common tokens occur exactly once in each 
121051 **     column of each row of the table.
121052 **
121053 **   * If a phrase contains some deferred tokens (and some non-deferred 
121054 **     tokens), count the potential occurrence identified by considering
121055 **     the non-deferred tokens instead of actual phrase occurrences.
121056 **
121057 **   * If the phrase is part of a NEAR expression, then only phrase instances
121058 **     that meet the NEAR constraint are included in the counts.
121059 */
121060 SQLCIPHER_PRIVATE int sqlcipher3Fts3EvalPhraseStats(
121061   Fts3Cursor *pCsr,               /* FTS cursor handle */
121062   Fts3Expr *pExpr,                /* Phrase expression */
121063   u32 *aiOut                      /* Array to write results into (see above) */
121064 ){
121065   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121066   int rc = SQLCIPHER_OK;
121067   int iCol;
121068
121069   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
121070     assert( pCsr->nDoc>0 );
121071     for(iCol=0; iCol<pTab->nColumn; iCol++){
121072       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
121073       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
121074     }
121075   }else{
121076     rc = fts3EvalGatherStats(pCsr, pExpr);
121077     if( rc==SQLCIPHER_OK ){
121078       assert( pExpr->aMI );
121079       for(iCol=0; iCol<pTab->nColumn; iCol++){
121080         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
121081         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
121082       }
121083     }
121084   }
121085
121086   return rc;
121087 }
121088
121089 /*
121090 ** The expression pExpr passed as the second argument to this function
121091 ** must be of type FTSQUERY_PHRASE. 
121092 **
121093 ** The returned value is either NULL or a pointer to a buffer containing
121094 ** a position-list indicating the occurrences of the phrase in column iCol
121095 ** of the current row. 
121096 **
121097 ** More specifically, the returned buffer contains 1 varint for each 
121098 ** occurence of the phrase in the column, stored using the normal (delta+2) 
121099 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
121100 ** if the requested column contains "a b X c d X X" and the position-list
121101 ** for 'X' is requested, the buffer returned may contain:
121102 **
121103 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
121104 **
121105 ** This function works regardless of whether or not the phrase is deferred,
121106 ** incremental, or neither.
121107 */
121108 SQLCIPHER_PRIVATE char *sqlcipher3Fts3EvalPhrasePoslist(
121109   Fts3Cursor *pCsr,               /* FTS3 cursor object */
121110   Fts3Expr *pExpr,                /* Phrase to return doclist for */
121111   int iCol                        /* Column to return position list for */
121112 ){
121113   Fts3Phrase *pPhrase = pExpr->pPhrase;
121114   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121115   char *pIter = pPhrase->doclist.pList;
121116   int iThis;
121117
121118   assert( iCol>=0 && iCol<pTab->nColumn );
121119   if( !pIter 
121120    || pExpr->bEof 
121121    || pExpr->iDocid!=pCsr->iPrevId
121122    || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) 
121123   ){
121124     return 0;
121125   }
121126
121127   assert( pPhrase->doclist.nList>0 );
121128   if( *pIter==0x01 ){
121129     pIter++;
121130     pIter += sqlcipher3Fts3GetVarint32(pIter, &iThis);
121131   }else{
121132     iThis = 0;
121133   }
121134   while( iThis<iCol ){
121135     fts3ColumnlistCopy(0, &pIter);
121136     if( *pIter==0x00 ) return 0;
121137     pIter++;
121138     pIter += sqlcipher3Fts3GetVarint32(pIter, &iThis);
121139   }
121140
121141   return ((iCol==iThis)?pIter:0);
121142 }
121143
121144 /*
121145 ** Free all components of the Fts3Phrase structure that were allocated by
121146 ** the eval module. Specifically, this means to free:
121147 **
121148 **   * the contents of pPhrase->doclist, and
121149 **   * any Fts3MultiSegReader objects held by phrase tokens.
121150 */
121151 SQLCIPHER_PRIVATE void sqlcipher3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
121152   if( pPhrase ){
121153     int i;
121154     sqlcipher3_free(pPhrase->doclist.aAll);
121155     fts3EvalInvalidatePoslist(pPhrase);
121156     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
121157     for(i=0; i<pPhrase->nToken; i++){
121158       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
121159       pPhrase->aToken[i].pSegcsr = 0;
121160     }
121161   }
121162 }
121163
121164 /*
121165 ** Return SQLCIPHER_CORRUPT_VTAB.
121166 */
121167 #ifdef SQLCIPHER_DEBUG
121168 SQLCIPHER_PRIVATE int sqlcipher3Fts3Corrupt(){
121169   return SQLCIPHER_CORRUPT_VTAB;
121170 }
121171 #endif
121172
121173 #if !SQLCIPHER_CORE
121174 /*
121175 ** Initialize API pointer table, if required.
121176 */
121177 SQLCIPHER_API int sqlcipher3_extension_init(
121178   sqlcipher3 *db, 
121179   char **pzErrMsg,
121180   const sqlcipher3_api_routines *pApi
121181 ){
121182   SQLCIPHER_EXTENSION_INIT2(pApi)
121183   return sqlcipher3Fts3Init(db);
121184 }
121185 #endif
121186
121187 #endif
121188
121189 /************** End of fts3.c ************************************************/
121190 /************** Begin file fts3_aux.c ****************************************/
121191 /*
121192 ** 2011 Jan 27
121193 **
121194 ** The author disclaims copyright to this source code.  In place of
121195 ** a legal notice, here is a blessing:
121196 **
121197 **    May you do good and not evil.
121198 **    May you find forgiveness for yourself and forgive others.
121199 **    May you share freely, never taking more than you give.
121200 **
121201 ******************************************************************************
121202 **
121203 */
121204 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
121205
121206 /* #include <string.h> */
121207 /* #include <assert.h> */
121208
121209 typedef struct Fts3auxTable Fts3auxTable;
121210 typedef struct Fts3auxCursor Fts3auxCursor;
121211
121212 struct Fts3auxTable {
121213   sqlcipher3_vtab base;              /* Base class used by SQLite core */
121214   Fts3Table *pFts3Tab;
121215 };
121216
121217 struct Fts3auxCursor {
121218   sqlcipher3_vtab_cursor base;       /* Base class used by SQLite core */
121219   Fts3MultiSegReader csr;        /* Must be right after "base" */
121220   Fts3SegFilter filter;
121221   char *zStop;
121222   int nStop;                      /* Byte-length of string zStop */
121223   int isEof;                      /* True if cursor is at EOF */
121224   sqlcipher3_int64 iRowid;           /* Current rowid */
121225
121226   int iCol;                       /* Current value of 'col' column */
121227   int nStat;                      /* Size of aStat[] array */
121228   struct Fts3auxColstats {
121229     sqlcipher3_int64 nDoc;           /* 'documents' values for current csr row */
121230     sqlcipher3_int64 nOcc;           /* 'occurrences' values for current csr row */
121231   } *aStat;
121232 };
121233
121234 /*
121235 ** Schema of the terms table.
121236 */
121237 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
121238
121239 /*
121240 ** This function does all the work for both the xConnect and xCreate methods.
121241 ** These tables have no persistent representation of their own, so xConnect
121242 ** and xCreate are identical operations.
121243 */
121244 static int fts3auxConnectMethod(
121245   sqlcipher3 *db,                    /* Database connection */
121246   void *pUnused,                  /* Unused */
121247   int argc,                       /* Number of elements in argv array */
121248   const char * const *argv,       /* xCreate/xConnect argument array */
121249   sqlcipher3_vtab **ppVtab,          /* OUT: New sqlcipher3_vtab object */
121250   char **pzErr                    /* OUT: sqlcipher3_malloc'd error message */
121251 ){
121252   char const *zDb;                /* Name of database (e.g. "main") */
121253   char const *zFts3;              /* Name of fts3 table */
121254   int nDb;                        /* Result of strlen(zDb) */
121255   int nFts3;                      /* Result of strlen(zFts3) */
121256   int nByte;                      /* Bytes of space to allocate here */
121257   int rc;                         /* value returned by declare_vtab() */
121258   Fts3auxTable *p;                /* Virtual table object to return */
121259
121260   UNUSED_PARAMETER(pUnused);
121261
121262   /* The user should specify a single argument - the name of an fts3 table. */
121263   if( argc!=4 ){
121264     *pzErr = sqlcipher3_mprintf(
121265         "wrong number of arguments to fts4aux constructor"
121266     );
121267     return SQLCIPHER_ERROR;
121268   }
121269
121270   zDb = argv[1]; 
121271   nDb = strlen(zDb);
121272   zFts3 = argv[3];
121273   nFts3 = strlen(zFts3);
121274
121275   rc = sqlcipher3_declare_vtab(db, FTS3_TERMS_SCHEMA);
121276   if( rc!=SQLCIPHER_OK ) return rc;
121277
121278   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
121279   p = (Fts3auxTable *)sqlcipher3_malloc(nByte);
121280   if( !p ) return SQLCIPHER_NOMEM;
121281   memset(p, 0, nByte);
121282
121283   p->pFts3Tab = (Fts3Table *)&p[1];
121284   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
121285   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
121286   p->pFts3Tab->db = db;
121287   p->pFts3Tab->nIndex = 1;
121288
121289   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
121290   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
121291   sqlcipher3Fts3Dequote((char *)p->pFts3Tab->zName);
121292
121293   *ppVtab = (sqlcipher3_vtab *)p;
121294   return SQLCIPHER_OK;
121295 }
121296
121297 /*
121298 ** This function does the work for both the xDisconnect and xDestroy methods.
121299 ** These tables have no persistent representation of their own, so xDisconnect
121300 ** and xDestroy are identical operations.
121301 */
121302 static int fts3auxDisconnectMethod(sqlcipher3_vtab *pVtab){
121303   Fts3auxTable *p = (Fts3auxTable *)pVtab;
121304   Fts3Table *pFts3 = p->pFts3Tab;
121305   int i;
121306
121307   /* Free any prepared statements held */
121308   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
121309     sqlcipher3_finalize(pFts3->aStmt[i]);
121310   }
121311   sqlcipher3_free(pFts3->zSegmentsTbl);
121312   sqlcipher3_free(p);
121313   return SQLCIPHER_OK;
121314 }
121315
121316 #define FTS4AUX_EQ_CONSTRAINT 1
121317 #define FTS4AUX_GE_CONSTRAINT 2
121318 #define FTS4AUX_LE_CONSTRAINT 4
121319
121320 /*
121321 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
121322 */
121323 static int fts3auxBestIndexMethod(
121324   sqlcipher3_vtab *pVTab, 
121325   sqlcipher3_index_info *pInfo
121326 ){
121327   int i;
121328   int iEq = -1;
121329   int iGe = -1;
121330   int iLe = -1;
121331
121332   UNUSED_PARAMETER(pVTab);
121333
121334   /* This vtab delivers always results in "ORDER BY term ASC" order. */
121335   if( pInfo->nOrderBy==1 
121336    && pInfo->aOrderBy[0].iColumn==0 
121337    && pInfo->aOrderBy[0].desc==0
121338   ){
121339     pInfo->orderByConsumed = 1;
121340   }
121341
121342   /* Search for equality and range constraints on the "term" column. */
121343   for(i=0; i<pInfo->nConstraint; i++){
121344     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
121345       int op = pInfo->aConstraint[i].op;
121346       if( op==SQLCIPHER_INDEX_CONSTRAINT_EQ ) iEq = i;
121347       if( op==SQLCIPHER_INDEX_CONSTRAINT_LT ) iLe = i;
121348       if( op==SQLCIPHER_INDEX_CONSTRAINT_LE ) iLe = i;
121349       if( op==SQLCIPHER_INDEX_CONSTRAINT_GT ) iGe = i;
121350       if( op==SQLCIPHER_INDEX_CONSTRAINT_GE ) iGe = i;
121351     }
121352   }
121353
121354   if( iEq>=0 ){
121355     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
121356     pInfo->aConstraintUsage[iEq].argvIndex = 1;
121357     pInfo->estimatedCost = 5;
121358   }else{
121359     pInfo->idxNum = 0;
121360     pInfo->estimatedCost = 20000;
121361     if( iGe>=0 ){
121362       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
121363       pInfo->aConstraintUsage[iGe].argvIndex = 1;
121364       pInfo->estimatedCost /= 2;
121365     }
121366     if( iLe>=0 ){
121367       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
121368       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
121369       pInfo->estimatedCost /= 2;
121370     }
121371   }
121372
121373   return SQLCIPHER_OK;
121374 }
121375
121376 /*
121377 ** xOpen - Open a cursor.
121378 */
121379 static int fts3auxOpenMethod(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCsr){
121380   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
121381
121382   UNUSED_PARAMETER(pVTab);
121383
121384   pCsr = (Fts3auxCursor *)sqlcipher3_malloc(sizeof(Fts3auxCursor));
121385   if( !pCsr ) return SQLCIPHER_NOMEM;
121386   memset(pCsr, 0, sizeof(Fts3auxCursor));
121387
121388   *ppCsr = (sqlcipher3_vtab_cursor *)pCsr;
121389   return SQLCIPHER_OK;
121390 }
121391
121392 /*
121393 ** xClose - Close a cursor.
121394 */
121395 static int fts3auxCloseMethod(sqlcipher3_vtab_cursor *pCursor){
121396   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121397   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121398
121399   sqlcipher3Fts3SegmentsClose(pFts3);
121400   sqlcipher3Fts3SegReaderFinish(&pCsr->csr);
121401   sqlcipher3_free((void *)pCsr->filter.zTerm);
121402   sqlcipher3_free(pCsr->zStop);
121403   sqlcipher3_free(pCsr->aStat);
121404   sqlcipher3_free(pCsr);
121405   return SQLCIPHER_OK;
121406 }
121407
121408 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
121409   if( nSize>pCsr->nStat ){
121410     struct Fts3auxColstats *aNew;
121411     aNew = (struct Fts3auxColstats *)sqlcipher3_realloc(pCsr->aStat, 
121412         sizeof(struct Fts3auxColstats) * nSize
121413     );
121414     if( aNew==0 ) return SQLCIPHER_NOMEM;
121415     memset(&aNew[pCsr->nStat], 0, 
121416         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
121417     );
121418     pCsr->aStat = aNew;
121419     pCsr->nStat = nSize;
121420   }
121421   return SQLCIPHER_OK;
121422 }
121423
121424 /*
121425 ** xNext - Advance the cursor to the next row, if any.
121426 */
121427 static int fts3auxNextMethod(sqlcipher3_vtab_cursor *pCursor){
121428   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121429   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121430   int rc;
121431
121432   /* Increment our pretend rowid value. */
121433   pCsr->iRowid++;
121434
121435   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
121436     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLCIPHER_OK;
121437   }
121438
121439   rc = sqlcipher3Fts3SegReaderStep(pFts3, &pCsr->csr);
121440   if( rc==SQLCIPHER_ROW ){
121441     int i = 0;
121442     int nDoclist = pCsr->csr.nDoclist;
121443     char *aDoclist = pCsr->csr.aDoclist;
121444     int iCol;
121445
121446     int eState = 0;
121447
121448     if( pCsr->zStop ){
121449       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
121450       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
121451       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
121452         pCsr->isEof = 1;
121453         return SQLCIPHER_OK;
121454       }
121455     }
121456
121457     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLCIPHER_NOMEM;
121458     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
121459     iCol = 0;
121460
121461     while( i<nDoclist ){
121462       sqlcipher3_int64 v = 0;
121463
121464       i += sqlcipher3Fts3GetVarint(&aDoclist[i], &v);
121465       switch( eState ){
121466         /* State 0. In this state the integer just read was a docid. */
121467         case 0:
121468           pCsr->aStat[0].nDoc++;
121469           eState = 1;
121470           iCol = 0;
121471           break;
121472
121473         /* State 1. In this state we are expecting either a 1, indicating
121474         ** that the following integer will be a column number, or the
121475         ** start of a position list for column 0.  
121476         ** 
121477         ** The only difference between state 1 and state 2 is that if the
121478         ** integer encountered in state 1 is not 0 or 1, then we need to
121479         ** increment the column 0 "nDoc" count for this term.
121480         */
121481         case 1:
121482           assert( iCol==0 );
121483           if( v>1 ){
121484             pCsr->aStat[1].nDoc++;
121485           }
121486           eState = 2;
121487           /* fall through */
121488
121489         case 2:
121490           if( v==0 ){       /* 0x00. Next integer will be a docid. */
121491             eState = 0;
121492           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
121493             eState = 3;
121494           }else{            /* 2 or greater. A position. */
121495             pCsr->aStat[iCol+1].nOcc++;
121496             pCsr->aStat[0].nOcc++;
121497           }
121498           break;
121499
121500         /* State 3. The integer just read is a column number. */
121501         default: assert( eState==3 );
121502           iCol = (int)v;
121503           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLCIPHER_NOMEM;
121504           pCsr->aStat[iCol+1].nDoc++;
121505           eState = 2;
121506           break;
121507       }
121508     }
121509
121510     pCsr->iCol = 0;
121511     rc = SQLCIPHER_OK;
121512   }else{
121513     pCsr->isEof = 1;
121514   }
121515   return rc;
121516 }
121517
121518 /*
121519 ** xFilter - Initialize a cursor to point at the start of its data.
121520 */
121521 static int fts3auxFilterMethod(
121522   sqlcipher3_vtab_cursor *pCursor,   /* The cursor used for this query */
121523   int idxNum,                     /* Strategy index */
121524   const char *idxStr,             /* Unused */
121525   int nVal,                       /* Number of elements in apVal */
121526   sqlcipher3_value **apVal           /* Arguments for the indexing scheme */
121527 ){
121528   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121529   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
121530   int rc;
121531   int isScan;
121532
121533   UNUSED_PARAMETER(nVal);
121534   UNUSED_PARAMETER(idxStr);
121535
121536   assert( idxStr==0 );
121537   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
121538        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
121539        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
121540   );
121541   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
121542
121543   /* In case this cursor is being reused, close and zero it. */
121544   testcase(pCsr->filter.zTerm);
121545   sqlcipher3Fts3SegReaderFinish(&pCsr->csr);
121546   sqlcipher3_free((void *)pCsr->filter.zTerm);
121547   sqlcipher3_free(pCsr->aStat);
121548   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
121549
121550   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
121551   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
121552
121553   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
121554     const unsigned char *zStr = sqlcipher3_value_text(apVal[0]);
121555     if( zStr ){
121556       pCsr->filter.zTerm = sqlcipher3_mprintf("%s", zStr);
121557       pCsr->filter.nTerm = sqlcipher3_value_bytes(apVal[0]);
121558       if( pCsr->filter.zTerm==0 ) return SQLCIPHER_NOMEM;
121559     }
121560   }
121561   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
121562     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
121563     pCsr->zStop = sqlcipher3_mprintf("%s", sqlcipher3_value_text(apVal[iIdx]));
121564     pCsr->nStop = sqlcipher3_value_bytes(apVal[iIdx]);
121565     if( pCsr->zStop==0 ) return SQLCIPHER_NOMEM;
121566   }
121567
121568   rc = sqlcipher3Fts3SegReaderCursor(pFts3, 0, FTS3_SEGCURSOR_ALL,
121569       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
121570   );
121571   if( rc==SQLCIPHER_OK ){
121572     rc = sqlcipher3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
121573   }
121574
121575   if( rc==SQLCIPHER_OK ) rc = fts3auxNextMethod(pCursor);
121576   return rc;
121577 }
121578
121579 /*
121580 ** xEof - Return true if the cursor is at EOF, or false otherwise.
121581 */
121582 static int fts3auxEofMethod(sqlcipher3_vtab_cursor *pCursor){
121583   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121584   return pCsr->isEof;
121585 }
121586
121587 /*
121588 ** xColumn - Return a column value.
121589 */
121590 static int fts3auxColumnMethod(
121591   sqlcipher3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121592   sqlcipher3_context *pContext,      /* Context for sqlcipher3_result_xxx() calls */
121593   int iCol                        /* Index of column to read value from */
121594 ){
121595   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
121596
121597   assert( p->isEof==0 );
121598   if( iCol==0 ){        /* Column "term" */
121599     sqlcipher3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLCIPHER_TRANSIENT);
121600   }else if( iCol==1 ){  /* Column "col" */
121601     if( p->iCol ){
121602       sqlcipher3_result_int(pContext, p->iCol-1);
121603     }else{
121604       sqlcipher3_result_text(pContext, "*", -1, SQLCIPHER_STATIC);
121605     }
121606   }else if( iCol==2 ){  /* Column "documents" */
121607     sqlcipher3_result_int64(pContext, p->aStat[p->iCol].nDoc);
121608   }else{                /* Column "occurrences" */
121609     sqlcipher3_result_int64(pContext, p->aStat[p->iCol].nOcc);
121610   }
121611
121612   return SQLCIPHER_OK;
121613 }
121614
121615 /*
121616 ** xRowid - Return the current rowid for the cursor.
121617 */
121618 static int fts3auxRowidMethod(
121619   sqlcipher3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121620   sqlcipher_int64 *pRowid            /* OUT: Rowid value */
121621 ){
121622   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
121623   *pRowid = pCsr->iRowid;
121624   return SQLCIPHER_OK;
121625 }
121626
121627 /*
121628 ** Register the fts3aux module with database connection db. Return SQLCIPHER_OK
121629 ** if successful or an error code if sqlcipher3_create_module() fails.
121630 */
121631 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitAux(sqlcipher3 *db){
121632   static const sqlcipher3_module fts3aux_module = {
121633      0,                           /* iVersion      */
121634      fts3auxConnectMethod,        /* xCreate       */
121635      fts3auxConnectMethod,        /* xConnect      */
121636      fts3auxBestIndexMethod,      /* xBestIndex    */
121637      fts3auxDisconnectMethod,     /* xDisconnect   */
121638      fts3auxDisconnectMethod,     /* xDestroy      */
121639      fts3auxOpenMethod,           /* xOpen         */
121640      fts3auxCloseMethod,          /* xClose        */
121641      fts3auxFilterMethod,         /* xFilter       */
121642      fts3auxNextMethod,           /* xNext         */
121643      fts3auxEofMethod,            /* xEof          */
121644      fts3auxColumnMethod,         /* xColumn       */
121645      fts3auxRowidMethod,          /* xRowid        */
121646      0,                           /* xUpdate       */
121647      0,                           /* xBegin        */
121648      0,                           /* xSync         */
121649      0,                           /* xCommit       */
121650      0,                           /* xRollback     */
121651      0,                           /* xFindFunction */
121652      0,                           /* xRename       */
121653      0,                           /* xSavepoint    */
121654      0,                           /* xRelease      */
121655      0                            /* xRollbackTo   */
121656   };
121657   int rc;                         /* Return code */
121658
121659   rc = sqlcipher3_create_module(db, "fts4aux", &fts3aux_module, 0);
121660   return rc;
121661 }
121662
121663 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
121664
121665 /************** End of fts3_aux.c ********************************************/
121666 /************** Begin file fts3_expr.c ***************************************/
121667 /*
121668 ** 2008 Nov 28
121669 **
121670 ** The author disclaims copyright to this source code.  In place of
121671 ** a legal notice, here is a blessing:
121672 **
121673 **    May you do good and not evil.
121674 **    May you find forgiveness for yourself and forgive others.
121675 **    May you share freely, never taking more than you give.
121676 **
121677 ******************************************************************************
121678 **
121679 ** This module contains code that implements a parser for fts3 query strings
121680 ** (the right-hand argument to the MATCH operator). Because the supported 
121681 ** syntax is relatively simple, the whole tokenizer/parser system is
121682 ** hand-coded. 
121683 */
121684 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
121685
121686 /*
121687 ** By default, this module parses the legacy syntax that has been 
121688 ** traditionally used by fts3. Or, if SQLCIPHER_ENABLE_FTS3_PARENTHESIS
121689 ** is defined, then it uses the new syntax. The differences between
121690 ** the new and the old syntaxes are:
121691 **
121692 **  a) The new syntax supports parenthesis. The old does not.
121693 **
121694 **  b) The new syntax supports the AND and NOT operators. The old does not.
121695 **
121696 **  c) The old syntax supports the "-" token qualifier. This is not 
121697 **     supported by the new syntax (it is replaced by the NOT operator).
121698 **
121699 **  d) When using the old syntax, the OR operator has a greater precedence
121700 **     than an implicit AND. When using the new, both implicity and explicit
121701 **     AND operators have a higher precedence than OR.
121702 **
121703 ** If compiled with SQLCIPHER_TEST defined, then this module exports the
121704 ** symbol "int sqlcipher3_fts3_enable_parentheses". Setting this variable
121705 ** to zero causes the module to use the old syntax. If it is set to 
121706 ** non-zero the new syntax is activated. This is so both syntaxes can
121707 ** be tested using a single build of testfixture.
121708 **
121709 ** The following describes the syntax supported by the fts3 MATCH
121710 ** operator in a similar format to that used by the lemon parser
121711 ** generator. This module does not use actually lemon, it uses a
121712 ** custom parser.
121713 **
121714 **   query ::= andexpr (OR andexpr)*.
121715 **
121716 **   andexpr ::= notexpr (AND? notexpr)*.
121717 **
121718 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
121719 **   notexpr ::= LP query RP.
121720 **
121721 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
121722 **
121723 **   distance_opt ::= .
121724 **   distance_opt ::= / INTEGER.
121725 **
121726 **   phrase ::= TOKEN.
121727 **   phrase ::= COLUMN:TOKEN.
121728 **   phrase ::= "TOKEN TOKEN TOKEN...".
121729 */
121730
121731 #ifdef SQLCIPHER_TEST
121732 SQLCIPHER_API int sqlcipher3_fts3_enable_parentheses = 0;
121733 #else
121734 # ifdef SQLCIPHER_ENABLE_FTS3_PARENTHESIS 
121735 #  define sqlcipher3_fts3_enable_parentheses 1
121736 # else
121737 #  define sqlcipher3_fts3_enable_parentheses 0
121738 # endif
121739 #endif
121740
121741 /*
121742 ** Default span for NEAR operators.
121743 */
121744 #define SQLCIPHER_FTS3_DEFAULT_NEAR_PARAM 10
121745
121746 /* #include <string.h> */
121747 /* #include <assert.h> */
121748
121749 /*
121750 ** isNot:
121751 **   This variable is used by function getNextNode(). When getNextNode() is
121752 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
121753 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
121754 **   FTS3 query "sqlcipher -mysql". Otherwise, ParseContext.isNot is set to
121755 **   zero.
121756 */
121757 typedef struct ParseContext ParseContext;
121758 struct ParseContext {
121759   sqlcipher3_tokenizer *pTokenizer;      /* Tokenizer module */
121760   const char **azCol;                 /* Array of column names for fts3 table */
121761   int bFts4;                          /* True to allow FTS4-only syntax */
121762   int nCol;                           /* Number of entries in azCol[] */
121763   int iDefaultCol;                    /* Default column to query */
121764   int isNot;                          /* True if getNextNode() sees a unary - */
121765   sqlcipher3_context *pCtx;              /* Write error message here */
121766   int nNest;                          /* Number of nested brackets */
121767 };
121768
121769 /*
121770 ** This function is equivalent to the standard isspace() function. 
121771 **
121772 ** The standard isspace() can be awkward to use safely, because although it
121773 ** is defined to accept an argument of type int, its behaviour when passed
121774 ** an integer that falls outside of the range of the unsigned char type
121775 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
121776 ** is defined to accept an argument of type char, and always returns 0 for
121777 ** any values that fall outside of the range of the unsigned char type (i.e.
121778 ** negative values).
121779 */
121780 static int fts3isspace(char c){
121781   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
121782 }
121783
121784 /*
121785 ** Allocate nByte bytes of memory using sqlcipher3_malloc(). If successful,
121786 ** zero the memory before returning a pointer to it. If unsuccessful, 
121787 ** return NULL.
121788 */
121789 static void *fts3MallocZero(int nByte){
121790   void *pRet = sqlcipher3_malloc(nByte);
121791   if( pRet ) memset(pRet, 0, nByte);
121792   return pRet;
121793 }
121794
121795
121796 /*
121797 ** Extract the next token from buffer z (length n) using the tokenizer
121798 ** and other information (column names etc.) in pParse. Create an Fts3Expr
121799 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
121800 ** single token and set *ppExpr to point to it. If the end of the buffer is
121801 ** reached before a token is found, set *ppExpr to zero. It is the
121802 ** responsibility of the caller to eventually deallocate the allocated 
121803 ** Fts3Expr structure (if any) by passing it to sqlcipher3_free().
121804 **
121805 ** Return SQLCIPHER_OK if successful, or SQLCIPHER_NOMEM if a memory allocation
121806 ** fails.
121807 */
121808 static int getNextToken(
121809   ParseContext *pParse,                   /* fts3 query parse context */
121810   int iCol,                               /* Value for Fts3Phrase.iColumn */
121811   const char *z, int n,                   /* Input string */
121812   Fts3Expr **ppExpr,                      /* OUT: expression */
121813   int *pnConsumed                         /* OUT: Number of bytes consumed */
121814 ){
121815   sqlcipher3_tokenizer *pTokenizer = pParse->pTokenizer;
121816   sqlcipher3_tokenizer_module const *pModule = pTokenizer->pModule;
121817   int rc;
121818   sqlcipher3_tokenizer_cursor *pCursor;
121819   Fts3Expr *pRet = 0;
121820   int nConsumed = 0;
121821
121822   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
121823   if( rc==SQLCIPHER_OK ){
121824     const char *zToken;
121825     int nToken, iStart, iEnd, iPosition;
121826     int nByte;                               /* total space to allocate */
121827
121828     pCursor->pTokenizer = pTokenizer;
121829     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
121830
121831     if( rc==SQLCIPHER_OK ){
121832       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
121833       pRet = (Fts3Expr *)fts3MallocZero(nByte);
121834       if( !pRet ){
121835         rc = SQLCIPHER_NOMEM;
121836       }else{
121837         pRet->eType = FTSQUERY_PHRASE;
121838         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
121839         pRet->pPhrase->nToken = 1;
121840         pRet->pPhrase->iColumn = iCol;
121841         pRet->pPhrase->aToken[0].n = nToken;
121842         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
121843         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
121844
121845         if( iEnd<n && z[iEnd]=='*' ){
121846           pRet->pPhrase->aToken[0].isPrefix = 1;
121847           iEnd++;
121848         }
121849
121850         while( 1 ){
121851           if( !sqlcipher3_fts3_enable_parentheses 
121852            && iStart>0 && z[iStart-1]=='-' 
121853           ){
121854             pParse->isNot = 1;
121855             iStart--;
121856           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
121857             pRet->pPhrase->aToken[0].bFirst = 1;
121858             iStart--;
121859           }else{
121860             break;
121861           }
121862         }
121863
121864       }
121865       nConsumed = iEnd;
121866     }
121867
121868     pModule->xClose(pCursor);
121869   }
121870   
121871   *pnConsumed = nConsumed;
121872   *ppExpr = pRet;
121873   return rc;
121874 }
121875
121876
121877 /*
121878 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
121879 ** then free the old allocation.
121880 */
121881 static void *fts3ReallocOrFree(void *pOrig, int nNew){
121882   void *pRet = sqlcipher3_realloc(pOrig, nNew);
121883   if( !pRet ){
121884     sqlcipher3_free(pOrig);
121885   }
121886   return pRet;
121887 }
121888
121889 /*
121890 ** Buffer zInput, length nInput, contains the contents of a quoted string
121891 ** that appeared as part of an fts3 query expression. Neither quote character
121892 ** is included in the buffer. This function attempts to tokenize the entire
121893 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
121894 ** containing the results.
121895 **
121896 ** If successful, SQLCIPHER_OK is returned and *ppExpr set to point at the
121897 ** allocated Fts3Expr structure. Otherwise, either SQLCIPHER_NOMEM (out of memory
121898 ** error) or SQLCIPHER_ERROR (tokenization error) is returned and *ppExpr set
121899 ** to 0.
121900 */
121901 static int getNextString(
121902   ParseContext *pParse,                   /* fts3 query parse context */
121903   const char *zInput, int nInput,         /* Input string */
121904   Fts3Expr **ppExpr                       /* OUT: expression */
121905 ){
121906   sqlcipher3_tokenizer *pTokenizer = pParse->pTokenizer;
121907   sqlcipher3_tokenizer_module const *pModule = pTokenizer->pModule;
121908   int rc;
121909   Fts3Expr *p = 0;
121910   sqlcipher3_tokenizer_cursor *pCursor = 0;
121911   char *zTemp = 0;
121912   int nTemp = 0;
121913
121914   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
121915   int nToken = 0;
121916
121917   /* The final Fts3Expr data structure, including the Fts3Phrase,
121918   ** Fts3PhraseToken structures token buffers are all stored as a single 
121919   ** allocation so that the expression can be freed with a single call to
121920   ** sqlcipher3_free(). Setting this up requires a two pass approach.
121921   **
121922   ** The first pass, in the block below, uses a tokenizer cursor to iterate
121923   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
121924   ** to assemble data in two dynamic buffers:
121925   **
121926   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
121927   **             structure, followed by the array of Fts3PhraseToken 
121928   **             structures. This pass only populates the Fts3PhraseToken array.
121929   **
121930   **   Buffer zTemp: Contains copies of all tokens.
121931   **
121932   ** The second pass, in the block that begins "if( rc==SQLCIPHER_DONE )" below,
121933   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
121934   ** structures.
121935   */
121936   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
121937   if( rc==SQLCIPHER_OK ){
121938     int ii;
121939     pCursor->pTokenizer = pTokenizer;
121940     for(ii=0; rc==SQLCIPHER_OK; ii++){
121941       const char *zByte;
121942       int nByte, iBegin, iEnd, iPos;
121943       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
121944       if( rc==SQLCIPHER_OK ){
121945         Fts3PhraseToken *pToken;
121946
121947         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
121948         if( !p ) goto no_mem;
121949
121950         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
121951         if( !zTemp ) goto no_mem;
121952
121953         assert( nToken==ii );
121954         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
121955         memset(pToken, 0, sizeof(Fts3PhraseToken));
121956
121957         memcpy(&zTemp[nTemp], zByte, nByte);
121958         nTemp += nByte;
121959
121960         pToken->n = nByte;
121961         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
121962         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
121963         nToken = ii+1;
121964       }
121965     }
121966
121967     pModule->xClose(pCursor);
121968     pCursor = 0;
121969   }
121970
121971   if( rc==SQLCIPHER_DONE ){
121972     int jj;
121973     char *zBuf = 0;
121974
121975     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
121976     if( !p ) goto no_mem;
121977     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
121978     p->eType = FTSQUERY_PHRASE;
121979     p->pPhrase = (Fts3Phrase *)&p[1];
121980     p->pPhrase->iColumn = pParse->iDefaultCol;
121981     p->pPhrase->nToken = nToken;
121982
121983     zBuf = (char *)&p->pPhrase->aToken[nToken];
121984     if( zTemp ){
121985       memcpy(zBuf, zTemp, nTemp);
121986       sqlcipher3_free(zTemp);
121987     }else{
121988       assert( nTemp==0 );
121989     }
121990
121991     for(jj=0; jj<p->pPhrase->nToken; jj++){
121992       p->pPhrase->aToken[jj].z = zBuf;
121993       zBuf += p->pPhrase->aToken[jj].n;
121994     }
121995     rc = SQLCIPHER_OK;
121996   }
121997
121998   *ppExpr = p;
121999   return rc;
122000 no_mem:
122001
122002   if( pCursor ){
122003     pModule->xClose(pCursor);
122004   }
122005   sqlcipher3_free(zTemp);
122006   sqlcipher3_free(p);
122007   *ppExpr = 0;
122008   return SQLCIPHER_NOMEM;
122009 }
122010
122011 /*
122012 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
122013 ** call fts3ExprParse(). So this forward declaration is required.
122014 */
122015 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
122016
122017 /*
122018 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
122019 ** structure, or set to 0 if the end of the input buffer is reached.
122020 **
122021 ** Returns an SQLite error code. SQLCIPHER_OK if everything works, SQLCIPHER_NOMEM
122022 ** if a malloc failure occurs, or SQLCIPHER_ERROR if a parse error is encountered.
122023 ** If SQLCIPHER_ERROR is returned, pContext is populated with an error message.
122024 */
122025 static int getNextNode(
122026   ParseContext *pParse,                   /* fts3 query parse context */
122027   const char *z, int n,                   /* Input string */
122028   Fts3Expr **ppExpr,                      /* OUT: expression */
122029   int *pnConsumed                         /* OUT: Number of bytes consumed */
122030 ){
122031   static const struct Fts3Keyword {
122032     char *z;                              /* Keyword text */
122033     unsigned char n;                      /* Length of the keyword */
122034     unsigned char parenOnly;              /* Only valid in paren mode */
122035     unsigned char eType;                  /* Keyword code */
122036   } aKeyword[] = {
122037     { "OR" ,  2, 0, FTSQUERY_OR   },
122038     { "AND",  3, 1, FTSQUERY_AND  },
122039     { "NOT",  3, 1, FTSQUERY_NOT  },
122040     { "NEAR", 4, 0, FTSQUERY_NEAR }
122041   };
122042   int ii;
122043   int iCol;
122044   int iColLen;
122045   int rc;
122046   Fts3Expr *pRet = 0;
122047
122048   const char *zInput = z;
122049   int nInput = n;
122050
122051   pParse->isNot = 0;
122052
122053   /* Skip over any whitespace before checking for a keyword, an open or
122054   ** close bracket, or a quoted string. 
122055   */
122056   while( nInput>0 && fts3isspace(*zInput) ){
122057     nInput--;
122058     zInput++;
122059   }
122060   if( nInput==0 ){
122061     return SQLCIPHER_DONE;
122062   }
122063
122064   /* See if we are dealing with a keyword. */
122065   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
122066     const struct Fts3Keyword *pKey = &aKeyword[ii];
122067
122068     if( (pKey->parenOnly & ~sqlcipher3_fts3_enable_parentheses)!=0 ){
122069       continue;
122070     }
122071
122072     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
122073       int nNear = SQLCIPHER_FTS3_DEFAULT_NEAR_PARAM;
122074       int nKey = pKey->n;
122075       char cNext;
122076
122077       /* If this is a "NEAR" keyword, check for an explicit nearness. */
122078       if( pKey->eType==FTSQUERY_NEAR ){
122079         assert( nKey==4 );
122080         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
122081           nNear = 0;
122082           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
122083             nNear = nNear * 10 + (zInput[nKey] - '0');
122084           }
122085         }
122086       }
122087
122088       /* At this point this is probably a keyword. But for that to be true,
122089       ** the next byte must contain either whitespace, an open or close
122090       ** parenthesis, a quote character, or EOF. 
122091       */
122092       cNext = zInput[nKey];
122093       if( fts3isspace(cNext) 
122094        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
122095       ){
122096         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
122097         if( !pRet ){
122098           return SQLCIPHER_NOMEM;
122099         }
122100         pRet->eType = pKey->eType;
122101         pRet->nNear = nNear;
122102         *ppExpr = pRet;
122103         *pnConsumed = (int)((zInput - z) + nKey);
122104         return SQLCIPHER_OK;
122105       }
122106
122107       /* Turns out that wasn't a keyword after all. This happens if the
122108       ** user has supplied a token such as "ORacle". Continue.
122109       */
122110     }
122111   }
122112
122113   /* Check for an open bracket. */
122114   if( sqlcipher3_fts3_enable_parentheses ){
122115     if( *zInput=='(' ){
122116       int nConsumed;
122117       pParse->nNest++;
122118       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
122119       if( rc==SQLCIPHER_OK && !*ppExpr ){
122120         rc = SQLCIPHER_DONE;
122121       }
122122       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
122123       return rc;
122124     }
122125   
122126     /* Check for a close bracket. */
122127     if( *zInput==')' ){
122128       pParse->nNest--;
122129       *pnConsumed = (int)((zInput - z) + 1);
122130       return SQLCIPHER_DONE;
122131     }
122132   }
122133
122134   /* See if we are dealing with a quoted phrase. If this is the case, then
122135   ** search for the closing quote and pass the whole string to getNextString()
122136   ** for processing. This is easy to do, as fts3 has no syntax for escaping
122137   ** a quote character embedded in a string.
122138   */
122139   if( *zInput=='"' ){
122140     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
122141     *pnConsumed = (int)((zInput - z) + ii + 1);
122142     if( ii==nInput ){
122143       return SQLCIPHER_ERROR;
122144     }
122145     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
122146   }
122147
122148
122149   /* If control flows to this point, this must be a regular token, or 
122150   ** the end of the input. Read a regular token using the sqlcipher3_tokenizer
122151   ** interface. Before doing so, figure out if there is an explicit
122152   ** column specifier for the token. 
122153   **
122154   ** TODO: Strangely, it is not possible to associate a column specifier
122155   ** with a quoted phrase, only with a single token. Not sure if this was
122156   ** an implementation artifact or an intentional decision when fts3 was
122157   ** first implemented. Whichever it was, this module duplicates the 
122158   ** limitation.
122159   */
122160   iCol = pParse->iDefaultCol;
122161   iColLen = 0;
122162   for(ii=0; ii<pParse->nCol; ii++){
122163     const char *zStr = pParse->azCol[ii];
122164     int nStr = (int)strlen(zStr);
122165     if( nInput>nStr && zInput[nStr]==':' 
122166      && sqlcipher3_strnicmp(zStr, zInput, nStr)==0 
122167     ){
122168       iCol = ii;
122169       iColLen = (int)((zInput - z) + nStr + 1);
122170       break;
122171     }
122172   }
122173   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
122174   *pnConsumed += iColLen;
122175   return rc;
122176 }
122177
122178 /*
122179 ** The argument is an Fts3Expr structure for a binary operator (any type
122180 ** except an FTSQUERY_PHRASE). Return an integer value representing the
122181 ** precedence of the operator. Lower values have a higher precedence (i.e.
122182 ** group more tightly). For example, in the C language, the == operator
122183 ** groups more tightly than ||, and would therefore have a higher precedence.
122184 **
122185 ** When using the new fts3 query syntax (when SQLCIPHER_ENABLE_FTS3_PARENTHESIS
122186 ** is defined), the order of the operators in precedence from highest to
122187 ** lowest is:
122188 **
122189 **   NEAR
122190 **   NOT
122191 **   AND (including implicit ANDs)
122192 **   OR
122193 **
122194 ** Note that when using the old query syntax, the OR operator has a higher
122195 ** precedence than the AND operator.
122196 */
122197 static int opPrecedence(Fts3Expr *p){
122198   assert( p->eType!=FTSQUERY_PHRASE );
122199   if( sqlcipher3_fts3_enable_parentheses ){
122200     return p->eType;
122201   }else if( p->eType==FTSQUERY_NEAR ){
122202     return 1;
122203   }else if( p->eType==FTSQUERY_OR ){
122204     return 2;
122205   }
122206   assert( p->eType==FTSQUERY_AND );
122207   return 3;
122208 }
122209
122210 /*
122211 ** Argument ppHead contains a pointer to the current head of a query 
122212 ** expression tree being parsed. pPrev is the expression node most recently
122213 ** inserted into the tree. This function adds pNew, which is always a binary
122214 ** operator node, into the expression tree based on the relative precedence
122215 ** of pNew and the existing nodes of the tree. This may result in the head
122216 ** of the tree changing, in which case *ppHead is set to the new root node.
122217 */
122218 static void insertBinaryOperator(
122219   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
122220   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
122221   Fts3Expr *pNew           /* New binary node to insert into expression tree */
122222 ){
122223   Fts3Expr *pSplit = pPrev;
122224   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
122225     pSplit = pSplit->pParent;
122226   }
122227
122228   if( pSplit->pParent ){
122229     assert( pSplit->pParent->pRight==pSplit );
122230     pSplit->pParent->pRight = pNew;
122231     pNew->pParent = pSplit->pParent;
122232   }else{
122233     *ppHead = pNew;
122234   }
122235   pNew->pLeft = pSplit;
122236   pSplit->pParent = pNew;
122237 }
122238
122239 /*
122240 ** Parse the fts3 query expression found in buffer z, length n. This function
122241 ** returns either when the end of the buffer is reached or an unmatched 
122242 ** closing bracket - ')' - is encountered.
122243 **
122244 ** If successful, SQLCIPHER_OK is returned, *ppExpr is set to point to the
122245 ** parsed form of the expression and *pnConsumed is set to the number of
122246 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLCIPHER_NOMEM
122247 ** (out of memory error) or SQLCIPHER_ERROR (parse error) is returned.
122248 */
122249 static int fts3ExprParse(
122250   ParseContext *pParse,                   /* fts3 query parse context */
122251   const char *z, int n,                   /* Text of MATCH query */
122252   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
122253   int *pnConsumed                         /* OUT: Number of bytes consumed */
122254 ){
122255   Fts3Expr *pRet = 0;
122256   Fts3Expr *pPrev = 0;
122257   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
122258   int nIn = n;
122259   const char *zIn = z;
122260   int rc = SQLCIPHER_OK;
122261   int isRequirePhrase = 1;
122262
122263   while( rc==SQLCIPHER_OK ){
122264     Fts3Expr *p = 0;
122265     int nByte = 0;
122266     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
122267     if( rc==SQLCIPHER_OK ){
122268       int isPhrase;
122269
122270       if( !sqlcipher3_fts3_enable_parentheses 
122271        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
122272       ){
122273         /* Create an implicit NOT operator. */
122274         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
122275         if( !pNot ){
122276           sqlcipher3Fts3ExprFree(p);
122277           rc = SQLCIPHER_NOMEM;
122278           goto exprparse_out;
122279         }
122280         pNot->eType = FTSQUERY_NOT;
122281         pNot->pRight = p;
122282         if( pNotBranch ){
122283           pNot->pLeft = pNotBranch;
122284         }
122285         pNotBranch = pNot;
122286         p = pPrev;
122287       }else{
122288         int eType = p->eType;
122289         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
122290
122291         /* The isRequirePhrase variable is set to true if a phrase or
122292         ** an expression contained in parenthesis is required. If a
122293         ** binary operator (AND, OR, NOT or NEAR) is encounted when
122294         ** isRequirePhrase is set, this is a syntax error.
122295         */
122296         if( !isPhrase && isRequirePhrase ){
122297           sqlcipher3Fts3ExprFree(p);
122298           rc = SQLCIPHER_ERROR;
122299           goto exprparse_out;
122300         }
122301   
122302         if( isPhrase && !isRequirePhrase ){
122303           /* Insert an implicit AND operator. */
122304           Fts3Expr *pAnd;
122305           assert( pRet && pPrev );
122306           pAnd = fts3MallocZero(sizeof(Fts3Expr));
122307           if( !pAnd ){
122308             sqlcipher3Fts3ExprFree(p);
122309             rc = SQLCIPHER_NOMEM;
122310             goto exprparse_out;
122311           }
122312           pAnd->eType = FTSQUERY_AND;
122313           insertBinaryOperator(&pRet, pPrev, pAnd);
122314           pPrev = pAnd;
122315         }
122316
122317         /* This test catches attempts to make either operand of a NEAR
122318         ** operator something other than a phrase. For example, either of
122319         ** the following:
122320         **
122321         **    (bracketed expression) NEAR phrase
122322         **    phrase NEAR (bracketed expression)
122323         **
122324         ** Return an error in either case.
122325         */
122326         if( pPrev && (
122327             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
122328          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
122329         )){
122330           sqlcipher3Fts3ExprFree(p);
122331           rc = SQLCIPHER_ERROR;
122332           goto exprparse_out;
122333         }
122334   
122335         if( isPhrase ){
122336           if( pRet ){
122337             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
122338             pPrev->pRight = p;
122339             p->pParent = pPrev;
122340           }else{
122341             pRet = p;
122342           }
122343         }else{
122344           insertBinaryOperator(&pRet, pPrev, p);
122345         }
122346         isRequirePhrase = !isPhrase;
122347       }
122348       assert( nByte>0 );
122349     }
122350     assert( rc!=SQLCIPHER_OK || (nByte>0 && nByte<=nIn) );
122351     nIn -= nByte;
122352     zIn += nByte;
122353     pPrev = p;
122354   }
122355
122356   if( rc==SQLCIPHER_DONE && pRet && isRequirePhrase ){
122357     rc = SQLCIPHER_ERROR;
122358   }
122359
122360   if( rc==SQLCIPHER_DONE ){
122361     rc = SQLCIPHER_OK;
122362     if( !sqlcipher3_fts3_enable_parentheses && pNotBranch ){
122363       if( !pRet ){
122364         rc = SQLCIPHER_ERROR;
122365       }else{
122366         Fts3Expr *pIter = pNotBranch;
122367         while( pIter->pLeft ){
122368           pIter = pIter->pLeft;
122369         }
122370         pIter->pLeft = pRet;
122371         pRet = pNotBranch;
122372       }
122373     }
122374   }
122375   *pnConsumed = n - nIn;
122376
122377 exprparse_out:
122378   if( rc!=SQLCIPHER_OK ){
122379     sqlcipher3Fts3ExprFree(pRet);
122380     sqlcipher3Fts3ExprFree(pNotBranch);
122381     pRet = 0;
122382   }
122383   *ppExpr = pRet;
122384   return rc;
122385 }
122386
122387 /*
122388 ** Parameters z and n contain a pointer to and length of a buffer containing
122389 ** an fts3 query expression, respectively. This function attempts to parse the
122390 ** query expression and create a tree of Fts3Expr structures representing the
122391 ** parsed expression. If successful, *ppExpr is set to point to the head
122392 ** of the parsed expression tree and SQLCIPHER_OK is returned. If an error
122393 ** occurs, either SQLCIPHER_NOMEM (out-of-memory error) or SQLCIPHER_ERROR (parse
122394 ** error) is returned and *ppExpr is set to 0.
122395 **
122396 ** If parameter n is a negative number, then z is assumed to point to a
122397 ** nul-terminated string and the length is determined using strlen().
122398 **
122399 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
122400 ** use to normalize query tokens while parsing the expression. The azCol[]
122401 ** array, which is assumed to contain nCol entries, should contain the names
122402 ** of each column in the target fts3 table, in order from left to right. 
122403 ** Column names must be nul-terminated strings.
122404 **
122405 ** The iDefaultCol parameter should be passed the index of the table column
122406 ** that appears on the left-hand-side of the MATCH operator (the default
122407 ** column to match against for tokens for which a column name is not explicitly
122408 ** specified as part of the query string), or -1 if tokens may by default
122409 ** match any table column.
122410 */
122411 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprParse(
122412   sqlcipher3_tokenizer *pTokenizer,      /* Tokenizer module */
122413   char **azCol,                       /* Array of column names for fts3 table */
122414   int bFts4,                          /* True to allow FTS4-only syntax */
122415   int nCol,                           /* Number of entries in azCol[] */
122416   int iDefaultCol,                    /* Default column to query */
122417   const char *z, int n,               /* Text of MATCH query */
122418   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
122419 ){
122420   int nParsed;
122421   int rc;
122422   ParseContext sParse;
122423   sParse.pTokenizer = pTokenizer;
122424   sParse.azCol = (const char **)azCol;
122425   sParse.nCol = nCol;
122426   sParse.iDefaultCol = iDefaultCol;
122427   sParse.nNest = 0;
122428   sParse.bFts4 = bFts4;
122429   if( z==0 ){
122430     *ppExpr = 0;
122431     return SQLCIPHER_OK;
122432   }
122433   if( n<0 ){
122434     n = (int)strlen(z);
122435   }
122436   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
122437
122438   /* Check for mismatched parenthesis */
122439   if( rc==SQLCIPHER_OK && sParse.nNest ){
122440     rc = SQLCIPHER_ERROR;
122441     sqlcipher3Fts3ExprFree(*ppExpr);
122442     *ppExpr = 0;
122443   }
122444
122445   return rc;
122446 }
122447
122448 /*
122449 ** Free a parsed fts3 query expression allocated by sqlcipher3Fts3ExprParse().
122450 */
122451 SQLCIPHER_PRIVATE void sqlcipher3Fts3ExprFree(Fts3Expr *p){
122452   if( p ){
122453     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
122454     sqlcipher3Fts3ExprFree(p->pLeft);
122455     sqlcipher3Fts3ExprFree(p->pRight);
122456     sqlcipher3Fts3EvalPhraseCleanup(p->pPhrase);
122457     sqlcipher3_free(p->aMI);
122458     sqlcipher3_free(p);
122459   }
122460 }
122461
122462 /****************************************************************************
122463 *****************************************************************************
122464 ** Everything after this point is just test code.
122465 */
122466
122467 #ifdef SQLCIPHER_TEST
122468
122469 /* #include <stdio.h> */
122470
122471 /*
122472 ** Function to query the hash-table of tokenizers (see README.tokenizers).
122473 */
122474 static int queryTestTokenizer(
122475   sqlcipher3 *db, 
122476   const char *zName,  
122477   const sqlcipher3_tokenizer_module **pp
122478 ){
122479   int rc;
122480   sqlcipher3_stmt *pStmt;
122481   const char zSql[] = "SELECT fts3_tokenizer(?)";
122482
122483   *pp = 0;
122484   rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
122485   if( rc!=SQLCIPHER_OK ){
122486     return rc;
122487   }
122488
122489   sqlcipher3_bind_text(pStmt, 1, zName, -1, SQLCIPHER_STATIC);
122490   if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
122491     if( sqlcipher3_column_type(pStmt, 0)==SQLCIPHER_BLOB ){
122492       memcpy((void *)pp, sqlcipher3_column_blob(pStmt, 0), sizeof(*pp));
122493     }
122494   }
122495
122496   return sqlcipher3_finalize(pStmt);
122497 }
122498
122499 /*
122500 ** Return a pointer to a buffer containing a text representation of the
122501 ** expression passed as the first argument. The buffer is obtained from
122502 ** sqlcipher3_malloc(). It is the responsibility of the caller to use 
122503 ** sqlcipher3_free() to release the memory. If an OOM condition is encountered,
122504 ** NULL is returned.
122505 **
122506 ** If the second argument is not NULL, then its contents are prepended to 
122507 ** the returned expression text and then freed using sqlcipher3_free().
122508 */
122509 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
122510   switch( pExpr->eType ){
122511     case FTSQUERY_PHRASE: {
122512       Fts3Phrase *pPhrase = pExpr->pPhrase;
122513       int i;
122514       zBuf = sqlcipher3_mprintf(
122515           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
122516       for(i=0; zBuf && i<pPhrase->nToken; i++){
122517         zBuf = sqlcipher3_mprintf("%z %.*s%s", zBuf, 
122518             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
122519             (pPhrase->aToken[i].isPrefix?"+":"")
122520         );
122521       }
122522       return zBuf;
122523     }
122524
122525     case FTSQUERY_NEAR:
122526       zBuf = sqlcipher3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
122527       break;
122528     case FTSQUERY_NOT:
122529       zBuf = sqlcipher3_mprintf("%zNOT ", zBuf);
122530       break;
122531     case FTSQUERY_AND:
122532       zBuf = sqlcipher3_mprintf("%zAND ", zBuf);
122533       break;
122534     case FTSQUERY_OR:
122535       zBuf = sqlcipher3_mprintf("%zOR ", zBuf);
122536       break;
122537   }
122538
122539   if( zBuf ) zBuf = sqlcipher3_mprintf("%z{", zBuf);
122540   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
122541   if( zBuf ) zBuf = sqlcipher3_mprintf("%z} {", zBuf);
122542
122543   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
122544   if( zBuf ) zBuf = sqlcipher3_mprintf("%z}", zBuf);
122545
122546   return zBuf;
122547 }
122548
122549 /*
122550 ** This is the implementation of a scalar SQL function used to test the 
122551 ** expression parser. It should be called as follows:
122552 **
122553 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
122554 **
122555 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
122556 ** to parse the query expression (see README.tokenizers). The second argument
122557 ** is the query expression to parse. Each subsequent argument is the name
122558 ** of a column of the fts3 table that the query expression may refer to.
122559 ** For example:
122560 **
122561 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
122562 */
122563 static void fts3ExprTest(
122564   sqlcipher3_context *context,
122565   int argc,
122566   sqlcipher3_value **argv
122567 ){
122568   sqlcipher3_tokenizer_module const *pModule = 0;
122569   sqlcipher3_tokenizer *pTokenizer = 0;
122570   int rc;
122571   char **azCol = 0;
122572   const char *zExpr;
122573   int nExpr;
122574   int nCol;
122575   int ii;
122576   Fts3Expr *pExpr;
122577   char *zBuf = 0;
122578   sqlcipher3 *db = sqlcipher3_context_db_handle(context);
122579
122580   if( argc<3 ){
122581     sqlcipher3_result_error(context, 
122582         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
122583     );
122584     return;
122585   }
122586
122587   rc = queryTestTokenizer(db,
122588                           (const char *)sqlcipher3_value_text(argv[0]), &pModule);
122589   if( rc==SQLCIPHER_NOMEM ){
122590     sqlcipher3_result_error_nomem(context);
122591     goto exprtest_out;
122592   }else if( !pModule ){
122593     sqlcipher3_result_error(context, "No such tokenizer module", -1);
122594     goto exprtest_out;
122595   }
122596
122597   rc = pModule->xCreate(0, 0, &pTokenizer);
122598   assert( rc==SQLCIPHER_NOMEM || rc==SQLCIPHER_OK );
122599   if( rc==SQLCIPHER_NOMEM ){
122600     sqlcipher3_result_error_nomem(context);
122601     goto exprtest_out;
122602   }
122603   pTokenizer->pModule = pModule;
122604
122605   zExpr = (const char *)sqlcipher3_value_text(argv[1]);
122606   nExpr = sqlcipher3_value_bytes(argv[1]);
122607   nCol = argc-2;
122608   azCol = (char **)sqlcipher3_malloc(nCol*sizeof(char *));
122609   if( !azCol ){
122610     sqlcipher3_result_error_nomem(context);
122611     goto exprtest_out;
122612   }
122613   for(ii=0; ii<nCol; ii++){
122614     azCol[ii] = (char *)sqlcipher3_value_text(argv[ii+2]);
122615   }
122616
122617   rc = sqlcipher3Fts3ExprParse(
122618       pTokenizer, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
122619   );
122620   if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_NOMEM ){
122621     sqlcipher3_result_error(context, "Error parsing expression", -1);
122622   }else if( rc==SQLCIPHER_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
122623     sqlcipher3_result_error_nomem(context);
122624   }else{
122625     sqlcipher3_result_text(context, zBuf, -1, SQLCIPHER_TRANSIENT);
122626     sqlcipher3_free(zBuf);
122627   }
122628
122629   sqlcipher3Fts3ExprFree(pExpr);
122630
122631 exprtest_out:
122632   if( pModule && pTokenizer ){
122633     rc = pModule->xDestroy(pTokenizer);
122634   }
122635   sqlcipher3_free(azCol);
122636 }
122637
122638 /*
122639 ** Register the query expression parser test function fts3_exprtest() 
122640 ** with database connection db. 
122641 */
122642 SQLCIPHER_PRIVATE int sqlcipher3Fts3ExprInitTestInterface(sqlcipher3* db){
122643   return sqlcipher3_create_function(
122644       db, "fts3_exprtest", -1, SQLCIPHER_UTF8, 0, fts3ExprTest, 0, 0
122645   );
122646 }
122647
122648 #endif
122649 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
122650
122651 /************** End of fts3_expr.c *******************************************/
122652 /************** Begin file fts3_hash.c ***************************************/
122653 /*
122654 ** 2001 September 22
122655 **
122656 ** The author disclaims copyright to this source code.  In place of
122657 ** a legal notice, here is a blessing:
122658 **
122659 **    May you do good and not evil.
122660 **    May you find forgiveness for yourself and forgive others.
122661 **    May you share freely, never taking more than you give.
122662 **
122663 *************************************************************************
122664 ** This is the implementation of generic hash-tables used in SQLite.
122665 ** We've modified it slightly to serve as a standalone hash table
122666 ** implementation for the full-text indexing module.
122667 */
122668
122669 /*
122670 ** The code in this file is only compiled if:
122671 **
122672 **     * The FTS3 module is being built as an extension
122673 **       (in which case SQLCIPHER_CORE is not defined), or
122674 **
122675 **     * The FTS3 module is being built into the core of
122676 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
122677 */
122678 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
122679
122680 /* #include <assert.h> */
122681 /* #include <stdlib.h> */
122682 /* #include <string.h> */
122683
122684
122685 /*
122686 ** Malloc and Free functions
122687 */
122688 static void *fts3HashMalloc(int n){
122689   void *p = sqlcipher3_malloc(n);
122690   if( p ){
122691     memset(p, 0, n);
122692   }
122693   return p;
122694 }
122695 static void fts3HashFree(void *p){
122696   sqlcipher3_free(p);
122697 }
122698
122699 /* Turn bulk memory into a hash table object by initializing the
122700 ** fields of the Hash structure.
122701 **
122702 ** "pNew" is a pointer to the hash table that is to be initialized.
122703 ** keyClass is one of the constants 
122704 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
122705 ** determines what kind of key the hash table will use.  "copyKey" is
122706 ** true if the hash table should make its own private copy of keys and
122707 ** false if it should just use the supplied pointer.
122708 */
122709 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
122710   assert( pNew!=0 );
122711   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
122712   pNew->keyClass = keyClass;
122713   pNew->copyKey = copyKey;
122714   pNew->first = 0;
122715   pNew->count = 0;
122716   pNew->htsize = 0;
122717   pNew->ht = 0;
122718 }
122719
122720 /* Remove all entries from a hash table.  Reclaim all memory.
122721 ** Call this routine to delete a hash table or to reset a hash table
122722 ** to the empty state.
122723 */
122724 SQLCIPHER_PRIVATE void sqlcipher3Fts3HashClear(Fts3Hash *pH){
122725   Fts3HashElem *elem;         /* For looping over all elements of the table */
122726
122727   assert( pH!=0 );
122728   elem = pH->first;
122729   pH->first = 0;
122730   fts3HashFree(pH->ht);
122731   pH->ht = 0;
122732   pH->htsize = 0;
122733   while( elem ){
122734     Fts3HashElem *next_elem = elem->next;
122735     if( pH->copyKey && elem->pKey ){
122736       fts3HashFree(elem->pKey);
122737     }
122738     fts3HashFree(elem);
122739     elem = next_elem;
122740   }
122741   pH->count = 0;
122742 }
122743
122744 /*
122745 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
122746 */
122747 static int fts3StrHash(const void *pKey, int nKey){
122748   const char *z = (const char *)pKey;
122749   int h = 0;
122750   if( nKey<=0 ) nKey = (int) strlen(z);
122751   while( nKey > 0  ){
122752     h = (h<<3) ^ h ^ *z++;
122753     nKey--;
122754   }
122755   return h & 0x7fffffff;
122756 }
122757 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
122758   if( n1!=n2 ) return 1;
122759   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
122760 }
122761
122762 /*
122763 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
122764 */
122765 static int fts3BinHash(const void *pKey, int nKey){
122766   int h = 0;
122767   const char *z = (const char *)pKey;
122768   while( nKey-- > 0 ){
122769     h = (h<<3) ^ h ^ *(z++);
122770   }
122771   return h & 0x7fffffff;
122772 }
122773 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
122774   if( n1!=n2 ) return 1;
122775   return memcmp(pKey1,pKey2,n1);
122776 }
122777
122778 /*
122779 ** Return a pointer to the appropriate hash function given the key class.
122780 **
122781 ** The C syntax in this function definition may be unfamilar to some 
122782 ** programmers, so we provide the following additional explanation:
122783 **
122784 ** The name of the function is "ftsHashFunction".  The function takes a
122785 ** single parameter "keyClass".  The return value of ftsHashFunction()
122786 ** is a pointer to another function.  Specifically, the return value
122787 ** of ftsHashFunction() is a pointer to a function that takes two parameters
122788 ** with types "const void*" and "int" and returns an "int".
122789 */
122790 static int (*ftsHashFunction(int keyClass))(const void*,int){
122791   if( keyClass==FTS3_HASH_STRING ){
122792     return &fts3StrHash;
122793   }else{
122794     assert( keyClass==FTS3_HASH_BINARY );
122795     return &fts3BinHash;
122796   }
122797 }
122798
122799 /*
122800 ** Return a pointer to the appropriate hash function given the key class.
122801 **
122802 ** For help in interpreted the obscure C code in the function definition,
122803 ** see the header comment on the previous function.
122804 */
122805 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
122806   if( keyClass==FTS3_HASH_STRING ){
122807     return &fts3StrCompare;
122808   }else{
122809     assert( keyClass==FTS3_HASH_BINARY );
122810     return &fts3BinCompare;
122811   }
122812 }
122813
122814 /* Link an element into the hash table
122815 */
122816 static void fts3HashInsertElement(
122817   Fts3Hash *pH,            /* The complete hash table */
122818   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
122819   Fts3HashElem *pNew       /* The element to be inserted */
122820 ){
122821   Fts3HashElem *pHead;     /* First element already in pEntry */
122822   pHead = pEntry->chain;
122823   if( pHead ){
122824     pNew->next = pHead;
122825     pNew->prev = pHead->prev;
122826     if( pHead->prev ){ pHead->prev->next = pNew; }
122827     else             { pH->first = pNew; }
122828     pHead->prev = pNew;
122829   }else{
122830     pNew->next = pH->first;
122831     if( pH->first ){ pH->first->prev = pNew; }
122832     pNew->prev = 0;
122833     pH->first = pNew;
122834   }
122835   pEntry->count++;
122836   pEntry->chain = pNew;
122837 }
122838
122839
122840 /* Resize the hash table so that it cantains "new_size" buckets.
122841 ** "new_size" must be a power of 2.  The hash table might fail 
122842 ** to resize if sqlcipherMalloc() fails.
122843 **
122844 ** Return non-zero if a memory allocation error occurs.
122845 */
122846 static int fts3Rehash(Fts3Hash *pH, int new_size){
122847   struct _fts3ht *new_ht;          /* The new hash table */
122848   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
122849   int (*xHash)(const void*,int);   /* The hash function */
122850
122851   assert( (new_size & (new_size-1))==0 );
122852   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
122853   if( new_ht==0 ) return 1;
122854   fts3HashFree(pH->ht);
122855   pH->ht = new_ht;
122856   pH->htsize = new_size;
122857   xHash = ftsHashFunction(pH->keyClass);
122858   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
122859     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
122860     next_elem = elem->next;
122861     fts3HashInsertElement(pH, &new_ht[h], elem);
122862   }
122863   return 0;
122864 }
122865
122866 /* This function (for internal use only) locates an element in an
122867 ** hash table that matches the given key.  The hash for this key has
122868 ** already been computed and is passed as the 4th parameter.
122869 */
122870 static Fts3HashElem *fts3FindElementByHash(
122871   const Fts3Hash *pH, /* The pH to be searched */
122872   const void *pKey,   /* The key we are searching for */
122873   int nKey,
122874   int h               /* The hash for this key. */
122875 ){
122876   Fts3HashElem *elem;            /* Used to loop thru the element list */
122877   int count;                     /* Number of elements left to test */
122878   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
122879
122880   if( pH->ht ){
122881     struct _fts3ht *pEntry = &pH->ht[h];
122882     elem = pEntry->chain;
122883     count = pEntry->count;
122884     xCompare = ftsCompareFunction(pH->keyClass);
122885     while( count-- && elem ){
122886       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
122887         return elem;
122888       }
122889       elem = elem->next;
122890     }
122891   }
122892   return 0;
122893 }
122894
122895 /* Remove a single entry from the hash table given a pointer to that
122896 ** element and a hash on the element's key.
122897 */
122898 static void fts3RemoveElementByHash(
122899   Fts3Hash *pH,         /* The pH containing "elem" */
122900   Fts3HashElem* elem,   /* The element to be removed from the pH */
122901   int h                 /* Hash value for the element */
122902 ){
122903   struct _fts3ht *pEntry;
122904   if( elem->prev ){
122905     elem->prev->next = elem->next; 
122906   }else{
122907     pH->first = elem->next;
122908   }
122909   if( elem->next ){
122910     elem->next->prev = elem->prev;
122911   }
122912   pEntry = &pH->ht[h];
122913   if( pEntry->chain==elem ){
122914     pEntry->chain = elem->next;
122915   }
122916   pEntry->count--;
122917   if( pEntry->count<=0 ){
122918     pEntry->chain = 0;
122919   }
122920   if( pH->copyKey && elem->pKey ){
122921     fts3HashFree(elem->pKey);
122922   }
122923   fts3HashFree( elem );
122924   pH->count--;
122925   if( pH->count<=0 ){
122926     assert( pH->first==0 );
122927     assert( pH->count==0 );
122928     fts3HashClear(pH);
122929   }
122930 }
122931
122932 SQLCIPHER_PRIVATE Fts3HashElem *sqlcipher3Fts3HashFindElem(
122933   const Fts3Hash *pH, 
122934   const void *pKey, 
122935   int nKey
122936 ){
122937   int h;                          /* A hash on key */
122938   int (*xHash)(const void*,int);  /* The hash function */
122939
122940   if( pH==0 || pH->ht==0 ) return 0;
122941   xHash = ftsHashFunction(pH->keyClass);
122942   assert( xHash!=0 );
122943   h = (*xHash)(pKey,nKey);
122944   assert( (pH->htsize & (pH->htsize-1))==0 );
122945   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
122946 }
122947
122948 /* 
122949 ** Attempt to locate an element of the hash table pH with a key
122950 ** that matches pKey,nKey.  Return the data for this element if it is
122951 ** found, or NULL if there is no match.
122952 */
122953 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
122954   Fts3HashElem *pElem;            /* The element that matches key (if any) */
122955
122956   pElem = sqlcipher3Fts3HashFindElem(pH, pKey, nKey);
122957   return pElem ? pElem->data : 0;
122958 }
122959
122960 /* Insert an element into the hash table pH.  The key is pKey,nKey
122961 ** and the data is "data".
122962 **
122963 ** If no element exists with a matching key, then a new
122964 ** element is created.  A copy of the key is made if the copyKey
122965 ** flag is set.  NULL is returned.
122966 **
122967 ** If another element already exists with the same key, then the
122968 ** new data replaces the old data and the old data is returned.
122969 ** The key is not copied in this instance.  If a malloc fails, then
122970 ** the new data is returned and the hash table is unchanged.
122971 **
122972 ** If the "data" parameter to this function is NULL, then the
122973 ** element corresponding to "key" is removed from the hash table.
122974 */
122975 SQLCIPHER_PRIVATE void *sqlcipher3Fts3HashInsert(
122976   Fts3Hash *pH,        /* The hash table to insert into */
122977   const void *pKey,    /* The key */
122978   int nKey,            /* Number of bytes in the key */
122979   void *data           /* The data */
122980 ){
122981   int hraw;                 /* Raw hash value of the key */
122982   int h;                    /* the hash of the key modulo hash table size */
122983   Fts3HashElem *elem;       /* Used to loop thru the element list */
122984   Fts3HashElem *new_elem;   /* New element added to the pH */
122985   int (*xHash)(const void*,int);  /* The hash function */
122986
122987   assert( pH!=0 );
122988   xHash = ftsHashFunction(pH->keyClass);
122989   assert( xHash!=0 );
122990   hraw = (*xHash)(pKey, nKey);
122991   assert( (pH->htsize & (pH->htsize-1))==0 );
122992   h = hraw & (pH->htsize-1);
122993   elem = fts3FindElementByHash(pH,pKey,nKey,h);
122994   if( elem ){
122995     void *old_data = elem->data;
122996     if( data==0 ){
122997       fts3RemoveElementByHash(pH,elem,h);
122998     }else{
122999       elem->data = data;
123000     }
123001     return old_data;
123002   }
123003   if( data==0 ) return 0;
123004   if( (pH->htsize==0 && fts3Rehash(pH,8))
123005    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
123006   ){
123007     pH->count = 0;
123008     return data;
123009   }
123010   assert( pH->htsize>0 );
123011   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
123012   if( new_elem==0 ) return data;
123013   if( pH->copyKey && pKey!=0 ){
123014     new_elem->pKey = fts3HashMalloc( nKey );
123015     if( new_elem->pKey==0 ){
123016       fts3HashFree(new_elem);
123017       return data;
123018     }
123019     memcpy((void*)new_elem->pKey, pKey, nKey);
123020   }else{
123021     new_elem->pKey = (void*)pKey;
123022   }
123023   new_elem->nKey = nKey;
123024   pH->count++;
123025   assert( pH->htsize>0 );
123026   assert( (pH->htsize & (pH->htsize-1))==0 );
123027   h = hraw & (pH->htsize-1);
123028   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
123029   new_elem->data = data;
123030   return 0;
123031 }
123032
123033 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
123034
123035 /************** End of fts3_hash.c *******************************************/
123036 /************** Begin file fts3_porter.c *************************************/
123037 /*
123038 ** 2006 September 30
123039 **
123040 ** The author disclaims copyright to this source code.  In place of
123041 ** a legal notice, here is a blessing:
123042 **
123043 **    May you do good and not evil.
123044 **    May you find forgiveness for yourself and forgive others.
123045 **    May you share freely, never taking more than you give.
123046 **
123047 *************************************************************************
123048 ** Implementation of the full-text-search tokenizer that implements
123049 ** a Porter stemmer.
123050 */
123051
123052 /*
123053 ** The code in this file is only compiled if:
123054 **
123055 **     * The FTS3 module is being built as an extension
123056 **       (in which case SQLCIPHER_CORE is not defined), or
123057 **
123058 **     * The FTS3 module is being built into the core of
123059 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
123060 */
123061 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
123062
123063 /* #include <assert.h> */
123064 /* #include <stdlib.h> */
123065 /* #include <stdio.h> */
123066 /* #include <string.h> */
123067
123068
123069 /*
123070 ** Class derived from sqlcipher3_tokenizer
123071 */
123072 typedef struct porter_tokenizer {
123073   sqlcipher3_tokenizer base;      /* Base class */
123074 } porter_tokenizer;
123075
123076 /*
123077 ** Class derived from sqlit3_tokenizer_cursor
123078 */
123079 typedef struct porter_tokenizer_cursor {
123080   sqlcipher3_tokenizer_cursor base;
123081   const char *zInput;          /* input we are tokenizing */
123082   int nInput;                  /* size of the input */
123083   int iOffset;                 /* current position in zInput */
123084   int iToken;                  /* index of next token to be returned */
123085   char *zToken;                /* storage for current token */
123086   int nAllocated;              /* space allocated to zToken buffer */
123087 } porter_tokenizer_cursor;
123088
123089
123090 /*
123091 ** Create a new tokenizer instance.
123092 */
123093 static int porterCreate(
123094   int argc, const char * const *argv,
123095   sqlcipher3_tokenizer **ppTokenizer
123096 ){
123097   porter_tokenizer *t;
123098
123099   UNUSED_PARAMETER(argc);
123100   UNUSED_PARAMETER(argv);
123101
123102   t = (porter_tokenizer *) sqlcipher3_malloc(sizeof(*t));
123103   if( t==NULL ) return SQLCIPHER_NOMEM;
123104   memset(t, 0, sizeof(*t));
123105   *ppTokenizer = &t->base;
123106   return SQLCIPHER_OK;
123107 }
123108
123109 /*
123110 ** Destroy a tokenizer
123111 */
123112 static int porterDestroy(sqlcipher3_tokenizer *pTokenizer){
123113   sqlcipher3_free(pTokenizer);
123114   return SQLCIPHER_OK;
123115 }
123116
123117 /*
123118 ** Prepare to begin tokenizing a particular string.  The input
123119 ** string to be tokenized is zInput[0..nInput-1].  A cursor
123120 ** used to incrementally tokenize this string is returned in 
123121 ** *ppCursor.
123122 */
123123 static int porterOpen(
123124   sqlcipher3_tokenizer *pTokenizer,         /* The tokenizer */
123125   const char *zInput, int nInput,        /* String to be tokenized */
123126   sqlcipher3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
123127 ){
123128   porter_tokenizer_cursor *c;
123129
123130   UNUSED_PARAMETER(pTokenizer);
123131
123132   c = (porter_tokenizer_cursor *) sqlcipher3_malloc(sizeof(*c));
123133   if( c==NULL ) return SQLCIPHER_NOMEM;
123134
123135   c->zInput = zInput;
123136   if( zInput==0 ){
123137     c->nInput = 0;
123138   }else if( nInput<0 ){
123139     c->nInput = (int)strlen(zInput);
123140   }else{
123141     c->nInput = nInput;
123142   }
123143   c->iOffset = 0;                 /* start tokenizing at the beginning */
123144   c->iToken = 0;
123145   c->zToken = NULL;               /* no space allocated, yet. */
123146   c->nAllocated = 0;
123147
123148   *ppCursor = &c->base;
123149   return SQLCIPHER_OK;
123150 }
123151
123152 /*
123153 ** Close a tokenization cursor previously opened by a call to
123154 ** porterOpen() above.
123155 */
123156 static int porterClose(sqlcipher3_tokenizer_cursor *pCursor){
123157   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123158   sqlcipher3_free(c->zToken);
123159   sqlcipher3_free(c);
123160   return SQLCIPHER_OK;
123161 }
123162 /*
123163 ** Vowel or consonant
123164 */
123165 static const char cType[] = {
123166    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
123167    1, 1, 1, 2, 1
123168 };
123169
123170 /*
123171 ** isConsonant() and isVowel() determine if their first character in
123172 ** the string they point to is a consonant or a vowel, according
123173 ** to Porter ruls.  
123174 **
123175 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
123176 ** 'Y' is a consonant unless it follows another consonant,
123177 ** in which case it is a vowel.
123178 **
123179 ** In these routine, the letters are in reverse order.  So the 'y' rule
123180 ** is that 'y' is a consonant unless it is followed by another
123181 ** consonent.
123182 */
123183 static int isVowel(const char*);
123184 static int isConsonant(const char *z){
123185   int j;
123186   char x = *z;
123187   if( x==0 ) return 0;
123188   assert( x>='a' && x<='z' );
123189   j = cType[x-'a'];
123190   if( j<2 ) return j;
123191   return z[1]==0 || isVowel(z + 1);
123192 }
123193 static int isVowel(const char *z){
123194   int j;
123195   char x = *z;
123196   if( x==0 ) return 0;
123197   assert( x>='a' && x<='z' );
123198   j = cType[x-'a'];
123199   if( j<2 ) return 1-j;
123200   return isConsonant(z + 1);
123201 }
123202
123203 /*
123204 ** Let any sequence of one or more vowels be represented by V and let
123205 ** C be sequence of one or more consonants.  Then every word can be
123206 ** represented as:
123207 **
123208 **           [C] (VC){m} [V]
123209 **
123210 ** In prose:  A word is an optional consonant followed by zero or
123211 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
123212 ** number of vowel consonant pairs.  This routine computes the value
123213 ** of m for the first i bytes of a word.
123214 **
123215 ** Return true if the m-value for z is 1 or more.  In other words,
123216 ** return true if z contains at least one vowel that is followed
123217 ** by a consonant.
123218 **
123219 ** In this routine z[] is in reverse order.  So we are really looking
123220 ** for an instance of of a consonant followed by a vowel.
123221 */
123222 static int m_gt_0(const char *z){
123223   while( isVowel(z) ){ z++; }
123224   if( *z==0 ) return 0;
123225   while( isConsonant(z) ){ z++; }
123226   return *z!=0;
123227 }
123228
123229 /* Like mgt0 above except we are looking for a value of m which is
123230 ** exactly 1
123231 */
123232 static int m_eq_1(const char *z){
123233   while( isVowel(z) ){ z++; }
123234   if( *z==0 ) return 0;
123235   while( isConsonant(z) ){ z++; }
123236   if( *z==0 ) return 0;
123237   while( isVowel(z) ){ z++; }
123238   if( *z==0 ) return 1;
123239   while( isConsonant(z) ){ z++; }
123240   return *z==0;
123241 }
123242
123243 /* Like mgt0 above except we are looking for a value of m>1 instead
123244 ** or m>0
123245 */
123246 static int m_gt_1(const char *z){
123247   while( isVowel(z) ){ z++; }
123248   if( *z==0 ) return 0;
123249   while( isConsonant(z) ){ z++; }
123250   if( *z==0 ) return 0;
123251   while( isVowel(z) ){ z++; }
123252   if( *z==0 ) return 0;
123253   while( isConsonant(z) ){ z++; }
123254   return *z!=0;
123255 }
123256
123257 /*
123258 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
123259 */
123260 static int hasVowel(const char *z){
123261   while( isConsonant(z) ){ z++; }
123262   return *z!=0;
123263 }
123264
123265 /*
123266 ** Return TRUE if the word ends in a double consonant.
123267 **
123268 ** The text is reversed here. So we are really looking at
123269 ** the first two characters of z[].
123270 */
123271 static int doubleConsonant(const char *z){
123272   return isConsonant(z) && z[0]==z[1];
123273 }
123274
123275 /*
123276 ** Return TRUE if the word ends with three letters which
123277 ** are consonant-vowel-consonent and where the final consonant
123278 ** is not 'w', 'x', or 'y'.
123279 **
123280 ** The word is reversed here.  So we are really checking the
123281 ** first three letters and the first one cannot be in [wxy].
123282 */
123283 static int star_oh(const char *z){
123284   return
123285     isConsonant(z) &&
123286     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
123287     isVowel(z+1) &&
123288     isConsonant(z+2);
123289 }
123290
123291 /*
123292 ** If the word ends with zFrom and xCond() is true for the stem
123293 ** of the word that preceeds the zFrom ending, then change the 
123294 ** ending to zTo.
123295 **
123296 ** The input word *pz and zFrom are both in reverse order.  zTo
123297 ** is in normal order. 
123298 **
123299 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
123300 ** match.  Not that TRUE is returned even if xCond() fails and
123301 ** no substitution occurs.
123302 */
123303 static int stem(
123304   char **pz,             /* The word being stemmed (Reversed) */
123305   const char *zFrom,     /* If the ending matches this... (Reversed) */
123306   const char *zTo,       /* ... change the ending to this (not reversed) */
123307   int (*xCond)(const char*)   /* Condition that must be true */
123308 ){
123309   char *z = *pz;
123310   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
123311   if( *zFrom!=0 ) return 0;
123312   if( xCond && !xCond(z) ) return 1;
123313   while( *zTo ){
123314     *(--z) = *(zTo++);
123315   }
123316   *pz = z;
123317   return 1;
123318 }
123319
123320 /*
123321 ** This is the fallback stemmer used when the porter stemmer is
123322 ** inappropriate.  The input word is copied into the output with
123323 ** US-ASCII case folding.  If the input word is too long (more
123324 ** than 20 bytes if it contains no digits or more than 6 bytes if
123325 ** it contains digits) then word is truncated to 20 or 6 bytes
123326 ** by taking 10 or 3 bytes from the beginning and end.
123327 */
123328 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123329   int i, mx, j;
123330   int hasDigit = 0;
123331   for(i=0; i<nIn; i++){
123332     char c = zIn[i];
123333     if( c>='A' && c<='Z' ){
123334       zOut[i] = c - 'A' + 'a';
123335     }else{
123336       if( c>='0' && c<='9' ) hasDigit = 1;
123337       zOut[i] = c;
123338     }
123339   }
123340   mx = hasDigit ? 3 : 10;
123341   if( nIn>mx*2 ){
123342     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
123343       zOut[j] = zOut[i];
123344     }
123345     i = j;
123346   }
123347   zOut[i] = 0;
123348   *pnOut = i;
123349 }
123350
123351
123352 /*
123353 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
123354 ** zOut is at least big enough to hold nIn bytes.  Write the actual
123355 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
123356 **
123357 ** Any upper-case characters in the US-ASCII character set ([A-Z])
123358 ** are converted to lower case.  Upper-case UTF characters are
123359 ** unchanged.
123360 **
123361 ** Words that are longer than about 20 bytes are stemmed by retaining
123362 ** a few bytes from the beginning and the end of the word.  If the
123363 ** word contains digits, 3 bytes are taken from the beginning and
123364 ** 3 bytes from the end.  For long words without digits, 10 bytes
123365 ** are taken from each end.  US-ASCII case folding still applies.
123366 ** 
123367 ** If the input word contains not digits but does characters not 
123368 ** in [a-zA-Z] then no stemming is attempted and this routine just 
123369 ** copies the input into the input into the output with US-ASCII
123370 ** case folding.
123371 **
123372 ** Stemming never increases the length of the word.  So there is
123373 ** no chance of overflowing the zOut buffer.
123374 */
123375 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123376   int i, j;
123377   char zReverse[28];
123378   char *z, *z2;
123379   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
123380     /* The word is too big or too small for the porter stemmer.
123381     ** Fallback to the copy stemmer */
123382     copy_stemmer(zIn, nIn, zOut, pnOut);
123383     return;
123384   }
123385   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
123386     char c = zIn[i];
123387     if( c>='A' && c<='Z' ){
123388       zReverse[j] = c + 'a' - 'A';
123389     }else if( c>='a' && c<='z' ){
123390       zReverse[j] = c;
123391     }else{
123392       /* The use of a character not in [a-zA-Z] means that we fallback
123393       ** to the copy stemmer */
123394       copy_stemmer(zIn, nIn, zOut, pnOut);
123395       return;
123396     }
123397   }
123398   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
123399   z = &zReverse[j+1];
123400
123401
123402   /* Step 1a */
123403   if( z[0]=='s' ){
123404     if(
123405      !stem(&z, "sess", "ss", 0) &&
123406      !stem(&z, "sei", "i", 0)  &&
123407      !stem(&z, "ss", "ss", 0)
123408     ){
123409       z++;
123410     }
123411   }
123412
123413   /* Step 1b */  
123414   z2 = z;
123415   if( stem(&z, "dee", "ee", m_gt_0) ){
123416     /* Do nothing.  The work was all in the test */
123417   }else if( 
123418      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
123419       && z!=z2
123420   ){
123421      if( stem(&z, "ta", "ate", 0) ||
123422          stem(&z, "lb", "ble", 0) ||
123423          stem(&z, "zi", "ize", 0) ){
123424        /* Do nothing.  The work was all in the test */
123425      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
123426        z++;
123427      }else if( m_eq_1(z) && star_oh(z) ){
123428        *(--z) = 'e';
123429      }
123430   }
123431
123432   /* Step 1c */
123433   if( z[0]=='y' && hasVowel(z+1) ){
123434     z[0] = 'i';
123435   }
123436
123437   /* Step 2 */
123438   switch( z[1] ){
123439    case 'a':
123440      stem(&z, "lanoita", "ate", m_gt_0) ||
123441      stem(&z, "lanoit", "tion", m_gt_0);
123442      break;
123443    case 'c':
123444      stem(&z, "icne", "ence", m_gt_0) ||
123445      stem(&z, "icna", "ance", m_gt_0);
123446      break;
123447    case 'e':
123448      stem(&z, "rezi", "ize", m_gt_0);
123449      break;
123450    case 'g':
123451      stem(&z, "igol", "log", m_gt_0);
123452      break;
123453    case 'l':
123454      stem(&z, "ilb", "ble", m_gt_0) ||
123455      stem(&z, "illa", "al", m_gt_0) ||
123456      stem(&z, "iltne", "ent", m_gt_0) ||
123457      stem(&z, "ile", "e", m_gt_0) ||
123458      stem(&z, "ilsuo", "ous", m_gt_0);
123459      break;
123460    case 'o':
123461      stem(&z, "noitazi", "ize", m_gt_0) ||
123462      stem(&z, "noita", "ate", m_gt_0) ||
123463      stem(&z, "rota", "ate", m_gt_0);
123464      break;
123465    case 's':
123466      stem(&z, "msila", "al", m_gt_0) ||
123467      stem(&z, "ssenevi", "ive", m_gt_0) ||
123468      stem(&z, "ssenluf", "ful", m_gt_0) ||
123469      stem(&z, "ssensuo", "ous", m_gt_0);
123470      break;
123471    case 't':
123472      stem(&z, "itila", "al", m_gt_0) ||
123473      stem(&z, "itivi", "ive", m_gt_0) ||
123474      stem(&z, "itilib", "ble", m_gt_0);
123475      break;
123476   }
123477
123478   /* Step 3 */
123479   switch( z[0] ){
123480    case 'e':
123481      stem(&z, "etaci", "ic", m_gt_0) ||
123482      stem(&z, "evita", "", m_gt_0)   ||
123483      stem(&z, "ezila", "al", m_gt_0);
123484      break;
123485    case 'i':
123486      stem(&z, "itici", "ic", m_gt_0);
123487      break;
123488    case 'l':
123489      stem(&z, "laci", "ic", m_gt_0) ||
123490      stem(&z, "luf", "", m_gt_0);
123491      break;
123492    case 's':
123493      stem(&z, "ssen", "", m_gt_0);
123494      break;
123495   }
123496
123497   /* Step 4 */
123498   switch( z[1] ){
123499    case 'a':
123500      if( z[0]=='l' && m_gt_1(z+2) ){
123501        z += 2;
123502      }
123503      break;
123504    case 'c':
123505      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
123506        z += 4;
123507      }
123508      break;
123509    case 'e':
123510      if( z[0]=='r' && m_gt_1(z+2) ){
123511        z += 2;
123512      }
123513      break;
123514    case 'i':
123515      if( z[0]=='c' && m_gt_1(z+2) ){
123516        z += 2;
123517      }
123518      break;
123519    case 'l':
123520      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
123521        z += 4;
123522      }
123523      break;
123524    case 'n':
123525      if( z[0]=='t' ){
123526        if( z[2]=='a' ){
123527          if( m_gt_1(z+3) ){
123528            z += 3;
123529          }
123530        }else if( z[2]=='e' ){
123531          stem(&z, "tneme", "", m_gt_1) ||
123532          stem(&z, "tnem", "", m_gt_1) ||
123533          stem(&z, "tne", "", m_gt_1);
123534        }
123535      }
123536      break;
123537    case 'o':
123538      if( z[0]=='u' ){
123539        if( m_gt_1(z+2) ){
123540          z += 2;
123541        }
123542      }else if( z[3]=='s' || z[3]=='t' ){
123543        stem(&z, "noi", "", m_gt_1);
123544      }
123545      break;
123546    case 's':
123547      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
123548        z += 3;
123549      }
123550      break;
123551    case 't':
123552      stem(&z, "eta", "", m_gt_1) ||
123553      stem(&z, "iti", "", m_gt_1);
123554      break;
123555    case 'u':
123556      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
123557        z += 3;
123558      }
123559      break;
123560    case 'v':
123561    case 'z':
123562      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
123563        z += 3;
123564      }
123565      break;
123566   }
123567
123568   /* Step 5a */
123569   if( z[0]=='e' ){
123570     if( m_gt_1(z+1) ){
123571       z++;
123572     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
123573       z++;
123574     }
123575   }
123576
123577   /* Step 5b */
123578   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
123579     z++;
123580   }
123581
123582   /* z[] is now the stemmed word in reverse order.  Flip it back
123583   ** around into forward order and return.
123584   */
123585   *pnOut = i = (int)strlen(z);
123586   zOut[i] = 0;
123587   while( *z ){
123588     zOut[--i] = *(z++);
123589   }
123590 }
123591
123592 /*
123593 ** Characters that can be part of a token.  We assume any character
123594 ** whose value is greater than 0x80 (any UTF character) can be
123595 ** part of a token.  In other words, delimiters all must have
123596 ** values of 0x7f or lower.
123597 */
123598 static const char porterIdChar[] = {
123599 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
123600     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
123601     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
123602     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
123603     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
123604     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
123605 };
123606 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
123607
123608 /*
123609 ** Extract the next token from a tokenization cursor.  The cursor must
123610 ** have been opened by a prior call to porterOpen().
123611 */
123612 static int porterNext(
123613   sqlcipher3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
123614   const char **pzToken,               /* OUT: *pzToken is the token text */
123615   int *pnBytes,                       /* OUT: Number of bytes in token */
123616   int *piStartOffset,                 /* OUT: Starting offset of token */
123617   int *piEndOffset,                   /* OUT: Ending offset of token */
123618   int *piPosition                     /* OUT: Position integer of token */
123619 ){
123620   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123621   const char *z = c->zInput;
123622
123623   while( c->iOffset<c->nInput ){
123624     int iStartOffset, ch;
123625
123626     /* Scan past delimiter characters */
123627     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
123628       c->iOffset++;
123629     }
123630
123631     /* Count non-delimiter characters. */
123632     iStartOffset = c->iOffset;
123633     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
123634       c->iOffset++;
123635     }
123636
123637     if( c->iOffset>iStartOffset ){
123638       int n = c->iOffset-iStartOffset;
123639       if( n>c->nAllocated ){
123640         char *pNew;
123641         c->nAllocated = n+20;
123642         pNew = sqlcipher3_realloc(c->zToken, c->nAllocated);
123643         if( !pNew ) return SQLCIPHER_NOMEM;
123644         c->zToken = pNew;
123645       }
123646       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
123647       *pzToken = c->zToken;
123648       *piStartOffset = iStartOffset;
123649       *piEndOffset = c->iOffset;
123650       *piPosition = c->iToken++;
123651       return SQLCIPHER_OK;
123652     }
123653   }
123654   return SQLCIPHER_DONE;
123655 }
123656
123657 /*
123658 ** The set of routines that implement the porter-stemmer tokenizer
123659 */
123660 static const sqlcipher3_tokenizer_module porterTokenizerModule = {
123661   0,
123662   porterCreate,
123663   porterDestroy,
123664   porterOpen,
123665   porterClose,
123666   porterNext,
123667 };
123668
123669 /*
123670 ** Allocate a new porter tokenizer.  Return a pointer to the new
123671 ** tokenizer in *ppModule
123672 */
123673 SQLCIPHER_PRIVATE void sqlcipher3Fts3PorterTokenizerModule(
123674   sqlcipher3_tokenizer_module const**ppModule
123675 ){
123676   *ppModule = &porterTokenizerModule;
123677 }
123678
123679 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
123680
123681 /************** End of fts3_porter.c *****************************************/
123682 /************** Begin file fts3_tokenizer.c **********************************/
123683 /*
123684 ** 2007 June 22
123685 **
123686 ** The author disclaims copyright to this source code.  In place of
123687 ** a legal notice, here is a blessing:
123688 **
123689 **    May you do good and not evil.
123690 **    May you find forgiveness for yourself and forgive others.
123691 **    May you share freely, never taking more than you give.
123692 **
123693 ******************************************************************************
123694 **
123695 ** This is part of an SQLite module implementing full-text search.
123696 ** This particular file implements the generic tokenizer interface.
123697 */
123698
123699 /*
123700 ** The code in this file is only compiled if:
123701 **
123702 **     * The FTS3 module is being built as an extension
123703 **       (in which case SQLCIPHER_CORE is not defined), or
123704 **
123705 **     * The FTS3 module is being built into the core of
123706 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
123707 */
123708 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
123709
123710 /* #include <assert.h> */
123711 /* #include <string.h> */
123712
123713 /*
123714 ** Implementation of the SQL scalar function for accessing the underlying 
123715 ** hash table. This function may be called as follows:
123716 **
123717 **   SELECT <function-name>(<key-name>);
123718 **   SELECT <function-name>(<key-name>, <pointer>);
123719 **
123720 ** where <function-name> is the name passed as the second argument
123721 ** to the sqlcipher3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
123722 **
123723 ** If the <pointer> argument is specified, it must be a blob value
123724 ** containing a pointer to be stored as the hash data corresponding
123725 ** to the string <key-name>. If <pointer> is not specified, then
123726 ** the string <key-name> must already exist in the has table. Otherwise,
123727 ** an error is returned.
123728 **
123729 ** Whether or not the <pointer> argument is specified, the value returned
123730 ** is a blob containing the pointer stored as the hash data corresponding
123731 ** to string <key-name> (after the hash-table is updated, if applicable).
123732 */
123733 static void scalarFunc(
123734   sqlcipher3_context *context,
123735   int argc,
123736   sqlcipher3_value **argv
123737 ){
123738   Fts3Hash *pHash;
123739   void *pPtr = 0;
123740   const unsigned char *zName;
123741   int nName;
123742
123743   assert( argc==1 || argc==2 );
123744
123745   pHash = (Fts3Hash *)sqlcipher3_user_data(context);
123746
123747   zName = sqlcipher3_value_text(argv[0]);
123748   nName = sqlcipher3_value_bytes(argv[0])+1;
123749
123750   if( argc==2 ){
123751     void *pOld;
123752     int n = sqlcipher3_value_bytes(argv[1]);
123753     if( n!=sizeof(pPtr) ){
123754       sqlcipher3_result_error(context, "argument type mismatch", -1);
123755       return;
123756     }
123757     pPtr = *(void **)sqlcipher3_value_blob(argv[1]);
123758     pOld = sqlcipher3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
123759     if( pOld==pPtr ){
123760       sqlcipher3_result_error(context, "out of memory", -1);
123761       return;
123762     }
123763   }else{
123764     pPtr = sqlcipher3Fts3HashFind(pHash, zName, nName);
123765     if( !pPtr ){
123766       char *zErr = sqlcipher3_mprintf("unknown tokenizer: %s", zName);
123767       sqlcipher3_result_error(context, zErr, -1);
123768       sqlcipher3_free(zErr);
123769       return;
123770     }
123771   }
123772
123773   sqlcipher3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLCIPHER_TRANSIENT);
123774 }
123775
123776 SQLCIPHER_PRIVATE int sqlcipher3Fts3IsIdChar(char c){
123777   static const char isFtsIdChar[] = {
123778       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
123779       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
123780       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
123781       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
123782       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
123783       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
123784       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
123785       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
123786   };
123787   return (c&0x80 || isFtsIdChar[(int)(c)]);
123788 }
123789
123790 SQLCIPHER_PRIVATE const char *sqlcipher3Fts3NextToken(const char *zStr, int *pn){
123791   const char *z1;
123792   const char *z2 = 0;
123793
123794   /* Find the start of the next token. */
123795   z1 = zStr;
123796   while( z2==0 ){
123797     char c = *z1;
123798     switch( c ){
123799       case '\0': return 0;        /* No more tokens here */
123800       case '\'':
123801       case '"':
123802       case '`': {
123803         z2 = z1;
123804         while( *++z2 && (*z2!=c || *++z2==c) );
123805         break;
123806       }
123807       case '[':
123808         z2 = &z1[1];
123809         while( *z2 && z2[0]!=']' ) z2++;
123810         if( *z2 ) z2++;
123811         break;
123812
123813       default:
123814         if( sqlcipher3Fts3IsIdChar(*z1) ){
123815           z2 = &z1[1];
123816           while( sqlcipher3Fts3IsIdChar(*z2) ) z2++;
123817         }else{
123818           z1++;
123819         }
123820     }
123821   }
123822
123823   *pn = (int)(z2-z1);
123824   return z1;
123825 }
123826
123827 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitTokenizer(
123828   Fts3Hash *pHash,                /* Tokenizer hash table */
123829   const char *zArg,               /* Tokenizer name */
123830   sqlcipher3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
123831   char **pzErr                    /* OUT: Set to malloced error message */
123832 ){
123833   int rc;
123834   char *z = (char *)zArg;
123835   int n = 0;
123836   char *zCopy;
123837   char *zEnd;                     /* Pointer to nul-term of zCopy */
123838   sqlcipher3_tokenizer_module *m;
123839
123840   zCopy = sqlcipher3_mprintf("%s", zArg);
123841   if( !zCopy ) return SQLCIPHER_NOMEM;
123842   zEnd = &zCopy[strlen(zCopy)];
123843
123844   z = (char *)sqlcipher3Fts3NextToken(zCopy, &n);
123845   z[n] = '\0';
123846   sqlcipher3Fts3Dequote(z);
123847
123848   m = (sqlcipher3_tokenizer_module *)sqlcipher3Fts3HashFind(pHash,z,(int)strlen(z)+1);
123849   if( !m ){
123850     *pzErr = sqlcipher3_mprintf("unknown tokenizer: %s", z);
123851     rc = SQLCIPHER_ERROR;
123852   }else{
123853     char const **aArg = 0;
123854     int iArg = 0;
123855     z = &z[n+1];
123856     while( z<zEnd && (NULL!=(z = (char *)sqlcipher3Fts3NextToken(z, &n))) ){
123857       int nNew = sizeof(char *)*(iArg+1);
123858       char const **aNew = (const char **)sqlcipher3_realloc((void *)aArg, nNew);
123859       if( !aNew ){
123860         sqlcipher3_free(zCopy);
123861         sqlcipher3_free((void *)aArg);
123862         return SQLCIPHER_NOMEM;
123863       }
123864       aArg = aNew;
123865       aArg[iArg++] = z;
123866       z[n] = '\0';
123867       sqlcipher3Fts3Dequote(z);
123868       z = &z[n+1];
123869     }
123870     rc = m->xCreate(iArg, aArg, ppTok);
123871     assert( rc!=SQLCIPHER_OK || *ppTok );
123872     if( rc!=SQLCIPHER_OK ){
123873       *pzErr = sqlcipher3_mprintf("unknown tokenizer");
123874     }else{
123875       (*ppTok)->pModule = m; 
123876     }
123877     sqlcipher3_free((void *)aArg);
123878   }
123879
123880   sqlcipher3_free(zCopy);
123881   return rc;
123882 }
123883
123884
123885 #ifdef SQLCIPHER_TEST
123886
123887 /* #include <tcl.h> */
123888 /* #include <string.h> */
123889
123890 /*
123891 ** Implementation of a special SQL scalar function for testing tokenizers 
123892 ** designed to be used in concert with the Tcl testing framework. This
123893 ** function must be called with two arguments:
123894 **
123895 **   SELECT <function-name>(<key-name>, <input-string>);
123896 **   SELECT <function-name>(<key-name>, <pointer>);
123897 **
123898 ** where <function-name> is the name passed as the second argument
123899 ** to the sqlcipher3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
123900 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
123901 **
123902 ** The return value is a string that may be interpreted as a Tcl
123903 ** list. For each token in the <input-string>, three elements are
123904 ** added to the returned list. The first is the token position, the 
123905 ** second is the token text (folded, stemmed, etc.) and the third is the
123906 ** substring of <input-string> associated with the token. For example, 
123907 ** using the built-in "simple" tokenizer:
123908 **
123909 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
123910 **
123911 ** will return the string:
123912 **
123913 **   "{0 i I 1 dont don't 2 see see 3 how how}"
123914 **   
123915 */
123916 static void testFunc(
123917   sqlcipher3_context *context,
123918   int argc,
123919   sqlcipher3_value **argv
123920 ){
123921   Fts3Hash *pHash;
123922   sqlcipher3_tokenizer_module *p;
123923   sqlcipher3_tokenizer *pTokenizer = 0;
123924   sqlcipher3_tokenizer_cursor *pCsr = 0;
123925
123926   const char *zErr = 0;
123927
123928   const char *zName;
123929   int nName;
123930   const char *zInput;
123931   int nInput;
123932
123933   const char *zArg = 0;
123934
123935   const char *zToken;
123936   int nToken;
123937   int iStart;
123938   int iEnd;
123939   int iPos;
123940
123941   Tcl_Obj *pRet;
123942
123943   assert( argc==2 || argc==3 );
123944
123945   nName = sqlcipher3_value_bytes(argv[0]);
123946   zName = (const char *)sqlcipher3_value_text(argv[0]);
123947   nInput = sqlcipher3_value_bytes(argv[argc-1]);
123948   zInput = (const char *)sqlcipher3_value_text(argv[argc-1]);
123949
123950   if( argc==3 ){
123951     zArg = (const char *)sqlcipher3_value_text(argv[1]);
123952   }
123953
123954   pHash = (Fts3Hash *)sqlcipher3_user_data(context);
123955   p = (sqlcipher3_tokenizer_module *)sqlcipher3Fts3HashFind(pHash, zName, nName+1);
123956
123957   if( !p ){
123958     char *zErr = sqlcipher3_mprintf("unknown tokenizer: %s", zName);
123959     sqlcipher3_result_error(context, zErr, -1);
123960     sqlcipher3_free(zErr);
123961     return;
123962   }
123963
123964   pRet = Tcl_NewObj();
123965   Tcl_IncrRefCount(pRet);
123966
123967   if( SQLCIPHER_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
123968     zErr = "error in xCreate()";
123969     goto finish;
123970   }
123971   pTokenizer->pModule = p;
123972   if( SQLCIPHER_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
123973     zErr = "error in xOpen()";
123974     goto finish;
123975   }
123976   pCsr->pTokenizer = pTokenizer;
123977
123978   while( SQLCIPHER_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
123979     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
123980     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
123981     zToken = &zInput[iStart];
123982     nToken = iEnd-iStart;
123983     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
123984   }
123985
123986   if( SQLCIPHER_OK!=p->xClose(pCsr) ){
123987     zErr = "error in xClose()";
123988     goto finish;
123989   }
123990   if( SQLCIPHER_OK!=p->xDestroy(pTokenizer) ){
123991     zErr = "error in xDestroy()";
123992     goto finish;
123993   }
123994
123995 finish:
123996   if( zErr ){
123997     sqlcipher3_result_error(context, zErr, -1);
123998   }else{
123999     sqlcipher3_result_text(context, Tcl_GetString(pRet), -1, SQLCIPHER_TRANSIENT);
124000   }
124001   Tcl_DecrRefCount(pRet);
124002 }
124003
124004 static
124005 int registerTokenizer(
124006   sqlcipher3 *db, 
124007   char *zName, 
124008   const sqlcipher3_tokenizer_module *p
124009 ){
124010   int rc;
124011   sqlcipher3_stmt *pStmt;
124012   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
124013
124014   rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
124015   if( rc!=SQLCIPHER_OK ){
124016     return rc;
124017   }
124018
124019   sqlcipher3_bind_text(pStmt, 1, zName, -1, SQLCIPHER_STATIC);
124020   sqlcipher3_bind_blob(pStmt, 2, &p, sizeof(p), SQLCIPHER_STATIC);
124021   sqlcipher3_step(pStmt);
124022
124023   return sqlcipher3_finalize(pStmt);
124024 }
124025
124026 static
124027 int queryTokenizer(
124028   sqlcipher3 *db, 
124029   char *zName,  
124030   const sqlcipher3_tokenizer_module **pp
124031 ){
124032   int rc;
124033   sqlcipher3_stmt *pStmt;
124034   const char zSql[] = "SELECT fts3_tokenizer(?)";
124035
124036   *pp = 0;
124037   rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
124038   if( rc!=SQLCIPHER_OK ){
124039     return rc;
124040   }
124041
124042   sqlcipher3_bind_text(pStmt, 1, zName, -1, SQLCIPHER_STATIC);
124043   if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
124044     if( sqlcipher3_column_type(pStmt, 0)==SQLCIPHER_BLOB ){
124045       memcpy((void *)pp, sqlcipher3_column_blob(pStmt, 0), sizeof(*pp));
124046     }
124047   }
124048
124049   return sqlcipher3_finalize(pStmt);
124050 }
124051
124052 SQLCIPHER_PRIVATE void sqlcipher3Fts3SimpleTokenizerModule(sqlcipher3_tokenizer_module const**ppModule);
124053
124054 /*
124055 ** Implementation of the scalar function fts3_tokenizer_internal_test().
124056 ** This function is used for testing only, it is not included in the
124057 ** build unless SQLCIPHER_TEST is defined.
124058 **
124059 ** The purpose of this is to test that the fts3_tokenizer() function
124060 ** can be used as designed by the C-code in the queryTokenizer and
124061 ** registerTokenizer() functions above. These two functions are repeated
124062 ** in the README.tokenizer file as an example, so it is important to
124063 ** test them.
124064 **
124065 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
124066 ** function with no arguments. An assert() will fail if a problem is
124067 ** detected. i.e.:
124068 **
124069 **     SELECT fts3_tokenizer_internal_test();
124070 **
124071 */
124072 static void intTestFunc(
124073   sqlcipher3_context *context,
124074   int argc,
124075   sqlcipher3_value **argv
124076 ){
124077   int rc;
124078   const sqlcipher3_tokenizer_module *p1;
124079   const sqlcipher3_tokenizer_module *p2;
124080   sqlcipher3 *db = (sqlcipher3 *)sqlcipher3_user_data(context);
124081
124082   UNUSED_PARAMETER(argc);
124083   UNUSED_PARAMETER(argv);
124084
124085   /* Test the query function */
124086   sqlcipher3Fts3SimpleTokenizerModule(&p1);
124087   rc = queryTokenizer(db, "simple", &p2);
124088   assert( rc==SQLCIPHER_OK );
124089   assert( p1==p2 );
124090   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124091   assert( rc==SQLCIPHER_ERROR );
124092   assert( p2==0 );
124093   assert( 0==strcmp(sqlcipher3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
124094
124095   /* Test the storage function */
124096   rc = registerTokenizer(db, "nosuchtokenizer", p1);
124097   assert( rc==SQLCIPHER_OK );
124098   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124099   assert( rc==SQLCIPHER_OK );
124100   assert( p2==p1 );
124101
124102   sqlcipher3_result_text(context, "ok", -1, SQLCIPHER_STATIC);
124103 }
124104
124105 #endif
124106
124107 /*
124108 ** Set up SQL objects in database db used to access the contents of
124109 ** the hash table pointed to by argument pHash. The hash table must
124110 ** been initialised to use string keys, and to take a private copy 
124111 ** of the key when a value is inserted. i.e. by a call similar to:
124112 **
124113 **    sqlcipher3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
124114 **
124115 ** This function adds a scalar function (see header comment above
124116 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
124117 ** defined at compilation time, a temporary virtual table (see header 
124118 ** comment above struct HashTableVtab) to the database schema. Both 
124119 ** provide read/write access to the contents of *pHash.
124120 **
124121 ** The third argument to this function, zName, is used as the name
124122 ** of both the scalar and, if created, the virtual table.
124123 */
124124 SQLCIPHER_PRIVATE int sqlcipher3Fts3InitHashTable(
124125   sqlcipher3 *db, 
124126   Fts3Hash *pHash, 
124127   const char *zName
124128 ){
124129   int rc = SQLCIPHER_OK;
124130   void *p = (void *)pHash;
124131   const int any = SQLCIPHER_ANY;
124132
124133 #ifdef SQLCIPHER_TEST
124134   char *zTest = 0;
124135   char *zTest2 = 0;
124136   void *pdb = (void *)db;
124137   zTest = sqlcipher3_mprintf("%s_test", zName);
124138   zTest2 = sqlcipher3_mprintf("%s_internal_test", zName);
124139   if( !zTest || !zTest2 ){
124140     rc = SQLCIPHER_NOMEM;
124141   }
124142 #endif
124143
124144   if( SQLCIPHER_OK==rc ){
124145     rc = sqlcipher3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
124146   }
124147   if( SQLCIPHER_OK==rc ){
124148     rc = sqlcipher3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
124149   }
124150 #ifdef SQLCIPHER_TEST
124151   if( SQLCIPHER_OK==rc ){
124152     rc = sqlcipher3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
124153   }
124154   if( SQLCIPHER_OK==rc ){
124155     rc = sqlcipher3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
124156   }
124157   if( SQLCIPHER_OK==rc ){
124158     rc = sqlcipher3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
124159   }
124160 #endif
124161
124162 #ifdef SQLCIPHER_TEST
124163   sqlcipher3_free(zTest);
124164   sqlcipher3_free(zTest2);
124165 #endif
124166
124167   return rc;
124168 }
124169
124170 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
124171
124172 /************** End of fts3_tokenizer.c **************************************/
124173 /************** Begin file fts3_tokenizer1.c *********************************/
124174 /*
124175 ** 2006 Oct 10
124176 **
124177 ** The author disclaims copyright to this source code.  In place of
124178 ** a legal notice, here is a blessing:
124179 **
124180 **    May you do good and not evil.
124181 **    May you find forgiveness for yourself and forgive others.
124182 **    May you share freely, never taking more than you give.
124183 **
124184 ******************************************************************************
124185 **
124186 ** Implementation of the "simple" full-text-search tokenizer.
124187 */
124188
124189 /*
124190 ** The code in this file is only compiled if:
124191 **
124192 **     * The FTS3 module is being built as an extension
124193 **       (in which case SQLCIPHER_CORE is not defined), or
124194 **
124195 **     * The FTS3 module is being built into the core of
124196 **       SQLite (in which case SQLCIPHER_ENABLE_FTS3 is defined).
124197 */
124198 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
124199
124200 /* #include <assert.h> */
124201 /* #include <stdlib.h> */
124202 /* #include <stdio.h> */
124203 /* #include <string.h> */
124204
124205
124206 typedef struct simple_tokenizer {
124207   sqlcipher3_tokenizer base;
124208   char delim[128];             /* flag ASCII delimiters */
124209 } simple_tokenizer;
124210
124211 typedef struct simple_tokenizer_cursor {
124212   sqlcipher3_tokenizer_cursor base;
124213   const char *pInput;          /* input we are tokenizing */
124214   int nBytes;                  /* size of the input */
124215   int iOffset;                 /* current position in pInput */
124216   int iToken;                  /* index of next token to be returned */
124217   char *pToken;                /* storage for current token */
124218   int nTokenAllocated;         /* space allocated to zToken buffer */
124219 } simple_tokenizer_cursor;
124220
124221
124222 static int simpleDelim(simple_tokenizer *t, unsigned char c){
124223   return c<0x80 && t->delim[c];
124224 }
124225 static int fts3_isalnum(int x){
124226   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
124227 }
124228
124229 /*
124230 ** Create a new tokenizer instance.
124231 */
124232 static int simpleCreate(
124233   int argc, const char * const *argv,
124234   sqlcipher3_tokenizer **ppTokenizer
124235 ){
124236   simple_tokenizer *t;
124237
124238   t = (simple_tokenizer *) sqlcipher3_malloc(sizeof(*t));
124239   if( t==NULL ) return SQLCIPHER_NOMEM;
124240   memset(t, 0, sizeof(*t));
124241
124242   /* TODO(shess) Delimiters need to remain the same from run to run,
124243   ** else we need to reindex.  One solution would be a meta-table to
124244   ** track such information in the database, then we'd only want this
124245   ** information on the initial create.
124246   */
124247   if( argc>1 ){
124248     int i, n = (int)strlen(argv[1]);
124249     for(i=0; i<n; i++){
124250       unsigned char ch = argv[1][i];
124251       /* We explicitly don't support UTF-8 delimiters for now. */
124252       if( ch>=0x80 ){
124253         sqlcipher3_free(t);
124254         return SQLCIPHER_ERROR;
124255       }
124256       t->delim[ch] = 1;
124257     }
124258   } else {
124259     /* Mark non-alphanumeric ASCII characters as delimiters */
124260     int i;
124261     for(i=1; i<0x80; i++){
124262       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
124263     }
124264   }
124265
124266   *ppTokenizer = &t->base;
124267   return SQLCIPHER_OK;
124268 }
124269
124270 /*
124271 ** Destroy a tokenizer
124272 */
124273 static int simpleDestroy(sqlcipher3_tokenizer *pTokenizer){
124274   sqlcipher3_free(pTokenizer);
124275   return SQLCIPHER_OK;
124276 }
124277
124278 /*
124279 ** Prepare to begin tokenizing a particular string.  The input
124280 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
124281 ** used to incrementally tokenize this string is returned in 
124282 ** *ppCursor.
124283 */
124284 static int simpleOpen(
124285   sqlcipher3_tokenizer *pTokenizer,         /* The tokenizer */
124286   const char *pInput, int nBytes,        /* String to be tokenized */
124287   sqlcipher3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
124288 ){
124289   simple_tokenizer_cursor *c;
124290
124291   UNUSED_PARAMETER(pTokenizer);
124292
124293   c = (simple_tokenizer_cursor *) sqlcipher3_malloc(sizeof(*c));
124294   if( c==NULL ) return SQLCIPHER_NOMEM;
124295
124296   c->pInput = pInput;
124297   if( pInput==0 ){
124298     c->nBytes = 0;
124299   }else if( nBytes<0 ){
124300     c->nBytes = (int)strlen(pInput);
124301   }else{
124302     c->nBytes = nBytes;
124303   }
124304   c->iOffset = 0;                 /* start tokenizing at the beginning */
124305   c->iToken = 0;
124306   c->pToken = NULL;               /* no space allocated, yet. */
124307   c->nTokenAllocated = 0;
124308
124309   *ppCursor = &c->base;
124310   return SQLCIPHER_OK;
124311 }
124312
124313 /*
124314 ** Close a tokenization cursor previously opened by a call to
124315 ** simpleOpen() above.
124316 */
124317 static int simpleClose(sqlcipher3_tokenizer_cursor *pCursor){
124318   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124319   sqlcipher3_free(c->pToken);
124320   sqlcipher3_free(c);
124321   return SQLCIPHER_OK;
124322 }
124323
124324 /*
124325 ** Extract the next token from a tokenization cursor.  The cursor must
124326 ** have been opened by a prior call to simpleOpen().
124327 */
124328 static int simpleNext(
124329   sqlcipher3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
124330   const char **ppToken,               /* OUT: *ppToken is the token text */
124331   int *pnBytes,                       /* OUT: Number of bytes in token */
124332   int *piStartOffset,                 /* OUT: Starting offset of token */
124333   int *piEndOffset,                   /* OUT: Ending offset of token */
124334   int *piPosition                     /* OUT: Position integer of token */
124335 ){
124336   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124337   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
124338   unsigned char *p = (unsigned char *)c->pInput;
124339
124340   while( c->iOffset<c->nBytes ){
124341     int iStartOffset;
124342
124343     /* Scan past delimiter characters */
124344     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
124345       c->iOffset++;
124346     }
124347
124348     /* Count non-delimiter characters. */
124349     iStartOffset = c->iOffset;
124350     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
124351       c->iOffset++;
124352     }
124353
124354     if( c->iOffset>iStartOffset ){
124355       int i, n = c->iOffset-iStartOffset;
124356       if( n>c->nTokenAllocated ){
124357         char *pNew;
124358         c->nTokenAllocated = n+20;
124359         pNew = sqlcipher3_realloc(c->pToken, c->nTokenAllocated);
124360         if( !pNew ) return SQLCIPHER_NOMEM;
124361         c->pToken = pNew;
124362       }
124363       for(i=0; i<n; i++){
124364         /* TODO(shess) This needs expansion to handle UTF-8
124365         ** case-insensitivity.
124366         */
124367         unsigned char ch = p[iStartOffset+i];
124368         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
124369       }
124370       *ppToken = c->pToken;
124371       *pnBytes = n;
124372       *piStartOffset = iStartOffset;
124373       *piEndOffset = c->iOffset;
124374       *piPosition = c->iToken++;
124375
124376       return SQLCIPHER_OK;
124377     }
124378   }
124379   return SQLCIPHER_DONE;
124380 }
124381
124382 /*
124383 ** The set of routines that implement the simple tokenizer
124384 */
124385 static const sqlcipher3_tokenizer_module simpleTokenizerModule = {
124386   0,
124387   simpleCreate,
124388   simpleDestroy,
124389   simpleOpen,
124390   simpleClose,
124391   simpleNext,
124392 };
124393
124394 /*
124395 ** Allocate a new simple tokenizer.  Return a pointer to the new
124396 ** tokenizer in *ppModule
124397 */
124398 SQLCIPHER_PRIVATE void sqlcipher3Fts3SimpleTokenizerModule(
124399   sqlcipher3_tokenizer_module const**ppModule
124400 ){
124401   *ppModule = &simpleTokenizerModule;
124402 }
124403
124404 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
124405
124406 /************** End of fts3_tokenizer1.c *************************************/
124407 /************** Begin file fts3_write.c **************************************/
124408 /*
124409 ** 2009 Oct 23
124410 **
124411 ** The author disclaims copyright to this source code.  In place of
124412 ** a legal notice, here is a blessing:
124413 **
124414 **    May you do good and not evil.
124415 **    May you find forgiveness for yourself and forgive others.
124416 **    May you share freely, never taking more than you give.
124417 **
124418 ******************************************************************************
124419 **
124420 ** This file is part of the SQLite FTS3 extension module. Specifically,
124421 ** this file contains code to insert, update and delete rows from FTS3
124422 ** tables. It also contains code to merge FTS3 b-tree segments. Some
124423 ** of the sub-routines used to merge segments are also used by the query 
124424 ** code in fts3.c.
124425 */
124426
124427 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
124428
124429 /* #include <string.h> */
124430 /* #include <assert.h> */
124431 /* #include <stdlib.h> */
124432
124433 /*
124434 ** When full-text index nodes are loaded from disk, the buffer that they
124435 ** are loaded into has the following number of bytes of padding at the end 
124436 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
124437 ** of 920 bytes is allocated for it.
124438 **
124439 ** This means that if we have a pointer into a buffer containing node data,
124440 ** it is always safe to read up to two varints from it without risking an
124441 ** overread, even if the node data is corrupted.
124442 */
124443 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
124444
124445 /*
124446 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
124447 ** memory incrementally instead of all at once. This can be a big performance
124448 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
124449 ** method before retrieving all query results (as may happen, for example,
124450 ** if a query has a LIMIT clause).
124451 **
124452 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
124453 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
124454 ** The code is written so that the hard lower-limit for each of these values 
124455 ** is 1. Clearly such small values would be inefficient, but can be useful 
124456 ** for testing purposes.
124457 **
124458 ** If this module is built with SQLCIPHER_TEST defined, these constants may
124459 ** be overridden at runtime for testing purposes. File fts3_test.c contains
124460 ** a Tcl interface to read and write the values.
124461 */
124462 #ifdef SQLCIPHER_TEST
124463 int test_fts3_node_chunksize = (4*1024);
124464 int test_fts3_node_chunk_threshold = (4*1024)*4;
124465 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
124466 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
124467 #else
124468 # define FTS3_NODE_CHUNKSIZE (4*1024) 
124469 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
124470 #endif
124471
124472 typedef struct PendingList PendingList;
124473 typedef struct SegmentNode SegmentNode;
124474 typedef struct SegmentWriter SegmentWriter;
124475
124476 /*
124477 ** An instance of the following data structure is used to build doclists
124478 ** incrementally. See function fts3PendingListAppend() for details.
124479 */
124480 struct PendingList {
124481   int nData;
124482   char *aData;
124483   int nSpace;
124484   sqlcipher3_int64 iLastDocid;
124485   sqlcipher3_int64 iLastCol;
124486   sqlcipher3_int64 iLastPos;
124487 };
124488
124489
124490 /*
124491 ** Each cursor has a (possibly empty) linked list of the following objects.
124492 */
124493 struct Fts3DeferredToken {
124494   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
124495   int iCol;                       /* Column token must occur in */
124496   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
124497   PendingList *pList;             /* Doclist is assembled here */
124498 };
124499
124500 /*
124501 ** An instance of this structure is used to iterate through the terms on
124502 ** a contiguous set of segment b-tree leaf nodes. Although the details of
124503 ** this structure are only manipulated by code in this file, opaque handles
124504 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
124505 ** terms when querying the full-text index. See functions:
124506 **
124507 **   sqlcipher3Fts3SegReaderNew()
124508 **   sqlcipher3Fts3SegReaderFree()
124509 **   sqlcipher3Fts3SegReaderIterate()
124510 **
124511 ** Methods used to manipulate Fts3SegReader structures:
124512 **
124513 **   fts3SegReaderNext()
124514 **   fts3SegReaderFirstDocid()
124515 **   fts3SegReaderNextDocid()
124516 */
124517 struct Fts3SegReader {
124518   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
124519
124520   sqlcipher3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
124521   sqlcipher3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
124522   sqlcipher3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
124523   sqlcipher3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
124524
124525   char *aNode;                    /* Pointer to node data (or NULL) */
124526   int nNode;                      /* Size of buffer at aNode (or 0) */
124527   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
124528   sqlcipher3_blob *pBlob;            /* If not NULL, blob handle to read node */
124529
124530   Fts3HashElem **ppNextElem;
124531
124532   /* Variables set by fts3SegReaderNext(). These may be read directly
124533   ** by the caller. They are valid from the time SegmentReaderNew() returns
124534   ** until SegmentReaderNext() returns something other than SQLCIPHER_OK
124535   ** (i.e. SQLCIPHER_DONE).
124536   */
124537   int nTerm;                      /* Number of bytes in current term */
124538   char *zTerm;                    /* Pointer to current term */
124539   int nTermAlloc;                 /* Allocated size of zTerm buffer */
124540   char *aDoclist;                 /* Pointer to doclist of current entry */
124541   int nDoclist;                   /* Size of doclist in current entry */
124542
124543   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
124544   ** through the current doclist (aDoclist/nDoclist).
124545   */
124546   char *pOffsetList;
124547   int nOffsetList;                /* For descending pending seg-readers only */
124548   sqlcipher3_int64 iDocid;
124549 };
124550
124551 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
124552 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
124553
124554 /*
124555 ** An instance of this structure is used to create a segment b-tree in the
124556 ** database. The internal details of this type are only accessed by the
124557 ** following functions:
124558 **
124559 **   fts3SegWriterAdd()
124560 **   fts3SegWriterFlush()
124561 **   fts3SegWriterFree()
124562 */
124563 struct SegmentWriter {
124564   SegmentNode *pTree;             /* Pointer to interior tree structure */
124565   sqlcipher3_int64 iFirst;           /* First slot in %_segments written */
124566   sqlcipher3_int64 iFree;            /* Next free slot in %_segments */
124567   char *zTerm;                    /* Pointer to previous term buffer */
124568   int nTerm;                      /* Number of bytes in zTerm */
124569   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
124570   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
124571   int nSize;                      /* Size of allocation at aData */
124572   int nData;                      /* Bytes of data in aData */
124573   char *aData;                    /* Pointer to block from malloc() */
124574 };
124575
124576 /*
124577 ** Type SegmentNode is used by the following three functions to create
124578 ** the interior part of the segment b+-tree structures (everything except
124579 ** the leaf nodes). These functions and type are only ever used by code
124580 ** within the fts3SegWriterXXX() family of functions described above.
124581 **
124582 **   fts3NodeAddTerm()
124583 **   fts3NodeWrite()
124584 **   fts3NodeFree()
124585 **
124586 ** When a b+tree is written to the database (either as a result of a merge
124587 ** or the pending-terms table being flushed), leaves are written into the 
124588 ** database file as soon as they are completely populated. The interior of
124589 ** the tree is assembled in memory and written out only once all leaves have
124590 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
124591 ** very large, meaning that the interior of the tree consumes relatively 
124592 ** little memory.
124593 */
124594 struct SegmentNode {
124595   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
124596   SegmentNode *pRight;            /* Pointer to right-sibling */
124597   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
124598   int nEntry;                     /* Number of terms written to node so far */
124599   char *zTerm;                    /* Pointer to previous term buffer */
124600   int nTerm;                      /* Number of bytes in zTerm */
124601   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
124602   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
124603   int nData;                      /* Bytes of valid data so far */
124604   char *aData;                    /* Node data */
124605 };
124606
124607 /*
124608 ** Valid values for the second argument to fts3SqlStmt().
124609 */
124610 #define SQL_DELETE_CONTENT             0
124611 #define SQL_IS_EMPTY                   1
124612 #define SQL_DELETE_ALL_CONTENT         2 
124613 #define SQL_DELETE_ALL_SEGMENTS        3
124614 #define SQL_DELETE_ALL_SEGDIR          4
124615 #define SQL_DELETE_ALL_DOCSIZE         5
124616 #define SQL_DELETE_ALL_STAT            6
124617 #define SQL_SELECT_CONTENT_BY_ROWID    7
124618 #define SQL_NEXT_SEGMENT_INDEX         8
124619 #define SQL_INSERT_SEGMENTS            9
124620 #define SQL_NEXT_SEGMENTS_ID          10
124621 #define SQL_INSERT_SEGDIR             11
124622 #define SQL_SELECT_LEVEL              12
124623 #define SQL_SELECT_LEVEL_RANGE        13
124624 #define SQL_SELECT_LEVEL_COUNT        14
124625 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
124626 #define SQL_DELETE_SEGDIR_LEVEL       16
124627 #define SQL_DELETE_SEGMENTS_RANGE     17
124628 #define SQL_CONTENT_INSERT            18
124629 #define SQL_DELETE_DOCSIZE            19
124630 #define SQL_REPLACE_DOCSIZE           20
124631 #define SQL_SELECT_DOCSIZE            21
124632 #define SQL_SELECT_DOCTOTAL           22
124633 #define SQL_REPLACE_DOCTOTAL          23
124634
124635 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
124636 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
124637
124638 #define SQL_DELETE_SEGDIR_RANGE       26
124639
124640 /*
124641 ** This function is used to obtain an SQLite prepared statement handle
124642 ** for the statement identified by the second argument. If successful,
124643 ** *pp is set to the requested statement handle and SQLCIPHER_OK returned.
124644 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
124645 **
124646 ** If argument apVal is not NULL, then it must point to an array with
124647 ** at least as many entries as the requested statement has bound 
124648 ** parameters. The values are bound to the statements parameters before
124649 ** returning.
124650 */
124651 static int fts3SqlStmt(
124652   Fts3Table *p,                   /* Virtual table handle */
124653   int eStmt,                      /* One of the SQL_XXX constants above */
124654   sqlcipher3_stmt **pp,              /* OUT: Statement handle */
124655   sqlcipher3_value **apVal           /* Values to bind to statement */
124656 ){
124657   const char *azSql[] = {
124658 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
124659 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
124660 /* 2  */  "DELETE FROM %Q.'%q_content'",
124661 /* 3  */  "DELETE FROM %Q.'%q_segments'",
124662 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
124663 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
124664 /* 6  */  "DELETE FROM %Q.'%q_stat'",
124665 /* 7  */  "SELECT %s WHERE rowid=?",
124666 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
124667 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
124668 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
124669 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
124670
124671           /* Return segments in order from oldest to newest.*/ 
124672 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124673             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
124674 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
124675             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
124676             "ORDER BY level DESC, idx ASC",
124677
124678 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
124679 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
124680
124681 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
124682 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
124683 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
124684 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
124685 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
124686 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
124687 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
124688 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
124689 /* 24 */  "",
124690 /* 25 */  "",
124691
124692 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
124693
124694   };
124695   int rc = SQLCIPHER_OK;
124696   sqlcipher3_stmt *pStmt;
124697
124698   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
124699   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
124700   
124701   pStmt = p->aStmt[eStmt];
124702   if( !pStmt ){
124703     char *zSql;
124704     if( eStmt==SQL_CONTENT_INSERT ){
124705       zSql = sqlcipher3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
124706     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
124707       zSql = sqlcipher3_mprintf(azSql[eStmt], p->zReadExprlist);
124708     }else{
124709       zSql = sqlcipher3_mprintf(azSql[eStmt], p->zDb, p->zName);
124710     }
124711     if( !zSql ){
124712       rc = SQLCIPHER_NOMEM;
124713     }else{
124714       rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
124715       sqlcipher3_free(zSql);
124716       assert( rc==SQLCIPHER_OK || pStmt==0 );
124717       p->aStmt[eStmt] = pStmt;
124718     }
124719   }
124720   if( apVal ){
124721     int i;
124722     int nParam = sqlcipher3_bind_parameter_count(pStmt);
124723     for(i=0; rc==SQLCIPHER_OK && i<nParam; i++){
124724       rc = sqlcipher3_bind_value(pStmt, i+1, apVal[i]);
124725     }
124726   }
124727   *pp = pStmt;
124728   return rc;
124729 }
124730
124731 static int fts3SelectDocsize(
124732   Fts3Table *pTab,                /* FTS3 table handle */
124733   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
124734   sqlcipher3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
124735   sqlcipher3_stmt **ppStmt           /* OUT: Statement handle */
124736 ){
124737   sqlcipher3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
124738   int rc;                         /* Return code */
124739
124740   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
124741
124742   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
124743   if( rc==SQLCIPHER_OK ){
124744     if( eStmt==SQL_SELECT_DOCSIZE ){
124745       sqlcipher3_bind_int64(pStmt, 1, iDocid);
124746     }
124747     rc = sqlcipher3_step(pStmt);
124748     if( rc!=SQLCIPHER_ROW || sqlcipher3_column_type(pStmt, 0)!=SQLCIPHER_BLOB ){
124749       rc = sqlcipher3_reset(pStmt);
124750       if( rc==SQLCIPHER_OK ) rc = FTS_CORRUPT_VTAB;
124751       pStmt = 0;
124752     }else{
124753       rc = SQLCIPHER_OK;
124754     }
124755   }
124756
124757   *ppStmt = pStmt;
124758   return rc;
124759 }
124760
124761 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDoctotal(
124762   Fts3Table *pTab,                /* Fts3 table handle */
124763   sqlcipher3_stmt **ppStmt           /* OUT: Statement handle */
124764 ){
124765   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
124766 }
124767
124768 SQLCIPHER_PRIVATE int sqlcipher3Fts3SelectDocsize(
124769   Fts3Table *pTab,                /* Fts3 table handle */
124770   sqlcipher3_int64 iDocid,           /* Docid to read size data for */
124771   sqlcipher3_stmt **ppStmt           /* OUT: Statement handle */
124772 ){
124773   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
124774 }
124775
124776 /*
124777 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
124778 ** array apVal[] to the SQL statement identified by eStmt, the statement
124779 ** is executed.
124780 **
124781 ** Returns SQLCIPHER_OK if the statement is successfully executed, or an
124782 ** SQLite error code otherwise.
124783 */
124784 static void fts3SqlExec(
124785   int *pRC,                /* Result code */
124786   Fts3Table *p,            /* The FTS3 table */
124787   int eStmt,               /* Index of statement to evaluate */
124788   sqlcipher3_value **apVal    /* Parameters to bind */
124789 ){
124790   sqlcipher3_stmt *pStmt;
124791   int rc;
124792   if( *pRC ) return;
124793   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
124794   if( rc==SQLCIPHER_OK ){
124795     sqlcipher3_step(pStmt);
124796     rc = sqlcipher3_reset(pStmt);
124797   }
124798   *pRC = rc;
124799 }
124800
124801
124802 /*
124803 ** This function ensures that the caller has obtained a shared-cache
124804 ** table-lock on the %_content table. This is required before reading
124805 ** data from the fts3 table. If this lock is not acquired first, then
124806 ** the caller may end up holding read-locks on the %_segments and %_segdir
124807 ** tables, but no read-lock on the %_content table. If this happens 
124808 ** a second connection will be able to write to the fts3 table, but
124809 ** attempting to commit those writes might return SQLCIPHER_LOCKED or
124810 ** SQLCIPHER_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
124811 ** write-locks on the %_segments and %_segdir ** tables). 
124812 **
124813 ** We try to avoid this because if FTS3 returns any error when committing
124814 ** a transaction, the whole transaction will be rolled back. And this is
124815 ** not what users expect when they get SQLCIPHER_LOCKED_SHAREDCACHE. It can
124816 ** still happen if the user reads data directly from the %_segments or
124817 ** %_segdir tables instead of going through FTS3 though.
124818 **
124819 ** This reasoning does not apply to a content=xxx table.
124820 */
124821 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadLock(Fts3Table *p){
124822   int rc;                         /* Return code */
124823   sqlcipher3_stmt *pStmt;            /* Statement used to obtain lock */
124824
124825   if( p->zContentTbl==0 ){
124826     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
124827     if( rc==SQLCIPHER_OK ){
124828       sqlcipher3_bind_null(pStmt, 1);
124829       sqlcipher3_step(pStmt);
124830       rc = sqlcipher3_reset(pStmt);
124831     }
124832   }else{
124833     rc = SQLCIPHER_OK;
124834   }
124835
124836   return rc;
124837 }
124838
124839 /*
124840 ** Set *ppStmt to a statement handle that may be used to iterate through
124841 ** all rows in the %_segdir table, from oldest to newest. If successful,
124842 ** return SQLCIPHER_OK. If an error occurs while preparing the statement, 
124843 ** return an SQLite error code.
124844 **
124845 ** There is only ever one instance of this SQL statement compiled for
124846 ** each FTS3 table.
124847 **
124848 ** The statement returns the following columns from the %_segdir table:
124849 **
124850 **   0: idx
124851 **   1: start_block
124852 **   2: leaves_end_block
124853 **   3: end_block
124854 **   4: root
124855 */
124856 SQLCIPHER_PRIVATE int sqlcipher3Fts3AllSegdirs(
124857   Fts3Table *p,                   /* FTS3 table */
124858   int iIndex,                     /* Index for p->aIndex[] */
124859   int iLevel,                     /* Level to select */
124860   sqlcipher3_stmt **ppStmt           /* OUT: Compiled statement */
124861 ){
124862   int rc;
124863   sqlcipher3_stmt *pStmt = 0;
124864
124865   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
124866   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
124867   assert( iIndex>=0 && iIndex<p->nIndex );
124868
124869   if( iLevel<0 ){
124870     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
124871     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
124872     if( rc==SQLCIPHER_OK ){ 
124873       sqlcipher3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
124874       sqlcipher3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL-1);
124875     }
124876   }else{
124877     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
124878     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
124879     if( rc==SQLCIPHER_OK ){ 
124880       sqlcipher3_bind_int(pStmt, 1, iLevel+iIndex*FTS3_SEGDIR_MAXLEVEL);
124881     }
124882   }
124883   *ppStmt = pStmt;
124884   return rc;
124885 }
124886
124887
124888 /*
124889 ** Append a single varint to a PendingList buffer. SQLCIPHER_OK is returned
124890 ** if successful, or an SQLite error code otherwise.
124891 **
124892 ** This function also serves to allocate the PendingList structure itself.
124893 ** For example, to create a new PendingList structure containing two
124894 ** varints:
124895 **
124896 **   PendingList *p = 0;
124897 **   fts3PendingListAppendVarint(&p, 1);
124898 **   fts3PendingListAppendVarint(&p, 2);
124899 */
124900 static int fts3PendingListAppendVarint(
124901   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
124902   sqlcipher3_int64 i                 /* Value to append to data */
124903 ){
124904   PendingList *p = *pp;
124905
124906   /* Allocate or grow the PendingList as required. */
124907   if( !p ){
124908     p = sqlcipher3_malloc(sizeof(*p) + 100);
124909     if( !p ){
124910       return SQLCIPHER_NOMEM;
124911     }
124912     p->nSpace = 100;
124913     p->aData = (char *)&p[1];
124914     p->nData = 0;
124915   }
124916   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
124917     int nNew = p->nSpace * 2;
124918     p = sqlcipher3_realloc(p, sizeof(*p) + nNew);
124919     if( !p ){
124920       sqlcipher3_free(*pp);
124921       *pp = 0;
124922       return SQLCIPHER_NOMEM;
124923     }
124924     p->nSpace = nNew;
124925     p->aData = (char *)&p[1];
124926   }
124927
124928   /* Append the new serialized varint to the end of the list. */
124929   p->nData += sqlcipher3Fts3PutVarint(&p->aData[p->nData], i);
124930   p->aData[p->nData] = '\0';
124931   *pp = p;
124932   return SQLCIPHER_OK;
124933 }
124934
124935 /*
124936 ** Add a docid/column/position entry to a PendingList structure. Non-zero
124937 ** is returned if the structure is sqlcipher3_realloced as part of adding
124938 ** the entry. Otherwise, zero.
124939 **
124940 ** If an OOM error occurs, *pRc is set to SQLCIPHER_NOMEM before returning.
124941 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
124942 ** it is set to SQLCIPHER_OK.
124943 */
124944 static int fts3PendingListAppend(
124945   PendingList **pp,               /* IN/OUT: PendingList structure */
124946   sqlcipher3_int64 iDocid,           /* Docid for entry to add */
124947   sqlcipher3_int64 iCol,             /* Column for entry to add */
124948   sqlcipher3_int64 iPos,             /* Position of term for entry to add */
124949   int *pRc                        /* OUT: Return code */
124950 ){
124951   PendingList *p = *pp;
124952   int rc = SQLCIPHER_OK;
124953
124954   assert( !p || p->iLastDocid<=iDocid );
124955
124956   if( !p || p->iLastDocid!=iDocid ){
124957     sqlcipher3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
124958     if( p ){
124959       assert( p->nData<p->nSpace );
124960       assert( p->aData[p->nData]==0 );
124961       p->nData++;
124962     }
124963     if( SQLCIPHER_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
124964       goto pendinglistappend_out;
124965     }
124966     p->iLastCol = -1;
124967     p->iLastPos = 0;
124968     p->iLastDocid = iDocid;
124969   }
124970   if( iCol>0 && p->iLastCol!=iCol ){
124971     if( SQLCIPHER_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
124972      || SQLCIPHER_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
124973     ){
124974       goto pendinglistappend_out;
124975     }
124976     p->iLastCol = iCol;
124977     p->iLastPos = 0;
124978   }
124979   if( iCol>=0 ){
124980     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
124981     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
124982     if( rc==SQLCIPHER_OK ){
124983       p->iLastPos = iPos;
124984     }
124985   }
124986
124987  pendinglistappend_out:
124988   *pRc = rc;
124989   if( p!=*pp ){
124990     *pp = p;
124991     return 1;
124992   }
124993   return 0;
124994 }
124995
124996 /*
124997 ** Free a PendingList object allocated by fts3PendingListAppend().
124998 */
124999 static void fts3PendingListDelete(PendingList *pList){
125000   sqlcipher3_free(pList);
125001 }
125002
125003 /*
125004 ** Add an entry to one of the pending-terms hash tables.
125005 */
125006 static int fts3PendingTermsAddOne(
125007   Fts3Table *p,
125008   int iCol,
125009   int iPos,
125010   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
125011   const char *zToken,
125012   int nToken
125013 ){
125014   PendingList *pList;
125015   int rc = SQLCIPHER_OK;
125016
125017   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
125018   if( pList ){
125019     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
125020   }
125021   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
125022     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
125023       /* Malloc failed while inserting the new entry. This can only 
125024       ** happen if there was no previous entry for this token.
125025       */
125026       assert( 0==fts3HashFind(pHash, zToken, nToken) );
125027       sqlcipher3_free(pList);
125028       rc = SQLCIPHER_NOMEM;
125029     }
125030   }
125031   if( rc==SQLCIPHER_OK ){
125032     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
125033   }
125034   return rc;
125035 }
125036
125037 /*
125038 ** Tokenize the nul-terminated string zText and add all tokens to the
125039 ** pending-terms hash-table. The docid used is that currently stored in
125040 ** p->iPrevDocid, and the column is specified by argument iCol.
125041 **
125042 ** If successful, SQLCIPHER_OK is returned. Otherwise, an SQLite error code.
125043 */
125044 static int fts3PendingTermsAdd(
125045   Fts3Table *p,                   /* Table into which text will be inserted */
125046   const char *zText,              /* Text of document to be inserted */
125047   int iCol,                       /* Column into which text is being inserted */
125048   u32 *pnWord                     /* OUT: Number of tokens inserted */
125049 ){
125050   int rc;
125051   int iStart;
125052   int iEnd;
125053   int iPos;
125054   int nWord = 0;
125055
125056   char const *zToken;
125057   int nToken;
125058
125059   sqlcipher3_tokenizer *pTokenizer = p->pTokenizer;
125060   sqlcipher3_tokenizer_module const *pModule = pTokenizer->pModule;
125061   sqlcipher3_tokenizer_cursor *pCsr;
125062   int (*xNext)(sqlcipher3_tokenizer_cursor *pCursor,
125063       const char**,int*,int*,int*,int*);
125064
125065   assert( pTokenizer && pModule );
125066
125067   /* If the user has inserted a NULL value, this function may be called with
125068   ** zText==0. In this case, add zero token entries to the hash table and 
125069   ** return early. */
125070   if( zText==0 ){
125071     *pnWord = 0;
125072     return SQLCIPHER_OK;
125073   }
125074
125075   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
125076   if( rc!=SQLCIPHER_OK ){
125077     return rc;
125078   }
125079   pCsr->pTokenizer = pTokenizer;
125080
125081   xNext = pModule->xNext;
125082   while( SQLCIPHER_OK==rc
125083       && SQLCIPHER_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
125084   ){
125085     int i;
125086     if( iPos>=nWord ) nWord = iPos+1;
125087
125088     /* Positions cannot be negative; we use -1 as a terminator internally.
125089     ** Tokens must have a non-zero length.
125090     */
125091     if( iPos<0 || !zToken || nToken<=0 ){
125092       rc = SQLCIPHER_ERROR;
125093       break;
125094     }
125095
125096     /* Add the term to the terms index */
125097     rc = fts3PendingTermsAddOne(
125098         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
125099     );
125100     
125101     /* Add the term to each of the prefix indexes that it is not too 
125102     ** short for. */
125103     for(i=1; rc==SQLCIPHER_OK && i<p->nIndex; i++){
125104       struct Fts3Index *pIndex = &p->aIndex[i];
125105       if( nToken<pIndex->nPrefix ) continue;
125106       rc = fts3PendingTermsAddOne(
125107           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
125108       );
125109     }
125110   }
125111
125112   pModule->xClose(pCsr);
125113   *pnWord = nWord;
125114   return (rc==SQLCIPHER_DONE ? SQLCIPHER_OK : rc);
125115 }
125116
125117 /* 
125118 ** Calling this function indicates that subsequent calls to 
125119 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
125120 ** contents of the document with docid iDocid.
125121 */
125122 static int fts3PendingTermsDocid(Fts3Table *p, sqlcipher_int64 iDocid){
125123   /* TODO(shess) Explore whether partially flushing the buffer on
125124   ** forced-flush would provide better performance.  I suspect that if
125125   ** we ordered the doclists by size and flushed the largest until the
125126   ** buffer was half empty, that would let the less frequent terms
125127   ** generate longer doclists.
125128   */
125129   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
125130     int rc = sqlcipher3Fts3PendingTermsFlush(p);
125131     if( rc!=SQLCIPHER_OK ) return rc;
125132   }
125133   p->iPrevDocid = iDocid;
125134   return SQLCIPHER_OK;
125135 }
125136
125137 /*
125138 ** Discard the contents of the pending-terms hash tables. 
125139 */
125140 SQLCIPHER_PRIVATE void sqlcipher3Fts3PendingTermsClear(Fts3Table *p){
125141   int i;
125142   for(i=0; i<p->nIndex; i++){
125143     Fts3HashElem *pElem;
125144     Fts3Hash *pHash = &p->aIndex[i].hPending;
125145     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
125146       PendingList *pList = (PendingList *)fts3HashData(pElem);
125147       fts3PendingListDelete(pList);
125148     }
125149     fts3HashClear(pHash);
125150   }
125151   p->nPendingData = 0;
125152 }
125153
125154 /*
125155 ** This function is called by the xUpdate() method as part of an INSERT
125156 ** operation. It adds entries for each term in the new record to the
125157 ** pendingTerms hash table.
125158 **
125159 ** Argument apVal is the same as the similarly named argument passed to
125160 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
125161 */
125162 static int fts3InsertTerms(Fts3Table *p, sqlcipher3_value **apVal, u32 *aSz){
125163   int i;                          /* Iterator variable */
125164   for(i=2; i<p->nColumn+2; i++){
125165     const char *zText = (const char *)sqlcipher3_value_text(apVal[i]);
125166     int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
125167     if( rc!=SQLCIPHER_OK ){
125168       return rc;
125169     }
125170     aSz[p->nColumn] += sqlcipher3_value_bytes(apVal[i]);
125171   }
125172   return SQLCIPHER_OK;
125173 }
125174
125175 /*
125176 ** This function is called by the xUpdate() method for an INSERT operation.
125177 ** The apVal parameter is passed a copy of the apVal argument passed by
125178 ** SQLite to the xUpdate() method. i.e:
125179 **
125180 **   apVal[0]                Not used for INSERT.
125181 **   apVal[1]                rowid
125182 **   apVal[2]                Left-most user-defined column
125183 **   ...
125184 **   apVal[p->nColumn+1]     Right-most user-defined column
125185 **   apVal[p->nColumn+2]     Hidden column with same name as table
125186 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
125187 */
125188 static int fts3InsertData(
125189   Fts3Table *p,                   /* Full-text table */
125190   sqlcipher3_value **apVal,          /* Array of values to insert */
125191   sqlcipher3_int64 *piDocid          /* OUT: Docid for row just inserted */
125192 ){
125193   int rc;                         /* Return code */
125194   sqlcipher3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
125195
125196   if( p->zContentTbl ){
125197     sqlcipher3_value *pRowid = apVal[p->nColumn+3];
125198     if( sqlcipher3_value_type(pRowid)==SQLCIPHER_NULL ){
125199       pRowid = apVal[1];
125200     }
125201     if( sqlcipher3_value_type(pRowid)!=SQLCIPHER_INTEGER ){
125202       return SQLCIPHER_CONSTRAINT;
125203     }
125204     *piDocid = sqlcipher3_value_int64(pRowid);
125205     return SQLCIPHER_OK;
125206   }
125207
125208   /* Locate the statement handle used to insert data into the %_content
125209   ** table. The SQL for this statement is:
125210   **
125211   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
125212   **
125213   ** The statement features N '?' variables, where N is the number of user
125214   ** defined columns in the FTS3 table, plus one for the docid field.
125215   */
125216   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
125217   if( rc!=SQLCIPHER_OK ){
125218     return rc;
125219   }
125220
125221   /* There is a quirk here. The users INSERT statement may have specified
125222   ** a value for the "rowid" field, for the "docid" field, or for both.
125223   ** Which is a problem, since "rowid" and "docid" are aliases for the
125224   ** same value. For example:
125225   **
125226   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
125227   **
125228   ** In FTS3, this is an error. It is an error to specify non-NULL values
125229   ** for both docid and some other rowid alias.
125230   */
125231   if( SQLCIPHER_NULL!=sqlcipher3_value_type(apVal[3+p->nColumn]) ){
125232     if( SQLCIPHER_NULL==sqlcipher3_value_type(apVal[0])
125233      && SQLCIPHER_NULL!=sqlcipher3_value_type(apVal[1])
125234     ){
125235       /* A rowid/docid conflict. */
125236       return SQLCIPHER_ERROR;
125237     }
125238     rc = sqlcipher3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
125239     if( rc!=SQLCIPHER_OK ) return rc;
125240   }
125241
125242   /* Execute the statement to insert the record. Set *piDocid to the 
125243   ** new docid value. 
125244   */
125245   sqlcipher3_step(pContentInsert);
125246   rc = sqlcipher3_reset(pContentInsert);
125247
125248   *piDocid = sqlcipher3_last_insert_rowid(p->db);
125249   return rc;
125250 }
125251
125252
125253
125254 /*
125255 ** Remove all data from the FTS3 table. Clear the hash table containing
125256 ** pending terms.
125257 */
125258 static int fts3DeleteAll(Fts3Table *p, int bContent){
125259   int rc = SQLCIPHER_OK;             /* Return code */
125260
125261   /* Discard the contents of the pending-terms hash table. */
125262   sqlcipher3Fts3PendingTermsClear(p);
125263
125264   /* Delete everything from the shadow tables. Except, leave %_content as
125265   ** is if bContent is false.  */
125266   assert( p->zContentTbl==0 || bContent==0 );
125267   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
125268   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
125269   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
125270   if( p->bHasDocsize ){
125271     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
125272   }
125273   if( p->bHasStat ){
125274     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
125275   }
125276   return rc;
125277 }
125278
125279 /*
125280 ** The first element in the apVal[] array is assumed to contain the docid
125281 ** (an integer) of a row about to be deleted. Remove all terms from the
125282 ** full-text index.
125283 */
125284 static void fts3DeleteTerms( 
125285   int *pRC,               /* Result code */
125286   Fts3Table *p,           /* The FTS table to delete from */
125287   sqlcipher3_value *pRowid,  /* The docid to be deleted */
125288   u32 *aSz                /* Sizes of deleted document written here */
125289 ){
125290   int rc;
125291   sqlcipher3_stmt *pSelect;
125292
125293   if( *pRC ) return;
125294   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
125295   if( rc==SQLCIPHER_OK ){
125296     if( SQLCIPHER_ROW==sqlcipher3_step(pSelect) ){
125297       int i;
125298       for(i=1; i<=p->nColumn; i++){
125299         const char *zText = (const char *)sqlcipher3_column_text(pSelect, i);
125300         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
125301         if( rc!=SQLCIPHER_OK ){
125302           sqlcipher3_reset(pSelect);
125303           *pRC = rc;
125304           return;
125305         }
125306         aSz[p->nColumn] += sqlcipher3_column_bytes(pSelect, i);
125307       }
125308     }
125309     rc = sqlcipher3_reset(pSelect);
125310   }else{
125311     sqlcipher3_reset(pSelect);
125312   }
125313   *pRC = rc;
125314 }
125315
125316 /*
125317 ** Forward declaration to account for the circular dependency between
125318 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
125319 */
125320 static int fts3SegmentMerge(Fts3Table *, int, int);
125321
125322 /* 
125323 ** This function allocates a new level iLevel index in the segdir table.
125324 ** Usually, indexes are allocated within a level sequentially starting
125325 ** with 0, so the allocated index is one greater than the value returned
125326 ** by:
125327 **
125328 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
125329 **
125330 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
125331 ** level, they are merged into a single level (iLevel+1) segment and the 
125332 ** allocated index is 0.
125333 **
125334 ** If successful, *piIdx is set to the allocated index slot and SQLCIPHER_OK
125335 ** returned. Otherwise, an SQLite error code is returned.
125336 */
125337 static int fts3AllocateSegdirIdx(
125338   Fts3Table *p, 
125339   int iIndex,                     /* Index for p->aIndex */
125340   int iLevel, 
125341   int *piIdx
125342 ){
125343   int rc;                         /* Return Code */
125344   sqlcipher3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
125345   int iNext = 0;                  /* Result of query pNextIdx */
125346
125347   /* Set variable iNext to the next available segdir index at level iLevel. */
125348   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
125349   if( rc==SQLCIPHER_OK ){
125350     sqlcipher3_bind_int(pNextIdx, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
125351     if( SQLCIPHER_ROW==sqlcipher3_step(pNextIdx) ){
125352       iNext = sqlcipher3_column_int(pNextIdx, 0);
125353     }
125354     rc = sqlcipher3_reset(pNextIdx);
125355   }
125356
125357   if( rc==SQLCIPHER_OK ){
125358     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
125359     ** full, merge all segments in level iLevel into a single iLevel+1
125360     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
125361     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
125362     */
125363     if( iNext>=FTS3_MERGE_COUNT ){
125364       rc = fts3SegmentMerge(p, iIndex, iLevel);
125365       *piIdx = 0;
125366     }else{
125367       *piIdx = iNext;
125368     }
125369   }
125370
125371   return rc;
125372 }
125373
125374 /*
125375 ** The %_segments table is declared as follows:
125376 **
125377 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
125378 **
125379 ** This function reads data from a single row of the %_segments table. The
125380 ** specific row is identified by the iBlockid parameter. If paBlob is not
125381 ** NULL, then a buffer is allocated using sqlcipher3_malloc() and populated
125382 ** with the contents of the blob stored in the "block" column of the 
125383 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
125384 ** to the size of the blob in bytes before returning.
125385 **
125386 ** If an error occurs, or the table does not contain the specified row,
125387 ** an SQLite error code is returned. Otherwise, SQLCIPHER_OK is returned. If
125388 ** paBlob is non-NULL, then it is the responsibility of the caller to
125389 ** eventually free the returned buffer.
125390 **
125391 ** This function may leave an open sqlcipher3_blob* handle in the
125392 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
125393 ** to this function. The handle may be closed by calling the
125394 ** sqlcipher3Fts3SegmentsClose() function. Reusing a blob handle is a handy
125395 ** performance improvement, but the blob handle should always be closed
125396 ** before control is returned to the user (to prevent a lock being held
125397 ** on the database file for longer than necessary). Thus, any virtual table
125398 ** method (xFilter etc.) that may directly or indirectly call this function
125399 ** must call sqlcipher3Fts3SegmentsClose() before returning.
125400 */
125401 SQLCIPHER_PRIVATE int sqlcipher3Fts3ReadBlock(
125402   Fts3Table *p,                   /* FTS3 table handle */
125403   sqlcipher3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
125404   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
125405   int *pnBlob,                    /* OUT: Size of blob data */
125406   int *pnLoad                     /* OUT: Bytes actually loaded */
125407 ){
125408   int rc;                         /* Return code */
125409
125410   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
125411   assert( pnBlob);
125412
125413   if( p->pSegments ){
125414     rc = sqlcipher3_blob_reopen(p->pSegments, iBlockid);
125415   }else{
125416     if( 0==p->zSegmentsTbl ){
125417       p->zSegmentsTbl = sqlcipher3_mprintf("%s_segments", p->zName);
125418       if( 0==p->zSegmentsTbl ) return SQLCIPHER_NOMEM;
125419     }
125420     rc = sqlcipher3_blob_open(
125421        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
125422     );
125423   }
125424
125425   if( rc==SQLCIPHER_OK ){
125426     int nByte = sqlcipher3_blob_bytes(p->pSegments);
125427     *pnBlob = nByte;
125428     if( paBlob ){
125429       char *aByte = sqlcipher3_malloc(nByte + FTS3_NODE_PADDING);
125430       if( !aByte ){
125431         rc = SQLCIPHER_NOMEM;
125432       }else{
125433         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
125434           nByte = FTS3_NODE_CHUNKSIZE;
125435           *pnLoad = nByte;
125436         }
125437         rc = sqlcipher3_blob_read(p->pSegments, aByte, nByte, 0);
125438         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
125439         if( rc!=SQLCIPHER_OK ){
125440           sqlcipher3_free(aByte);
125441           aByte = 0;
125442         }
125443       }
125444       *paBlob = aByte;
125445     }
125446   }
125447
125448   return rc;
125449 }
125450
125451 /*
125452 ** Close the blob handle at p->pSegments, if it is open. See comments above
125453 ** the sqlcipher3Fts3ReadBlock() function for details.
125454 */
125455 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegmentsClose(Fts3Table *p){
125456   sqlcipher3_blob_close(p->pSegments);
125457   p->pSegments = 0;
125458 }
125459     
125460 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
125461   int nRead;                      /* Number of bytes to read */
125462   int rc;                         /* Return code */
125463
125464   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
125465   rc = sqlcipher3_blob_read(
125466       pReader->pBlob, 
125467       &pReader->aNode[pReader->nPopulate],
125468       nRead,
125469       pReader->nPopulate
125470   );
125471
125472   if( rc==SQLCIPHER_OK ){
125473     pReader->nPopulate += nRead;
125474     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
125475     if( pReader->nPopulate==pReader->nNode ){
125476       sqlcipher3_blob_close(pReader->pBlob);
125477       pReader->pBlob = 0;
125478       pReader->nPopulate = 0;
125479     }
125480   }
125481   return rc;
125482 }
125483
125484 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
125485   int rc = SQLCIPHER_OK;
125486   assert( !pReader->pBlob 
125487        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
125488   );
125489   while( pReader->pBlob && rc==SQLCIPHER_OK 
125490      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
125491   ){
125492     rc = fts3SegReaderIncrRead(pReader);
125493   }
125494   return rc;
125495 }
125496
125497 /*
125498 ** Move the iterator passed as the first argument to the next term in the
125499 ** segment. If successful, SQLCIPHER_OK is returned. If there is no next term,
125500 ** SQLCIPHER_DONE. Otherwise, an SQLite error code.
125501 */
125502 static int fts3SegReaderNext(
125503   Fts3Table *p, 
125504   Fts3SegReader *pReader,
125505   int bIncr
125506 ){
125507   int rc;                         /* Return code of various sub-routines */
125508   char *pNext;                    /* Cursor variable */
125509   int nPrefix;                    /* Number of bytes in term prefix */
125510   int nSuffix;                    /* Number of bytes in term suffix */
125511
125512   if( !pReader->aDoclist ){
125513     pNext = pReader->aNode;
125514   }else{
125515     pNext = &pReader->aDoclist[pReader->nDoclist];
125516   }
125517
125518   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
125519
125520     if( fts3SegReaderIsPending(pReader) ){
125521       Fts3HashElem *pElem = *(pReader->ppNextElem);
125522       if( pElem==0 ){
125523         pReader->aNode = 0;
125524       }else{
125525         PendingList *pList = (PendingList *)fts3HashData(pElem);
125526         pReader->zTerm = (char *)fts3HashKey(pElem);
125527         pReader->nTerm = fts3HashKeysize(pElem);
125528         pReader->nNode = pReader->nDoclist = pList->nData + 1;
125529         pReader->aNode = pReader->aDoclist = pList->aData;
125530         pReader->ppNextElem++;
125531         assert( pReader->aNode );
125532       }
125533       return SQLCIPHER_OK;
125534     }
125535
125536     if( !fts3SegReaderIsRootOnly(pReader) ){
125537       sqlcipher3_free(pReader->aNode);
125538       sqlcipher3_blob_close(pReader->pBlob);
125539       pReader->pBlob = 0;
125540     }
125541     pReader->aNode = 0;
125542
125543     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
125544     ** blocks have already been traversed.  */
125545     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
125546     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
125547       return SQLCIPHER_OK;
125548     }
125549
125550     rc = sqlcipher3Fts3ReadBlock(
125551         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
125552         (bIncr ? &pReader->nPopulate : 0)
125553     );
125554     if( rc!=SQLCIPHER_OK ) return rc;
125555     assert( pReader->pBlob==0 );
125556     if( bIncr && pReader->nPopulate<pReader->nNode ){
125557       pReader->pBlob = p->pSegments;
125558       p->pSegments = 0;
125559     }
125560     pNext = pReader->aNode;
125561   }
125562
125563   assert( !fts3SegReaderIsPending(pReader) );
125564
125565   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
125566   if( rc!=SQLCIPHER_OK ) return rc;
125567   
125568   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
125569   ** safe (no risk of overread) even if the node data is corrupted. */
125570   pNext += sqlcipher3Fts3GetVarint32(pNext, &nPrefix);
125571   pNext += sqlcipher3Fts3GetVarint32(pNext, &nSuffix);
125572   if( nPrefix<0 || nSuffix<=0 
125573    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
125574   ){
125575     return FTS_CORRUPT_VTAB;
125576   }
125577
125578   if( nPrefix+nSuffix>pReader->nTermAlloc ){
125579     int nNew = (nPrefix+nSuffix)*2;
125580     char *zNew = sqlcipher3_realloc(pReader->zTerm, nNew);
125581     if( !zNew ){
125582       return SQLCIPHER_NOMEM;
125583     }
125584     pReader->zTerm = zNew;
125585     pReader->nTermAlloc = nNew;
125586   }
125587
125588   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
125589   if( rc!=SQLCIPHER_OK ) return rc;
125590
125591   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
125592   pReader->nTerm = nPrefix+nSuffix;
125593   pNext += nSuffix;
125594   pNext += sqlcipher3Fts3GetVarint32(pNext, &pReader->nDoclist);
125595   pReader->aDoclist = pNext;
125596   pReader->pOffsetList = 0;
125597
125598   /* Check that the doclist does not appear to extend past the end of the
125599   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
125600   ** of these statements is untrue, then the data structure is corrupt.
125601   */
125602   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
125603    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
125604   ){
125605     return FTS_CORRUPT_VTAB;
125606   }
125607   return SQLCIPHER_OK;
125608 }
125609
125610 /*
125611 ** Set the SegReader to point to the first docid in the doclist associated
125612 ** with the current term.
125613 */
125614 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
125615   int rc = SQLCIPHER_OK;
125616   assert( pReader->aDoclist );
125617   assert( !pReader->pOffsetList );
125618   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
125619     u8 bEof = 0;
125620     pReader->iDocid = 0;
125621     pReader->nOffsetList = 0;
125622     sqlcipher3Fts3DoclistPrev(0,
125623         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
125624         &pReader->iDocid, &pReader->nOffsetList, &bEof
125625     );
125626   }else{
125627     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
125628     if( rc==SQLCIPHER_OK ){
125629       int n = sqlcipher3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
125630       pReader->pOffsetList = &pReader->aDoclist[n];
125631     }
125632   }
125633   return rc;
125634 }
125635
125636 /*
125637 ** Advance the SegReader to point to the next docid in the doclist
125638 ** associated with the current term.
125639 ** 
125640 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
125641 ** *ppOffsetList is set to point to the first column-offset list
125642 ** in the doclist entry (i.e. immediately past the docid varint).
125643 ** *pnOffsetList is set to the length of the set of column-offset
125644 ** lists, not including the nul-terminator byte. For example:
125645 */
125646 static int fts3SegReaderNextDocid(
125647   Fts3Table *pTab,
125648   Fts3SegReader *pReader,         /* Reader to advance to next docid */
125649   char **ppOffsetList,            /* OUT: Pointer to current position-list */
125650   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
125651 ){
125652   int rc = SQLCIPHER_OK;
125653   char *p = pReader->pOffsetList;
125654   char c = 0;
125655
125656   assert( p );
125657
125658   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
125659     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
125660     ** Pending-terms doclists are always built up in ascending order, so
125661     ** we have to iterate through them backwards here. */
125662     u8 bEof = 0;
125663     if( ppOffsetList ){
125664       *ppOffsetList = pReader->pOffsetList;
125665       *pnOffsetList = pReader->nOffsetList - 1;
125666     }
125667     sqlcipher3Fts3DoclistPrev(0,
125668         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
125669         &pReader->nOffsetList, &bEof
125670     );
125671     if( bEof ){
125672       pReader->pOffsetList = 0;
125673     }else{
125674       pReader->pOffsetList = p;
125675     }
125676   }else{
125677     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
125678
125679     /* Pointer p currently points at the first byte of an offset list. The
125680     ** following block advances it to point one byte past the end of
125681     ** the same offset list. */
125682     while( 1 ){
125683   
125684       /* The following line of code (and the "p++" below the while() loop) is
125685       ** normally all that is required to move pointer p to the desired 
125686       ** position. The exception is if this node is being loaded from disk
125687       ** incrementally and pointer "p" now points to the first byte passed
125688       ** the populated part of pReader->aNode[].
125689       */
125690       while( *p | c ) c = *p++ & 0x80;
125691       assert( *p==0 );
125692   
125693       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
125694       rc = fts3SegReaderIncrRead(pReader);
125695       if( rc!=SQLCIPHER_OK ) return rc;
125696     }
125697     p++;
125698   
125699     /* If required, populate the output variables with a pointer to and the
125700     ** size of the previous offset-list.
125701     */
125702     if( ppOffsetList ){
125703       *ppOffsetList = pReader->pOffsetList;
125704       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
125705     }
125706
125707     while( p<pEnd && *p==0 ) p++;
125708   
125709     /* If there are no more entries in the doclist, set pOffsetList to
125710     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
125711     ** Fts3SegReader.pOffsetList to point to the next offset list before
125712     ** returning.
125713     */
125714     if( p>=pEnd ){
125715       pReader->pOffsetList = 0;
125716     }else{
125717       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
125718       if( rc==SQLCIPHER_OK ){
125719         sqlcipher3_int64 iDelta;
125720         pReader->pOffsetList = p + sqlcipher3Fts3GetVarint(p, &iDelta);
125721         if( pTab->bDescIdx ){
125722           pReader->iDocid -= iDelta;
125723         }else{
125724           pReader->iDocid += iDelta;
125725         }
125726       }
125727     }
125728   }
125729
125730   return SQLCIPHER_OK;
125731 }
125732
125733
125734 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrOvfl(
125735   Fts3Cursor *pCsr, 
125736   Fts3MultiSegReader *pMsr,
125737   int *pnOvfl
125738 ){
125739   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
125740   int nOvfl = 0;
125741   int ii;
125742   int rc = SQLCIPHER_OK;
125743   int pgsz = p->nPgsz;
125744
125745   assert( p->bHasStat );
125746   assert( pgsz>0 );
125747
125748   for(ii=0; rc==SQLCIPHER_OK && ii<pMsr->nSegment; ii++){
125749     Fts3SegReader *pReader = pMsr->apSegment[ii];
125750     if( !fts3SegReaderIsPending(pReader) 
125751      && !fts3SegReaderIsRootOnly(pReader) 
125752     ){
125753       sqlcipher3_int64 jj;
125754       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
125755         int nBlob;
125756         rc = sqlcipher3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
125757         if( rc!=SQLCIPHER_OK ) break;
125758         if( (nBlob+35)>pgsz ){
125759           nOvfl += (nBlob + 34)/pgsz;
125760         }
125761       }
125762     }
125763   }
125764   *pnOvfl = nOvfl;
125765   return rc;
125766 }
125767
125768 /*
125769 ** Free all allocations associated with the iterator passed as the 
125770 ** second argument.
125771 */
125772 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFree(Fts3SegReader *pReader){
125773   if( pReader && !fts3SegReaderIsPending(pReader) ){
125774     sqlcipher3_free(pReader->zTerm);
125775     if( !fts3SegReaderIsRootOnly(pReader) ){
125776       sqlcipher3_free(pReader->aNode);
125777       sqlcipher3_blob_close(pReader->pBlob);
125778     }
125779   }
125780   sqlcipher3_free(pReader);
125781 }
125782
125783 /*
125784 ** Allocate a new SegReader object.
125785 */
125786 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderNew(
125787   int iAge,                       /* Segment "age". */
125788   sqlcipher3_int64 iStartLeaf,       /* First leaf to traverse */
125789   sqlcipher3_int64 iEndLeaf,         /* Final leaf to traverse */
125790   sqlcipher3_int64 iEndBlock,        /* Final block of segment */
125791   const char *zRoot,              /* Buffer containing root node */
125792   int nRoot,                      /* Size of buffer containing root node */
125793   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
125794 ){
125795   int rc = SQLCIPHER_OK;             /* Return code */
125796   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
125797   int nExtra = 0;                 /* Bytes to allocate segment root node */
125798
125799   assert( iStartLeaf<=iEndLeaf );
125800   if( iStartLeaf==0 ){
125801     nExtra = nRoot + FTS3_NODE_PADDING;
125802   }
125803
125804   pReader = (Fts3SegReader *)sqlcipher3_malloc(sizeof(Fts3SegReader) + nExtra);
125805   if( !pReader ){
125806     return SQLCIPHER_NOMEM;
125807   }
125808   memset(pReader, 0, sizeof(Fts3SegReader));
125809   pReader->iIdx = iAge;
125810   pReader->iStartBlock = iStartLeaf;
125811   pReader->iLeafEndBlock = iEndLeaf;
125812   pReader->iEndBlock = iEndBlock;
125813
125814   if( nExtra ){
125815     /* The entire segment is stored in the root node. */
125816     pReader->aNode = (char *)&pReader[1];
125817     pReader->nNode = nRoot;
125818     memcpy(pReader->aNode, zRoot, nRoot);
125819     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
125820   }else{
125821     pReader->iCurrentBlock = iStartLeaf-1;
125822   }
125823
125824   if( rc==SQLCIPHER_OK ){
125825     *ppReader = pReader;
125826   }else{
125827     sqlcipher3Fts3SegReaderFree(pReader);
125828   }
125829   return rc;
125830 }
125831
125832 /*
125833 ** This is a comparison function used as a qsort() callback when sorting
125834 ** an array of pending terms by term. This occurs as part of flushing
125835 ** the contents of the pending-terms hash table to the database.
125836 */
125837 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
125838   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
125839   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
125840   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
125841   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
125842
125843   int n = (n1<n2 ? n1 : n2);
125844   int c = memcmp(z1, z2, n);
125845   if( c==0 ){
125846     c = n1 - n2;
125847   }
125848   return c;
125849 }
125850
125851 /*
125852 ** This function is used to allocate an Fts3SegReader that iterates through
125853 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
125854 **
125855 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
125856 ** through each term in the pending-terms table. Or, if isPrefixIter is
125857 ** non-zero, it iterates through each term and its prefixes. For example, if
125858 ** the pending terms hash table contains the terms "sqlcipher", "mysql" and
125859 ** "firebird", then the iterator visits the following 'terms' (in the order
125860 ** shown):
125861 **
125862 **   f fi fir fire fireb firebi firebir firebird
125863 **   m my mys mysq mysql
125864 **   s sq sql sqli sqlit sqlcipher
125865 **
125866 ** Whereas if isPrefixIter is zero, the terms visited are:
125867 **
125868 **   firebird mysql sqlcipher
125869 */
125870 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderPending(
125871   Fts3Table *p,                   /* Virtual table handle */
125872   int iIndex,                     /* Index for p->aIndex */
125873   const char *zTerm,              /* Term to search for */
125874   int nTerm,                      /* Size of buffer zTerm */
125875   int bPrefix,                    /* True for a prefix iterator */
125876   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
125877 ){
125878   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
125879   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
125880   int nElem = 0;                  /* Size of array at aElem */
125881   int rc = SQLCIPHER_OK;             /* Return Code */
125882   Fts3Hash *pHash;
125883
125884   pHash = &p->aIndex[iIndex].hPending;
125885   if( bPrefix ){
125886     int nAlloc = 0;               /* Size of allocated array at aElem */
125887     Fts3HashElem *pE = 0;         /* Iterator variable */
125888
125889     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
125890       char *zKey = (char *)fts3HashKey(pE);
125891       int nKey = fts3HashKeysize(pE);
125892       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
125893         if( nElem==nAlloc ){
125894           Fts3HashElem **aElem2;
125895           nAlloc += 16;
125896           aElem2 = (Fts3HashElem **)sqlcipher3_realloc(
125897               aElem, nAlloc*sizeof(Fts3HashElem *)
125898           );
125899           if( !aElem2 ){
125900             rc = SQLCIPHER_NOMEM;
125901             nElem = 0;
125902             break;
125903           }
125904           aElem = aElem2;
125905         }
125906
125907         aElem[nElem++] = pE;
125908       }
125909     }
125910
125911     /* If more than one term matches the prefix, sort the Fts3HashElem
125912     ** objects in term order using qsort(). This uses the same comparison
125913     ** callback as is used when flushing terms to disk.
125914     */
125915     if( nElem>1 ){
125916       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
125917     }
125918
125919   }else{
125920     /* The query is a simple term lookup that matches at most one term in
125921     ** the index. All that is required is a straight hash-lookup. */
125922     Fts3HashElem *pE = fts3HashFindElem(pHash, zTerm, nTerm);
125923     if( pE ){
125924       aElem = &pE;
125925       nElem = 1;
125926     }
125927   }
125928
125929   if( nElem>0 ){
125930     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
125931     pReader = (Fts3SegReader *)sqlcipher3_malloc(nByte);
125932     if( !pReader ){
125933       rc = SQLCIPHER_NOMEM;
125934     }else{
125935       memset(pReader, 0, nByte);
125936       pReader->iIdx = 0x7FFFFFFF;
125937       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
125938       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
125939     }
125940   }
125941
125942   if( bPrefix ){
125943     sqlcipher3_free(aElem);
125944   }
125945   *ppReader = pReader;
125946   return rc;
125947 }
125948
125949 /*
125950 ** Compare the entries pointed to by two Fts3SegReader structures. 
125951 ** Comparison is as follows:
125952 **
125953 **   1) EOF is greater than not EOF.
125954 **
125955 **   2) The current terms (if any) are compared using memcmp(). If one
125956 **      term is a prefix of another, the longer term is considered the
125957 **      larger.
125958 **
125959 **   3) By segment age. An older segment is considered larger.
125960 */
125961 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
125962   int rc;
125963   if( pLhs->aNode && pRhs->aNode ){
125964     int rc2 = pLhs->nTerm - pRhs->nTerm;
125965     if( rc2<0 ){
125966       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
125967     }else{
125968       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
125969     }
125970     if( rc==0 ){
125971       rc = rc2;
125972     }
125973   }else{
125974     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
125975   }
125976   if( rc==0 ){
125977     rc = pRhs->iIdx - pLhs->iIdx;
125978   }
125979   assert( rc!=0 );
125980   return rc;
125981 }
125982
125983 /*
125984 ** A different comparison function for SegReader structures. In this
125985 ** version, it is assumed that each SegReader points to an entry in
125986 ** a doclist for identical terms. Comparison is made as follows:
125987 **
125988 **   1) EOF (end of doclist in this case) is greater than not EOF.
125989 **
125990 **   2) By current docid.
125991 **
125992 **   3) By segment age. An older segment is considered larger.
125993 */
125994 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
125995   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
125996   if( rc==0 ){
125997     if( pLhs->iDocid==pRhs->iDocid ){
125998       rc = pRhs->iIdx - pLhs->iIdx;
125999     }else{
126000       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
126001     }
126002   }
126003   assert( pLhs->aNode && pRhs->aNode );
126004   return rc;
126005 }
126006 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126007   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126008   if( rc==0 ){
126009     if( pLhs->iDocid==pRhs->iDocid ){
126010       rc = pRhs->iIdx - pLhs->iIdx;
126011     }else{
126012       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
126013     }
126014   }
126015   assert( pLhs->aNode && pRhs->aNode );
126016   return rc;
126017 }
126018
126019 /*
126020 ** Compare the term that the Fts3SegReader object passed as the first argument
126021 ** points to with the term specified by arguments zTerm and nTerm. 
126022 **
126023 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
126024 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
126025 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
126026 */
126027 static int fts3SegReaderTermCmp(
126028   Fts3SegReader *pSeg,            /* Segment reader object */
126029   const char *zTerm,              /* Term to compare to */
126030   int nTerm                       /* Size of term zTerm in bytes */
126031 ){
126032   int res = 0;
126033   if( pSeg->aNode ){
126034     if( pSeg->nTerm>nTerm ){
126035       res = memcmp(pSeg->zTerm, zTerm, nTerm);
126036     }else{
126037       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
126038     }
126039     if( res==0 ){
126040       res = pSeg->nTerm-nTerm;
126041     }
126042   }
126043   return res;
126044 }
126045
126046 /*
126047 ** Argument apSegment is an array of nSegment elements. It is known that
126048 ** the final (nSegment-nSuspect) members are already in sorted order
126049 ** (according to the comparison function provided). This function shuffles
126050 ** the array around until all entries are in sorted order.
126051 */
126052 static void fts3SegReaderSort(
126053   Fts3SegReader **apSegment,                     /* Array to sort entries of */
126054   int nSegment,                                  /* Size of apSegment array */
126055   int nSuspect,                                  /* Unsorted entry count */
126056   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
126057 ){
126058   int i;                          /* Iterator variable */
126059
126060   assert( nSuspect<=nSegment );
126061
126062   if( nSuspect==nSegment ) nSuspect--;
126063   for(i=nSuspect-1; i>=0; i--){
126064     int j;
126065     for(j=i; j<(nSegment-1); j++){
126066       Fts3SegReader *pTmp;
126067       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
126068       pTmp = apSegment[j+1];
126069       apSegment[j+1] = apSegment[j];
126070       apSegment[j] = pTmp;
126071     }
126072   }
126073
126074 #ifndef NDEBUG
126075   /* Check that the list really is sorted now. */
126076   for(i=0; i<(nSuspect-1); i++){
126077     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
126078   }
126079 #endif
126080 }
126081
126082 /* 
126083 ** Insert a record into the %_segments table.
126084 */
126085 static int fts3WriteSegment(
126086   Fts3Table *p,                   /* Virtual table handle */
126087   sqlcipher3_int64 iBlock,           /* Block id for new block */
126088   char *z,                        /* Pointer to buffer containing block data */
126089   int n                           /* Size of buffer z in bytes */
126090 ){
126091   sqlcipher3_stmt *pStmt;
126092   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
126093   if( rc==SQLCIPHER_OK ){
126094     sqlcipher3_bind_int64(pStmt, 1, iBlock);
126095     sqlcipher3_bind_blob(pStmt, 2, z, n, SQLCIPHER_STATIC);
126096     sqlcipher3_step(pStmt);
126097     rc = sqlcipher3_reset(pStmt);
126098   }
126099   return rc;
126100 }
126101
126102 /* 
126103 ** Insert a record into the %_segdir table.
126104 */
126105 static int fts3WriteSegdir(
126106   Fts3Table *p,                   /* Virtual table handle */
126107   int iLevel,                     /* Value for "level" field */
126108   int iIdx,                       /* Value for "idx" field */
126109   sqlcipher3_int64 iStartBlock,      /* Value for "start_block" field */
126110   sqlcipher3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
126111   sqlcipher3_int64 iEndBlock,        /* Value for "end_block" field */
126112   char *zRoot,                    /* Blob value for "root" field */
126113   int nRoot                       /* Number of bytes in buffer zRoot */
126114 ){
126115   sqlcipher3_stmt *pStmt;
126116   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
126117   if( rc==SQLCIPHER_OK ){
126118     sqlcipher3_bind_int(pStmt, 1, iLevel);
126119     sqlcipher3_bind_int(pStmt, 2, iIdx);
126120     sqlcipher3_bind_int64(pStmt, 3, iStartBlock);
126121     sqlcipher3_bind_int64(pStmt, 4, iLeafEndBlock);
126122     sqlcipher3_bind_int64(pStmt, 5, iEndBlock);
126123     sqlcipher3_bind_blob(pStmt, 6, zRoot, nRoot, SQLCIPHER_STATIC);
126124     sqlcipher3_step(pStmt);
126125     rc = sqlcipher3_reset(pStmt);
126126   }
126127   return rc;
126128 }
126129
126130 /*
126131 ** Return the size of the common prefix (if any) shared by zPrev and
126132 ** zNext, in bytes. For example, 
126133 **
126134 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
126135 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
126136 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
126137 */
126138 static int fts3PrefixCompress(
126139   const char *zPrev,              /* Buffer containing previous term */
126140   int nPrev,                      /* Size of buffer zPrev in bytes */
126141   const char *zNext,              /* Buffer containing next term */
126142   int nNext                       /* Size of buffer zNext in bytes */
126143 ){
126144   int n;
126145   UNUSED_PARAMETER(nNext);
126146   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
126147   return n;
126148 }
126149
126150 /*
126151 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
126152 ** (according to memcmp) than the previous term.
126153 */
126154 static int fts3NodeAddTerm(
126155   Fts3Table *p,                   /* Virtual table handle */
126156   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
126157   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
126158   const char *zTerm,              /* Pointer to buffer containing term */
126159   int nTerm                       /* Size of term in bytes */
126160 ){
126161   SegmentNode *pTree = *ppTree;
126162   int rc;
126163   SegmentNode *pNew;
126164
126165   /* First try to append the term to the current node. Return early if 
126166   ** this is possible.
126167   */
126168   if( pTree ){
126169     int nData = pTree->nData;     /* Current size of node in bytes */
126170     int nReq = nData;             /* Required space after adding zTerm */
126171     int nPrefix;                  /* Number of bytes of prefix compression */
126172     int nSuffix;                  /* Suffix length */
126173
126174     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
126175     nSuffix = nTerm-nPrefix;
126176
126177     nReq += sqlcipher3Fts3VarintLen(nPrefix)+sqlcipher3Fts3VarintLen(nSuffix)+nSuffix;
126178     if( nReq<=p->nNodeSize || !pTree->zTerm ){
126179
126180       if( nReq>p->nNodeSize ){
126181         /* An unusual case: this is the first term to be added to the node
126182         ** and the static node buffer (p->nNodeSize bytes) is not large
126183         ** enough. Use a separately malloced buffer instead This wastes
126184         ** p->nNodeSize bytes, but since this scenario only comes about when
126185         ** the database contain two terms that share a prefix of almost 2KB, 
126186         ** this is not expected to be a serious problem. 
126187         */
126188         assert( pTree->aData==(char *)&pTree[1] );
126189         pTree->aData = (char *)sqlcipher3_malloc(nReq);
126190         if( !pTree->aData ){
126191           return SQLCIPHER_NOMEM;
126192         }
126193       }
126194
126195       if( pTree->zTerm ){
126196         /* There is no prefix-length field for first term in a node */
126197         nData += sqlcipher3Fts3PutVarint(&pTree->aData[nData], nPrefix);
126198       }
126199
126200       nData += sqlcipher3Fts3PutVarint(&pTree->aData[nData], nSuffix);
126201       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
126202       pTree->nData = nData + nSuffix;
126203       pTree->nEntry++;
126204
126205       if( isCopyTerm ){
126206         if( pTree->nMalloc<nTerm ){
126207           char *zNew = sqlcipher3_realloc(pTree->zMalloc, nTerm*2);
126208           if( !zNew ){
126209             return SQLCIPHER_NOMEM;
126210           }
126211           pTree->nMalloc = nTerm*2;
126212           pTree->zMalloc = zNew;
126213         }
126214         pTree->zTerm = pTree->zMalloc;
126215         memcpy(pTree->zTerm, zTerm, nTerm);
126216         pTree->nTerm = nTerm;
126217       }else{
126218         pTree->zTerm = (char *)zTerm;
126219         pTree->nTerm = nTerm;
126220       }
126221       return SQLCIPHER_OK;
126222     }
126223   }
126224
126225   /* If control flows to here, it was not possible to append zTerm to the
126226   ** current node. Create a new node (a right-sibling of the current node).
126227   ** If this is the first node in the tree, the term is added to it.
126228   **
126229   ** Otherwise, the term is not added to the new node, it is left empty for
126230   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
126231   ** has no parent, one is created here.
126232   */
126233   pNew = (SegmentNode *)sqlcipher3_malloc(sizeof(SegmentNode) + p->nNodeSize);
126234   if( !pNew ){
126235     return SQLCIPHER_NOMEM;
126236   }
126237   memset(pNew, 0, sizeof(SegmentNode));
126238   pNew->nData = 1 + FTS3_VARINT_MAX;
126239   pNew->aData = (char *)&pNew[1];
126240
126241   if( pTree ){
126242     SegmentNode *pParent = pTree->pParent;
126243     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
126244     if( pTree->pParent==0 ){
126245       pTree->pParent = pParent;
126246     }
126247     pTree->pRight = pNew;
126248     pNew->pLeftmost = pTree->pLeftmost;
126249     pNew->pParent = pParent;
126250     pNew->zMalloc = pTree->zMalloc;
126251     pNew->nMalloc = pTree->nMalloc;
126252     pTree->zMalloc = 0;
126253   }else{
126254     pNew->pLeftmost = pNew;
126255     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
126256   }
126257
126258   *ppTree = pNew;
126259   return rc;
126260 }
126261
126262 /*
126263 ** Helper function for fts3NodeWrite().
126264 */
126265 static int fts3TreeFinishNode(
126266   SegmentNode *pTree, 
126267   int iHeight, 
126268   sqlcipher3_int64 iLeftChild
126269 ){
126270   int nStart;
126271   assert( iHeight>=1 && iHeight<128 );
126272   nStart = FTS3_VARINT_MAX - sqlcipher3Fts3VarintLen(iLeftChild);
126273   pTree->aData[nStart] = (char)iHeight;
126274   sqlcipher3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
126275   return nStart;
126276 }
126277
126278 /*
126279 ** Write the buffer for the segment node pTree and all of its peers to the
126280 ** database. Then call this function recursively to write the parent of 
126281 ** pTree and its peers to the database. 
126282 **
126283 ** Except, if pTree is a root node, do not write it to the database. Instead,
126284 ** set output variables *paRoot and *pnRoot to contain the root node.
126285 **
126286 ** If successful, SQLCIPHER_OK is returned and output variable *piLast is
126287 ** set to the largest blockid written to the database (or zero if no
126288 ** blocks were written to the db). Otherwise, an SQLite error code is 
126289 ** returned.
126290 */
126291 static int fts3NodeWrite(
126292   Fts3Table *p,                   /* Virtual table handle */
126293   SegmentNode *pTree,             /* SegmentNode handle */
126294   int iHeight,                    /* Height of this node in tree */
126295   sqlcipher3_int64 iLeaf,            /* Block id of first leaf node */
126296   sqlcipher3_int64 iFree,            /* Block id of next free slot in %_segments */
126297   sqlcipher3_int64 *piLast,          /* OUT: Block id of last entry written */
126298   char **paRoot,                  /* OUT: Data for root node */
126299   int *pnRoot                     /* OUT: Size of root node in bytes */
126300 ){
126301   int rc = SQLCIPHER_OK;
126302
126303   if( !pTree->pParent ){
126304     /* Root node of the tree. */
126305     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
126306     *piLast = iFree-1;
126307     *pnRoot = pTree->nData - nStart;
126308     *paRoot = &pTree->aData[nStart];
126309   }else{
126310     SegmentNode *pIter;
126311     sqlcipher3_int64 iNextFree = iFree;
126312     sqlcipher3_int64 iNextLeaf = iLeaf;
126313     for(pIter=pTree->pLeftmost; pIter && rc==SQLCIPHER_OK; pIter=pIter->pRight){
126314       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
126315       int nWrite = pIter->nData - nStart;
126316   
126317       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
126318       iNextFree++;
126319       iNextLeaf += (pIter->nEntry+1);
126320     }
126321     if( rc==SQLCIPHER_OK ){
126322       assert( iNextLeaf==iFree );
126323       rc = fts3NodeWrite(
126324           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
126325       );
126326     }
126327   }
126328
126329   return rc;
126330 }
126331
126332 /*
126333 ** Free all memory allocations associated with the tree pTree.
126334 */
126335 static void fts3NodeFree(SegmentNode *pTree){
126336   if( pTree ){
126337     SegmentNode *p = pTree->pLeftmost;
126338     fts3NodeFree(p->pParent);
126339     while( p ){
126340       SegmentNode *pRight = p->pRight;
126341       if( p->aData!=(char *)&p[1] ){
126342         sqlcipher3_free(p->aData);
126343       }
126344       assert( pRight==0 || p->zMalloc==0 );
126345       sqlcipher3_free(p->zMalloc);
126346       sqlcipher3_free(p);
126347       p = pRight;
126348     }
126349   }
126350 }
126351
126352 /*
126353 ** Add a term to the segment being constructed by the SegmentWriter object
126354 ** *ppWriter. When adding the first term to a segment, *ppWriter should
126355 ** be passed NULL. This function will allocate a new SegmentWriter object
126356 ** and return it via the input/output variable *ppWriter in this case.
126357 **
126358 ** If successful, SQLCIPHER_OK is returned. Otherwise, an SQLite error code.
126359 */
126360 static int fts3SegWriterAdd(
126361   Fts3Table *p,                   /* Virtual table handle */
126362   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
126363   int isCopyTerm,                 /* True if buffer zTerm must be copied */
126364   const char *zTerm,              /* Pointer to buffer containing term */
126365   int nTerm,                      /* Size of term in bytes */
126366   const char *aDoclist,           /* Pointer to buffer containing doclist */
126367   int nDoclist                    /* Size of doclist in bytes */
126368 ){
126369   int nPrefix;                    /* Size of term prefix in bytes */
126370   int nSuffix;                    /* Size of term suffix in bytes */
126371   int nReq;                       /* Number of bytes required on leaf page */
126372   int nData;
126373   SegmentWriter *pWriter = *ppWriter;
126374
126375   if( !pWriter ){
126376     int rc;
126377     sqlcipher3_stmt *pStmt;
126378
126379     /* Allocate the SegmentWriter structure */
126380     pWriter = (SegmentWriter *)sqlcipher3_malloc(sizeof(SegmentWriter));
126381     if( !pWriter ) return SQLCIPHER_NOMEM;
126382     memset(pWriter, 0, sizeof(SegmentWriter));
126383     *ppWriter = pWriter;
126384
126385     /* Allocate a buffer in which to accumulate data */
126386     pWriter->aData = (char *)sqlcipher3_malloc(p->nNodeSize);
126387     if( !pWriter->aData ) return SQLCIPHER_NOMEM;
126388     pWriter->nSize = p->nNodeSize;
126389
126390     /* Find the next free blockid in the %_segments table */
126391     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
126392     if( rc!=SQLCIPHER_OK ) return rc;
126393     if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
126394       pWriter->iFree = sqlcipher3_column_int64(pStmt, 0);
126395       pWriter->iFirst = pWriter->iFree;
126396     }
126397     rc = sqlcipher3_reset(pStmt);
126398     if( rc!=SQLCIPHER_OK ) return rc;
126399   }
126400   nData = pWriter->nData;
126401
126402   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
126403   nSuffix = nTerm-nPrefix;
126404
126405   /* Figure out how many bytes are required by this new entry */
126406   nReq = sqlcipher3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
126407     sqlcipher3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
126408     nSuffix +                               /* Term suffix */
126409     sqlcipher3Fts3VarintLen(nDoclist) +        /* Size of doclist */
126410     nDoclist;                               /* Doclist data */
126411
126412   if( nData>0 && nData+nReq>p->nNodeSize ){
126413     int rc;
126414
126415     /* The current leaf node is full. Write it out to the database. */
126416     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
126417     if( rc!=SQLCIPHER_OK ) return rc;
126418
126419     /* Add the current term to the interior node tree. The term added to
126420     ** the interior tree must:
126421     **
126422     **   a) be greater than the largest term on the leaf node just written
126423     **      to the database (still available in pWriter->zTerm), and
126424     **
126425     **   b) be less than or equal to the term about to be added to the new
126426     **      leaf node (zTerm/nTerm).
126427     **
126428     ** In other words, it must be the prefix of zTerm 1 byte longer than
126429     ** the common prefix (if any) of zTerm and pWriter->zTerm.
126430     */
126431     assert( nPrefix<nTerm );
126432     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
126433     if( rc!=SQLCIPHER_OK ) return rc;
126434
126435     nData = 0;
126436     pWriter->nTerm = 0;
126437
126438     nPrefix = 0;
126439     nSuffix = nTerm;
126440     nReq = 1 +                              /* varint containing prefix size */
126441       sqlcipher3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
126442       nTerm +                               /* Term suffix */
126443       sqlcipher3Fts3VarintLen(nDoclist) +      /* Size of doclist */
126444       nDoclist;                             /* Doclist data */
126445   }
126446
126447   /* If the buffer currently allocated is too small for this entry, realloc
126448   ** the buffer to make it large enough.
126449   */
126450   if( nReq>pWriter->nSize ){
126451     char *aNew = sqlcipher3_realloc(pWriter->aData, nReq);
126452     if( !aNew ) return SQLCIPHER_NOMEM;
126453     pWriter->aData = aNew;
126454     pWriter->nSize = nReq;
126455   }
126456   assert( nData+nReq<=pWriter->nSize );
126457
126458   /* Append the prefix-compressed term and doclist to the buffer. */
126459   nData += sqlcipher3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
126460   nData += sqlcipher3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
126461   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
126462   nData += nSuffix;
126463   nData += sqlcipher3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
126464   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
126465   pWriter->nData = nData + nDoclist;
126466
126467   /* Save the current term so that it can be used to prefix-compress the next.
126468   ** If the isCopyTerm parameter is true, then the buffer pointed to by
126469   ** zTerm is transient, so take a copy of the term data. Otherwise, just
126470   ** store a copy of the pointer.
126471   */
126472   if( isCopyTerm ){
126473     if( nTerm>pWriter->nMalloc ){
126474       char *zNew = sqlcipher3_realloc(pWriter->zMalloc, nTerm*2);
126475       if( !zNew ){
126476         return SQLCIPHER_NOMEM;
126477       }
126478       pWriter->nMalloc = nTerm*2;
126479       pWriter->zMalloc = zNew;
126480       pWriter->zTerm = zNew;
126481     }
126482     assert( pWriter->zTerm==pWriter->zMalloc );
126483     memcpy(pWriter->zTerm, zTerm, nTerm);
126484   }else{
126485     pWriter->zTerm = (char *)zTerm;
126486   }
126487   pWriter->nTerm = nTerm;
126488
126489   return SQLCIPHER_OK;
126490 }
126491
126492 /*
126493 ** Flush all data associated with the SegmentWriter object pWriter to the
126494 ** database. This function must be called after all terms have been added
126495 ** to the segment using fts3SegWriterAdd(). If successful, SQLCIPHER_OK is
126496 ** returned. Otherwise, an SQLite error code.
126497 */
126498 static int fts3SegWriterFlush(
126499   Fts3Table *p,                   /* Virtual table handle */
126500   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
126501   int iLevel,                     /* Value for 'level' column of %_segdir */
126502   int iIdx                        /* Value for 'idx' column of %_segdir */
126503 ){
126504   int rc;                         /* Return code */
126505   if( pWriter->pTree ){
126506     sqlcipher3_int64 iLast = 0;      /* Largest block id written to database */
126507     sqlcipher3_int64 iLastLeaf;      /* Largest leaf block id written to db */
126508     char *zRoot = NULL;           /* Pointer to buffer containing root node */
126509     int nRoot = 0;                /* Size of buffer zRoot */
126510
126511     iLastLeaf = pWriter->iFree;
126512     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
126513     if( rc==SQLCIPHER_OK ){
126514       rc = fts3NodeWrite(p, pWriter->pTree, 1,
126515           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
126516     }
126517     if( rc==SQLCIPHER_OK ){
126518       rc = fts3WriteSegdir(
126519           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
126520     }
126521   }else{
126522     /* The entire tree fits on the root node. Write it to the segdir table. */
126523     rc = fts3WriteSegdir(
126524         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
126525   }
126526   return rc;
126527 }
126528
126529 /*
126530 ** Release all memory held by the SegmentWriter object passed as the 
126531 ** first argument.
126532 */
126533 static void fts3SegWriterFree(SegmentWriter *pWriter){
126534   if( pWriter ){
126535     sqlcipher3_free(pWriter->aData);
126536     sqlcipher3_free(pWriter->zMalloc);
126537     fts3NodeFree(pWriter->pTree);
126538     sqlcipher3_free(pWriter);
126539   }
126540 }
126541
126542 /*
126543 ** The first value in the apVal[] array is assumed to contain an integer.
126544 ** This function tests if there exist any documents with docid values that
126545 ** are different from that integer. i.e. if deleting the document with docid
126546 ** pRowid would mean the FTS3 table were empty.
126547 **
126548 ** If successful, *pisEmpty is set to true if the table is empty except for
126549 ** document pRowid, or false otherwise, and SQLCIPHER_OK is returned. If an
126550 ** error occurs, an SQLite error code is returned.
126551 */
126552 static int fts3IsEmpty(Fts3Table *p, sqlcipher3_value *pRowid, int *pisEmpty){
126553   sqlcipher3_stmt *pStmt;
126554   int rc;
126555   if( p->zContentTbl ){
126556     /* If using the content=xxx option, assume the table is never empty */
126557     *pisEmpty = 0;
126558     rc = SQLCIPHER_OK;
126559   }else{
126560     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
126561     if( rc==SQLCIPHER_OK ){
126562       if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
126563         *pisEmpty = sqlcipher3_column_int(pStmt, 0);
126564       }
126565       rc = sqlcipher3_reset(pStmt);
126566     }
126567   }
126568   return rc;
126569 }
126570
126571 /*
126572 ** Set *pnMax to the largest segment level in the database for the index
126573 ** iIndex.
126574 **
126575 ** Segment levels are stored in the 'level' column of the %_segdir table.
126576 **
126577 ** Return SQLCIPHER_OK if successful, or an SQLite error code if not.
126578 */
126579 static int fts3SegmentMaxLevel(Fts3Table *p, int iIndex, int *pnMax){
126580   sqlcipher3_stmt *pStmt;
126581   int rc;
126582   assert( iIndex>=0 && iIndex<p->nIndex );
126583
126584   /* Set pStmt to the compiled version of:
126585   **
126586   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
126587   **
126588   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
126589   */
126590   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
126591   if( rc!=SQLCIPHER_OK ) return rc;
126592   sqlcipher3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
126593   sqlcipher3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL - 1);
126594   if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
126595     *pnMax = sqlcipher3_column_int(pStmt, 0);
126596   }
126597   return sqlcipher3_reset(pStmt);
126598 }
126599
126600 /*
126601 ** This function is used after merging multiple segments into a single large
126602 ** segment to delete the old, now redundant, segment b-trees. Specifically,
126603 ** it:
126604 ** 
126605 **   1) Deletes all %_segments entries for the segments associated with 
126606 **      each of the SegReader objects in the array passed as the third 
126607 **      argument, and
126608 **
126609 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
126610 **      entries regardless of level if (iLevel<0).
126611 **
126612 ** SQLCIPHER_OK is returned if successful, otherwise an SQLite error code.
126613 */
126614 static int fts3DeleteSegdir(
126615   Fts3Table *p,                   /* Virtual table handle */
126616   int iIndex,                     /* Index for p->aIndex */
126617   int iLevel,                     /* Level of %_segdir entries to delete */
126618   Fts3SegReader **apSegment,      /* Array of SegReader objects */
126619   int nReader                     /* Size of array apSegment */
126620 ){
126621   int rc;                         /* Return Code */
126622   int i;                          /* Iterator variable */
126623   sqlcipher3_stmt *pDelete;          /* SQL statement to delete rows */
126624
126625   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
126626   for(i=0; rc==SQLCIPHER_OK && i<nReader; i++){
126627     Fts3SegReader *pSegment = apSegment[i];
126628     if( pSegment->iStartBlock ){
126629       sqlcipher3_bind_int64(pDelete, 1, pSegment->iStartBlock);
126630       sqlcipher3_bind_int64(pDelete, 2, pSegment->iEndBlock);
126631       sqlcipher3_step(pDelete);
126632       rc = sqlcipher3_reset(pDelete);
126633     }
126634   }
126635   if( rc!=SQLCIPHER_OK ){
126636     return rc;
126637   }
126638
126639   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
126640   if( iLevel==FTS3_SEGCURSOR_ALL ){
126641     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
126642     if( rc==SQLCIPHER_OK ){
126643       sqlcipher3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
126644       sqlcipher3_bind_int(pDelete, 2, (iIndex+1) * FTS3_SEGDIR_MAXLEVEL - 1);
126645     }
126646   }else{
126647     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
126648     if( rc==SQLCIPHER_OK ){
126649       sqlcipher3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
126650     }
126651   }
126652
126653   if( rc==SQLCIPHER_OK ){
126654     sqlcipher3_step(pDelete);
126655     rc = sqlcipher3_reset(pDelete);
126656   }
126657
126658   return rc;
126659 }
126660
126661 /*
126662 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
126663 ** a position list that may (or may not) feature multiple columns. This
126664 ** function adjusts the pointer *ppList and the length *pnList so that they
126665 ** identify the subset of the position list that corresponds to column iCol.
126666 **
126667 ** If there are no entries in the input position list for column iCol, then
126668 ** *pnList is set to zero before returning.
126669 */
126670 static void fts3ColumnFilter(
126671   int iCol,                       /* Column to filter on */
126672   char **ppList,                  /* IN/OUT: Pointer to position list */
126673   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
126674 ){
126675   char *pList = *ppList;
126676   int nList = *pnList;
126677   char *pEnd = &pList[nList];
126678   int iCurrent = 0;
126679   char *p = pList;
126680
126681   assert( iCol>=0 );
126682   while( 1 ){
126683     char c = 0;
126684     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
126685   
126686     if( iCol==iCurrent ){
126687       nList = (int)(p - pList);
126688       break;
126689     }
126690
126691     nList -= (int)(p - pList);
126692     pList = p;
126693     if( nList==0 ){
126694       break;
126695     }
126696     p = &pList[1];
126697     p += sqlcipher3Fts3GetVarint32(p, &iCurrent);
126698   }
126699
126700   *ppList = pList;
126701   *pnList = nList;
126702 }
126703
126704 /*
126705 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
126706 ** existing data). Grow the buffer if required.
126707 **
126708 ** If successful, return SQLCIPHER_OK. Otherwise, if an OOM error is encountered
126709 ** trying to resize the buffer, return SQLCIPHER_NOMEM.
126710 */
126711 static int fts3MsrBufferData(
126712   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
126713   char *pList,
126714   int nList
126715 ){
126716   if( nList>pMsr->nBuffer ){
126717     char *pNew;
126718     pMsr->nBuffer = nList*2;
126719     pNew = (char *)sqlcipher3_realloc(pMsr->aBuffer, pMsr->nBuffer);
126720     if( !pNew ) return SQLCIPHER_NOMEM;
126721     pMsr->aBuffer = pNew;
126722   }
126723
126724   memcpy(pMsr->aBuffer, pList, nList);
126725   return SQLCIPHER_OK;
126726 }
126727
126728 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrNext(
126729   Fts3Table *p,                   /* Virtual table handle */
126730   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
126731   sqlcipher3_int64 *piDocid,         /* OUT: Docid value */
126732   char **paPoslist,               /* OUT: Pointer to position list */
126733   int *pnPoslist                  /* OUT: Size of position list in bytes */
126734 ){
126735   int nMerge = pMsr->nAdvance;
126736   Fts3SegReader **apSegment = pMsr->apSegment;
126737   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
126738     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
126739   );
126740
126741   if( nMerge==0 ){
126742     *paPoslist = 0;
126743     return SQLCIPHER_OK;
126744   }
126745
126746   while( 1 ){
126747     Fts3SegReader *pSeg;
126748     pSeg = pMsr->apSegment[0];
126749
126750     if( pSeg->pOffsetList==0 ){
126751       *paPoslist = 0;
126752       break;
126753     }else{
126754       int rc;
126755       char *pList;
126756       int nList;
126757       int j;
126758       sqlcipher3_int64 iDocid = apSegment[0]->iDocid;
126759
126760       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
126761       j = 1;
126762       while( rc==SQLCIPHER_OK 
126763         && j<nMerge
126764         && apSegment[j]->pOffsetList
126765         && apSegment[j]->iDocid==iDocid
126766       ){
126767         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
126768         j++;
126769       }
126770       if( rc!=SQLCIPHER_OK ) return rc;
126771       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
126772
126773       if( pMsr->iColFilter>=0 ){
126774         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
126775       }
126776
126777       if( nList>0 ){
126778         if( fts3SegReaderIsPending(apSegment[0]) ){
126779           rc = fts3MsrBufferData(pMsr, pList, nList+1);
126780           if( rc!=SQLCIPHER_OK ) return rc;
126781           *paPoslist = pMsr->aBuffer;
126782           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
126783         }else{
126784           *paPoslist = pList;
126785         }
126786         *piDocid = iDocid;
126787         *pnPoslist = nList;
126788         break;
126789       }
126790     }
126791   }
126792
126793   return SQLCIPHER_OK;
126794 }
126795
126796 static int fts3SegReaderStart(
126797   Fts3Table *p,                   /* Virtual table handle */
126798   Fts3MultiSegReader *pCsr,       /* Cursor object */
126799   const char *zTerm,              /* Term searched for (or NULL) */
126800   int nTerm                       /* Length of zTerm in bytes */
126801 ){
126802   int i;
126803   int nSeg = pCsr->nSegment;
126804
126805   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
126806   ** for, then advance each segment iterator until it points to a term of
126807   ** equal or greater value than the specified term. This prevents many
126808   ** unnecessary merge/sort operations for the case where single segment
126809   ** b-tree leaf nodes contain more than one term.
126810   */
126811   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
126812     Fts3SegReader *pSeg = pCsr->apSegment[i];
126813     do {
126814       int rc = fts3SegReaderNext(p, pSeg, 0);
126815       if( rc!=SQLCIPHER_OK ) return rc;
126816     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
126817   }
126818   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
126819
126820   return SQLCIPHER_OK;
126821 }
126822
126823 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStart(
126824   Fts3Table *p,                   /* Virtual table handle */
126825   Fts3MultiSegReader *pCsr,       /* Cursor object */
126826   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
126827 ){
126828   pCsr->pFilter = pFilter;
126829   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
126830 }
126831
126832 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrStart(
126833   Fts3Table *p,                   /* Virtual table handle */
126834   Fts3MultiSegReader *pCsr,       /* Cursor object */
126835   int iCol,                       /* Column to match on. */
126836   const char *zTerm,              /* Term to iterate through a doclist for */
126837   int nTerm                       /* Number of bytes in zTerm */
126838 ){
126839   int i;
126840   int rc;
126841   int nSegment = pCsr->nSegment;
126842   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
126843     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
126844   );
126845
126846   assert( pCsr->pFilter==0 );
126847   assert( zTerm && nTerm>0 );
126848
126849   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
126850   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
126851   if( rc!=SQLCIPHER_OK ) return rc;
126852
126853   /* Determine how many of the segments actually point to zTerm/nTerm. */
126854   for(i=0; i<nSegment; i++){
126855     Fts3SegReader *pSeg = pCsr->apSegment[i];
126856     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
126857       break;
126858     }
126859   }
126860   pCsr->nAdvance = i;
126861
126862   /* Advance each of the segments to point to the first docid. */
126863   for(i=0; i<pCsr->nAdvance; i++){
126864     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
126865     if( rc!=SQLCIPHER_OK ) return rc;
126866   }
126867   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
126868
126869   assert( iCol<0 || iCol<p->nColumn );
126870   pCsr->iColFilter = iCol;
126871
126872   return SQLCIPHER_OK;
126873 }
126874
126875 /*
126876 ** This function is called on a MultiSegReader that has been started using
126877 ** sqlcipher3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
126878 ** have been made. Calling this function puts the MultiSegReader in such
126879 ** a state that if the next two calls are:
126880 **
126881 **   sqlcipher3Fts3SegReaderStart()
126882 **   sqlcipher3Fts3SegReaderStep()
126883 **
126884 ** then the entire doclist for the term is available in 
126885 ** MultiSegReader.aDoclist/nDoclist.
126886 */
126887 SQLCIPHER_PRIVATE int sqlcipher3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
126888   int i;                          /* Used to iterate through segment-readers */
126889
126890   assert( pCsr->zTerm==0 );
126891   assert( pCsr->nTerm==0 );
126892   assert( pCsr->aDoclist==0 );
126893   assert( pCsr->nDoclist==0 );
126894
126895   pCsr->nAdvance = 0;
126896   pCsr->bRestart = 1;
126897   for(i=0; i<pCsr->nSegment; i++){
126898     pCsr->apSegment[i]->pOffsetList = 0;
126899     pCsr->apSegment[i]->nOffsetList = 0;
126900     pCsr->apSegment[i]->iDocid = 0;
126901   }
126902
126903   return SQLCIPHER_OK;
126904 }
126905
126906
126907 SQLCIPHER_PRIVATE int sqlcipher3Fts3SegReaderStep(
126908   Fts3Table *p,                   /* Virtual table handle */
126909   Fts3MultiSegReader *pCsr        /* Cursor object */
126910 ){
126911   int rc = SQLCIPHER_OK;
126912
126913   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
126914   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
126915   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
126916   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
126917   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
126918   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
126919
126920   Fts3SegReader **apSegment = pCsr->apSegment;
126921   int nSegment = pCsr->nSegment;
126922   Fts3SegFilter *pFilter = pCsr->pFilter;
126923   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
126924     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
126925   );
126926
126927   if( pCsr->nSegment==0 ) return SQLCIPHER_OK;
126928
126929   do {
126930     int nMerge;
126931     int i;
126932   
126933     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
126934     ** forward. Then sort the list in order of current term again.  
126935     */
126936     for(i=0; i<pCsr->nAdvance; i++){
126937       rc = fts3SegReaderNext(p, apSegment[i], 0);
126938       if( rc!=SQLCIPHER_OK ) return rc;
126939     }
126940     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
126941     pCsr->nAdvance = 0;
126942
126943     /* If all the seg-readers are at EOF, we're finished. return SQLCIPHER_OK. */
126944     assert( rc==SQLCIPHER_OK );
126945     if( apSegment[0]->aNode==0 ) break;
126946
126947     pCsr->nTerm = apSegment[0]->nTerm;
126948     pCsr->zTerm = apSegment[0]->zTerm;
126949
126950     /* If this is a prefix-search, and if the term that apSegment[0] points
126951     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
126952     ** required callbacks have been made. In this case exit early.
126953     **
126954     ** Similarly, if this is a search for an exact match, and the first term
126955     ** of segment apSegment[0] is not a match, exit early.
126956     */
126957     if( pFilter->zTerm && !isScan ){
126958       if( pCsr->nTerm<pFilter->nTerm 
126959        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
126960        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
126961       ){
126962         break;
126963       }
126964     }
126965
126966     nMerge = 1;
126967     while( nMerge<nSegment 
126968         && apSegment[nMerge]->aNode
126969         && apSegment[nMerge]->nTerm==pCsr->nTerm 
126970         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
126971     ){
126972       nMerge++;
126973     }
126974
126975     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
126976     if( nMerge==1 
126977      && !isIgnoreEmpty 
126978      && !isFirst 
126979      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
126980     ){
126981       pCsr->nDoclist = apSegment[0]->nDoclist;
126982       if( fts3SegReaderIsPending(apSegment[0]) ){
126983         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
126984         pCsr->aDoclist = pCsr->aBuffer;
126985       }else{
126986         pCsr->aDoclist = apSegment[0]->aDoclist;
126987       }
126988       if( rc==SQLCIPHER_OK ) rc = SQLCIPHER_ROW;
126989     }else{
126990       int nDoclist = 0;           /* Size of doclist */
126991       sqlcipher3_int64 iPrev = 0;    /* Previous docid stored in doclist */
126992
126993       /* The current term of the first nMerge entries in the array
126994       ** of Fts3SegReader objects is the same. The doclists must be merged
126995       ** and a single term returned with the merged doclist.
126996       */
126997       for(i=0; i<nMerge; i++){
126998         fts3SegReaderFirstDocid(p, apSegment[i]);
126999       }
127000       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
127001       while( apSegment[0]->pOffsetList ){
127002         int j;                    /* Number of segments that share a docid */
127003         char *pList;
127004         int nList;
127005         int nByte;
127006         sqlcipher3_int64 iDocid = apSegment[0]->iDocid;
127007         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127008         j = 1;
127009         while( j<nMerge
127010             && apSegment[j]->pOffsetList
127011             && apSegment[j]->iDocid==iDocid
127012         ){
127013           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127014           j++;
127015         }
127016
127017         if( isColFilter ){
127018           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
127019         }
127020
127021         if( !isIgnoreEmpty || nList>0 ){
127022
127023           /* Calculate the 'docid' delta value to write into the merged 
127024           ** doclist. */
127025           sqlcipher3_int64 iDelta;
127026           if( p->bDescIdx && nDoclist>0 ){
127027             iDelta = iPrev - iDocid;
127028           }else{
127029             iDelta = iDocid - iPrev;
127030           }
127031           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
127032           assert( nDoclist>0 || iDelta==iDocid );
127033
127034           nByte = sqlcipher3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
127035           if( nDoclist+nByte>pCsr->nBuffer ){
127036             char *aNew;
127037             pCsr->nBuffer = (nDoclist+nByte)*2;
127038             aNew = sqlcipher3_realloc(pCsr->aBuffer, pCsr->nBuffer);
127039             if( !aNew ){
127040               return SQLCIPHER_NOMEM;
127041             }
127042             pCsr->aBuffer = aNew;
127043           }
127044
127045           if( isFirst ){
127046             char *a = &pCsr->aBuffer[nDoclist];
127047             int nWrite;
127048            
127049             nWrite = sqlcipher3Fts3FirstFilter(iDelta, pList, nList, a);
127050             if( nWrite ){
127051               iPrev = iDocid;
127052               nDoclist += nWrite;
127053             }
127054           }else{
127055             nDoclist += sqlcipher3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
127056             iPrev = iDocid;
127057             if( isRequirePos ){
127058               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
127059               nDoclist += nList;
127060               pCsr->aBuffer[nDoclist++] = '\0';
127061             }
127062           }
127063         }
127064
127065         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
127066       }
127067       if( nDoclist>0 ){
127068         pCsr->aDoclist = pCsr->aBuffer;
127069         pCsr->nDoclist = nDoclist;
127070         rc = SQLCIPHER_ROW;
127071       }
127072     }
127073     pCsr->nAdvance = nMerge;
127074   }while( rc==SQLCIPHER_OK );
127075
127076   return rc;
127077 }
127078
127079
127080 SQLCIPHER_PRIVATE void sqlcipher3Fts3SegReaderFinish(
127081   Fts3MultiSegReader *pCsr       /* Cursor object */
127082 ){
127083   if( pCsr ){
127084     int i;
127085     for(i=0; i<pCsr->nSegment; i++){
127086       sqlcipher3Fts3SegReaderFree(pCsr->apSegment[i]);
127087     }
127088     sqlcipher3_free(pCsr->apSegment);
127089     sqlcipher3_free(pCsr->aBuffer);
127090
127091     pCsr->nSegment = 0;
127092     pCsr->apSegment = 0;
127093     pCsr->aBuffer = 0;
127094   }
127095 }
127096
127097 /*
127098 ** Merge all level iLevel segments in the database into a single 
127099 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
127100 ** single segment with a level equal to the numerically largest level 
127101 ** currently present in the database.
127102 **
127103 ** If this function is called with iLevel<0, but there is only one
127104 ** segment in the database, SQLCIPHER_DONE is returned immediately. 
127105 ** Otherwise, if successful, SQLCIPHER_OK is returned. If an error occurs, 
127106 ** an SQLite error code is returned.
127107 */
127108 static int fts3SegmentMerge(Fts3Table *p, int iIndex, int iLevel){
127109   int rc;                         /* Return code */
127110   int iIdx = 0;                   /* Index of new segment */
127111   int iNewLevel = 0;              /* Level/index to create new segment at */
127112   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
127113   Fts3SegFilter filter;           /* Segment term filter condition */
127114   Fts3MultiSegReader csr;        /* Cursor to iterate through level(s) */
127115   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
127116
127117   assert( iLevel==FTS3_SEGCURSOR_ALL
127118        || iLevel==FTS3_SEGCURSOR_PENDING
127119        || iLevel>=0
127120   );
127121   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127122   assert( iIndex>=0 && iIndex<p->nIndex );
127123
127124   rc = sqlcipher3Fts3SegReaderCursor(p, iIndex, iLevel, 0, 0, 1, 0, &csr);
127125   if( rc!=SQLCIPHER_OK || csr.nSegment==0 ) goto finished;
127126
127127   if( iLevel==FTS3_SEGCURSOR_ALL ){
127128     /* This call is to merge all segments in the database to a single
127129     ** segment. The level of the new segment is equal to the the numerically 
127130     ** greatest segment level currently present in the database for this
127131     ** index. The idx of the new segment is always 0.  */
127132     if( csr.nSegment==1 ){
127133       rc = SQLCIPHER_DONE;
127134       goto finished;
127135     }
127136     rc = fts3SegmentMaxLevel(p, iIndex, &iNewLevel);
127137     bIgnoreEmpty = 1;
127138
127139   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
127140     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL; 
127141     rc = fts3AllocateSegdirIdx(p, iIndex, 0, &iIdx);
127142   }else{
127143     /* This call is to merge all segments at level iLevel. find the next
127144     ** available segment index at level iLevel+1. The call to
127145     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
127146     ** a single iLevel+2 segment if necessary.  */
127147     rc = fts3AllocateSegdirIdx(p, iIndex, iLevel+1, &iIdx);
127148     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL + iLevel+1;
127149   }
127150   if( rc!=SQLCIPHER_OK ) goto finished;
127151   assert( csr.nSegment>0 );
127152   assert( iNewLevel>=(iIndex*FTS3_SEGDIR_MAXLEVEL) );
127153   assert( iNewLevel<((iIndex+1)*FTS3_SEGDIR_MAXLEVEL) );
127154
127155   memset(&filter, 0, sizeof(Fts3SegFilter));
127156   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
127157   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
127158
127159   rc = sqlcipher3Fts3SegReaderStart(p, &csr, &filter);
127160   while( SQLCIPHER_OK==rc ){
127161     rc = sqlcipher3Fts3SegReaderStep(p, &csr);
127162     if( rc!=SQLCIPHER_ROW ) break;
127163     rc = fts3SegWriterAdd(p, &pWriter, 1, 
127164         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
127165   }
127166   if( rc!=SQLCIPHER_OK ) goto finished;
127167   assert( pWriter );
127168
127169   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
127170     rc = fts3DeleteSegdir(p, iIndex, iLevel, csr.apSegment, csr.nSegment);
127171     if( rc!=SQLCIPHER_OK ) goto finished;
127172   }
127173   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
127174
127175  finished:
127176   fts3SegWriterFree(pWriter);
127177   sqlcipher3Fts3SegReaderFinish(&csr);
127178   return rc;
127179 }
127180
127181
127182 /* 
127183 ** Flush the contents of pendingTerms to level 0 segments.
127184 */
127185 SQLCIPHER_PRIVATE int sqlcipher3Fts3PendingTermsFlush(Fts3Table *p){
127186   int rc = SQLCIPHER_OK;
127187   int i;
127188   for(i=0; rc==SQLCIPHER_OK && i<p->nIndex; i++){
127189     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_PENDING);
127190     if( rc==SQLCIPHER_DONE ) rc = SQLCIPHER_OK;
127191   }
127192   sqlcipher3Fts3PendingTermsClear(p);
127193   return rc;
127194 }
127195
127196 /*
127197 ** Encode N integers as varints into a blob.
127198 */
127199 static void fts3EncodeIntArray(
127200   int N,             /* The number of integers to encode */
127201   u32 *a,            /* The integer values */
127202   char *zBuf,        /* Write the BLOB here */
127203   int *pNBuf         /* Write number of bytes if zBuf[] used here */
127204 ){
127205   int i, j;
127206   for(i=j=0; i<N; i++){
127207     j += sqlcipher3Fts3PutVarint(&zBuf[j], (sqlcipher3_int64)a[i]);
127208   }
127209   *pNBuf = j;
127210 }
127211
127212 /*
127213 ** Decode a blob of varints into N integers
127214 */
127215 static void fts3DecodeIntArray(
127216   int N,             /* The number of integers to decode */
127217   u32 *a,            /* Write the integer values */
127218   const char *zBuf,  /* The BLOB containing the varints */
127219   int nBuf           /* size of the BLOB */
127220 ){
127221   int i, j;
127222   UNUSED_PARAMETER(nBuf);
127223   for(i=j=0; i<N; i++){
127224     sqlcipher3_int64 x;
127225     j += sqlcipher3Fts3GetVarint(&zBuf[j], &x);
127226     assert(j<=nBuf);
127227     a[i] = (u32)(x & 0xffffffff);
127228   }
127229 }
127230
127231 /*
127232 ** Insert the sizes (in tokens) for each column of the document
127233 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
127234 ** a blob of varints.
127235 */
127236 static void fts3InsertDocsize(
127237   int *pRC,                       /* Result code */
127238   Fts3Table *p,                   /* Table into which to insert */
127239   u32 *aSz                        /* Sizes of each column, in tokens */
127240 ){
127241   char *pBlob;             /* The BLOB encoding of the document size */
127242   int nBlob;               /* Number of bytes in the BLOB */
127243   sqlcipher3_stmt *pStmt;     /* Statement used to insert the encoding */
127244   int rc;                  /* Result code from subfunctions */
127245
127246   if( *pRC ) return;
127247   pBlob = sqlcipher3_malloc( 10*p->nColumn );
127248   if( pBlob==0 ){
127249     *pRC = SQLCIPHER_NOMEM;
127250     return;
127251   }
127252   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
127253   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
127254   if( rc ){
127255     sqlcipher3_free(pBlob);
127256     *pRC = rc;
127257     return;
127258   }
127259   sqlcipher3_bind_int64(pStmt, 1, p->iPrevDocid);
127260   sqlcipher3_bind_blob(pStmt, 2, pBlob, nBlob, sqlcipher3_free);
127261   sqlcipher3_step(pStmt);
127262   *pRC = sqlcipher3_reset(pStmt);
127263 }
127264
127265 /*
127266 ** Record 0 of the %_stat table contains a blob consisting of N varints,
127267 ** where N is the number of user defined columns in the fts3 table plus
127268 ** two. If nCol is the number of user defined columns, then values of the 
127269 ** varints are set as follows:
127270 **
127271 **   Varint 0:       Total number of rows in the table.
127272 **
127273 **   Varint 1..nCol: For each column, the total number of tokens stored in
127274 **                   the column for all rows of the table.
127275 **
127276 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
127277 **                   columns of all rows of the table.
127278 **
127279 */
127280 static void fts3UpdateDocTotals(
127281   int *pRC,                       /* The result code */
127282   Fts3Table *p,                   /* Table being updated */
127283   u32 *aSzIns,                    /* Size increases */
127284   u32 *aSzDel,                    /* Size decreases */
127285   int nChng                       /* Change in the number of documents */
127286 ){
127287   char *pBlob;             /* Storage for BLOB written into %_stat */
127288   int nBlob;               /* Size of BLOB written into %_stat */
127289   u32 *a;                  /* Array of integers that becomes the BLOB */
127290   sqlcipher3_stmt *pStmt;     /* Statement for reading and writing */
127291   int i;                   /* Loop counter */
127292   int rc;                  /* Result code from subfunctions */
127293
127294   const int nStat = p->nColumn+2;
127295
127296   if( *pRC ) return;
127297   a = sqlcipher3_malloc( (sizeof(u32)+10)*nStat );
127298   if( a==0 ){
127299     *pRC = SQLCIPHER_NOMEM;
127300     return;
127301   }
127302   pBlob = (char*)&a[nStat];
127303   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
127304   if( rc ){
127305     sqlcipher3_free(a);
127306     *pRC = rc;
127307     return;
127308   }
127309   if( sqlcipher3_step(pStmt)==SQLCIPHER_ROW ){
127310     fts3DecodeIntArray(nStat, a,
127311          sqlcipher3_column_blob(pStmt, 0),
127312          sqlcipher3_column_bytes(pStmt, 0));
127313   }else{
127314     memset(a, 0, sizeof(u32)*(nStat) );
127315   }
127316   sqlcipher3_reset(pStmt);
127317   if( nChng<0 && a[0]<(u32)(-nChng) ){
127318     a[0] = 0;
127319   }else{
127320     a[0] += nChng;
127321   }
127322   for(i=0; i<p->nColumn+1; i++){
127323     u32 x = a[i+1];
127324     if( x+aSzIns[i] < aSzDel[i] ){
127325       x = 0;
127326     }else{
127327       x = x + aSzIns[i] - aSzDel[i];
127328     }
127329     a[i+1] = x;
127330   }
127331   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
127332   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
127333   if( rc ){
127334     sqlcipher3_free(a);
127335     *pRC = rc;
127336     return;
127337   }
127338   sqlcipher3_bind_blob(pStmt, 1, pBlob, nBlob, SQLCIPHER_STATIC);
127339   sqlcipher3_step(pStmt);
127340   *pRC = sqlcipher3_reset(pStmt);
127341   sqlcipher3_free(a);
127342 }
127343
127344 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
127345   int i;
127346   int bSeenDone = 0;
127347   int rc = SQLCIPHER_OK;
127348   for(i=0; rc==SQLCIPHER_OK && i<p->nIndex; i++){
127349     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_ALL);
127350     if( rc==SQLCIPHER_DONE ){
127351       bSeenDone = 1;
127352       rc = SQLCIPHER_OK;
127353     }
127354   }
127355   sqlcipher3Fts3SegmentsClose(p);
127356   sqlcipher3Fts3PendingTermsClear(p);
127357
127358   return (rc==SQLCIPHER_OK && bReturnDone && bSeenDone) ? SQLCIPHER_DONE : rc;
127359 }
127360
127361 /*
127362 ** This function is called when the user executes the following statement:
127363 **
127364 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
127365 **
127366 ** The entire FTS index is discarded and rebuilt. If the table is one 
127367 ** created using the content=xxx option, then the new index is based on
127368 ** the current contents of the xxx table. Otherwise, it is rebuilt based
127369 ** on the contents of the %_content table.
127370 */
127371 static int fts3DoRebuild(Fts3Table *p){
127372   int rc;                         /* Return Code */
127373
127374   rc = fts3DeleteAll(p, 0);
127375   if( rc==SQLCIPHER_OK ){
127376     u32 *aSz = 0;
127377     u32 *aSzIns = 0;
127378     u32 *aSzDel = 0;
127379     sqlcipher3_stmt *pStmt = 0;
127380     int nEntry = 0;
127381
127382     /* Compose and prepare an SQL statement to loop through the content table */
127383     char *zSql = sqlcipher3_mprintf("SELECT %s" , p->zReadExprlist);
127384     if( !zSql ){
127385       rc = SQLCIPHER_NOMEM;
127386     }else{
127387       rc = sqlcipher3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
127388       sqlcipher3_free(zSql);
127389     }
127390
127391     if( rc==SQLCIPHER_OK ){
127392       int nByte = sizeof(u32) * (p->nColumn+1)*3;
127393       aSz = (u32 *)sqlcipher3_malloc(nByte);
127394       if( aSz==0 ){
127395         rc = SQLCIPHER_NOMEM;
127396       }else{
127397         memset(aSz, 0, nByte);
127398         aSzIns = &aSz[p->nColumn+1];
127399         aSzDel = &aSzIns[p->nColumn+1];
127400       }
127401     }
127402
127403     while( rc==SQLCIPHER_OK && SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
127404       int iCol;
127405       rc = fts3PendingTermsDocid(p, sqlcipher3_column_int64(pStmt, 0));
127406       aSz[p->nColumn] = 0;
127407       for(iCol=0; rc==SQLCIPHER_OK && iCol<p->nColumn; iCol++){
127408         const char *z = (const char *) sqlcipher3_column_text(pStmt, iCol+1);
127409         rc = fts3PendingTermsAdd(p, z, iCol, &aSz[iCol]);
127410         aSz[p->nColumn] += sqlcipher3_column_bytes(pStmt, iCol+1);
127411       }
127412       if( p->bHasDocsize ){
127413         fts3InsertDocsize(&rc, p, aSz);
127414       }
127415       if( rc!=SQLCIPHER_OK ){
127416         sqlcipher3_finalize(pStmt);
127417         pStmt = 0;
127418       }else{
127419         nEntry++;
127420         for(iCol=0; iCol<=p->nColumn; iCol++){
127421           aSzIns[iCol] += aSz[iCol];
127422         }
127423       }
127424     }
127425     if( p->bHasStat ){
127426       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
127427     }
127428     sqlcipher3_free(aSz);
127429
127430     if( pStmt ){
127431       int rc2 = sqlcipher3_finalize(pStmt);
127432       if( rc==SQLCIPHER_OK ){
127433         rc = rc2;
127434       }
127435     }
127436   }
127437
127438   return rc;
127439 }
127440
127441 /*
127442 ** Handle a 'special' INSERT of the form:
127443 **
127444 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
127445 **
127446 ** Argument pVal contains the result of <expr>. Currently the only 
127447 ** meaningful value to insert is the text 'optimize'.
127448 */
127449 static int fts3SpecialInsert(Fts3Table *p, sqlcipher3_value *pVal){
127450   int rc;                         /* Return Code */
127451   const char *zVal = (const char *)sqlcipher3_value_text(pVal);
127452   int nVal = sqlcipher3_value_bytes(pVal);
127453
127454   if( !zVal ){
127455     return SQLCIPHER_NOMEM;
127456   }else if( nVal==8 && 0==sqlcipher3_strnicmp(zVal, "optimize", 8) ){
127457     rc = fts3DoOptimize(p, 0);
127458   }else if( nVal==7 && 0==sqlcipher3_strnicmp(zVal, "rebuild", 7) ){
127459     rc = fts3DoRebuild(p);
127460 #ifdef SQLCIPHER_TEST
127461   }else if( nVal>9 && 0==sqlcipher3_strnicmp(zVal, "nodesize=", 9) ){
127462     p->nNodeSize = atoi(&zVal[9]);
127463     rc = SQLCIPHER_OK;
127464   }else if( nVal>11 && 0==sqlcipher3_strnicmp(zVal, "maxpending=", 9) ){
127465     p->nMaxPendingData = atoi(&zVal[11]);
127466     rc = SQLCIPHER_OK;
127467 #endif
127468   }else{
127469     rc = SQLCIPHER_ERROR;
127470   }
127471
127472   return rc;
127473 }
127474
127475 /*
127476 ** Delete all cached deferred doclists. Deferred doclists are cached
127477 ** (allocated) by the sqlcipher3Fts3CacheDeferredDoclists() function.
127478 */
127479 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
127480   Fts3DeferredToken *pDef;
127481   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
127482     fts3PendingListDelete(pDef->pList);
127483     pDef->pList = 0;
127484   }
127485 }
127486
127487 /*
127488 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
127489 ** this list using sqlcipher3Fts3DeferToken().
127490 */
127491 SQLCIPHER_PRIVATE void sqlcipher3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
127492   Fts3DeferredToken *pDef;
127493   Fts3DeferredToken *pNext;
127494   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
127495     pNext = pDef->pNext;
127496     fts3PendingListDelete(pDef->pList);
127497     sqlcipher3_free(pDef);
127498   }
127499   pCsr->pDeferred = 0;
127500 }
127501
127502 /*
127503 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
127504 ** based on the row that pCsr currently points to.
127505 **
127506 ** A deferred-doclist is like any other doclist with position information
127507 ** included, except that it only contains entries for a single row of the
127508 ** table, not for all rows.
127509 */
127510 SQLCIPHER_PRIVATE int sqlcipher3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
127511   int rc = SQLCIPHER_OK;             /* Return code */
127512   if( pCsr->pDeferred ){
127513     int i;                        /* Used to iterate through table columns */
127514     sqlcipher3_int64 iDocid;         /* Docid of the row pCsr points to */
127515     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
127516   
127517     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
127518     sqlcipher3_tokenizer *pT = p->pTokenizer;
127519     sqlcipher3_tokenizer_module const *pModule = pT->pModule;
127520    
127521     assert( pCsr->isRequireSeek==0 );
127522     iDocid = sqlcipher3_column_int64(pCsr->pStmt, 0);
127523   
127524     for(i=0; i<p->nColumn && rc==SQLCIPHER_OK; i++){
127525       const char *zText = (const char *)sqlcipher3_column_text(pCsr->pStmt, i+1);
127526       sqlcipher3_tokenizer_cursor *pTC = 0;
127527   
127528       rc = pModule->xOpen(pT, zText, -1, &pTC);
127529       while( rc==SQLCIPHER_OK ){
127530         char const *zToken;       /* Buffer containing token */
127531         int nToken;               /* Number of bytes in token */
127532         int iDum1, iDum2;         /* Dummy variables */
127533         int iPos;                 /* Position of token in zText */
127534   
127535         pTC->pTokenizer = pT;
127536         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
127537         for(pDef=pCsr->pDeferred; pDef && rc==SQLCIPHER_OK; pDef=pDef->pNext){
127538           Fts3PhraseToken *pPT = pDef->pToken;
127539           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
127540            && (pPT->bFirst==0 || iPos==0)
127541            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
127542            && (0==memcmp(zToken, pPT->z, pPT->n))
127543           ){
127544             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
127545           }
127546         }
127547       }
127548       if( pTC ) pModule->xClose(pTC);
127549       if( rc==SQLCIPHER_DONE ) rc = SQLCIPHER_OK;
127550     }
127551   
127552     for(pDef=pCsr->pDeferred; pDef && rc==SQLCIPHER_OK; pDef=pDef->pNext){
127553       if( pDef->pList ){
127554         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
127555       }
127556     }
127557   }
127558
127559   return rc;
127560 }
127561
127562 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferredTokenList(
127563   Fts3DeferredToken *p, 
127564   char **ppData, 
127565   int *pnData
127566 ){
127567   char *pRet;
127568   int nSkip;
127569   sqlcipher3_int64 dummy;
127570
127571   *ppData = 0;
127572   *pnData = 0;
127573
127574   if( p->pList==0 ){
127575     return SQLCIPHER_OK;
127576   }
127577
127578   pRet = (char *)sqlcipher3_malloc(p->pList->nData);
127579   if( !pRet ) return SQLCIPHER_NOMEM;
127580
127581   nSkip = sqlcipher3Fts3GetVarint(p->pList->aData, &dummy);
127582   *pnData = p->pList->nData - nSkip;
127583   *ppData = pRet;
127584   
127585   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
127586   return SQLCIPHER_OK;
127587 }
127588
127589 /*
127590 ** Add an entry for token pToken to the pCsr->pDeferred list.
127591 */
127592 SQLCIPHER_PRIVATE int sqlcipher3Fts3DeferToken(
127593   Fts3Cursor *pCsr,               /* Fts3 table cursor */
127594   Fts3PhraseToken *pToken,        /* Token to defer */
127595   int iCol                        /* Column that token must appear in (or -1) */
127596 ){
127597   Fts3DeferredToken *pDeferred;
127598   pDeferred = sqlcipher3_malloc(sizeof(*pDeferred));
127599   if( !pDeferred ){
127600     return SQLCIPHER_NOMEM;
127601   }
127602   memset(pDeferred, 0, sizeof(*pDeferred));
127603   pDeferred->pToken = pToken;
127604   pDeferred->pNext = pCsr->pDeferred; 
127605   pDeferred->iCol = iCol;
127606   pCsr->pDeferred = pDeferred;
127607
127608   assert( pToken->pDeferred==0 );
127609   pToken->pDeferred = pDeferred;
127610
127611   return SQLCIPHER_OK;
127612 }
127613
127614 /*
127615 ** SQLite value pRowid contains the rowid of a row that may or may not be
127616 ** present in the FTS3 table. If it is, delete it and adjust the contents
127617 ** of subsiduary data structures accordingly.
127618 */
127619 static int fts3DeleteByRowid(
127620   Fts3Table *p, 
127621   sqlcipher3_value *pRowid, 
127622   int *pnDoc,
127623   u32 *aSzDel
127624 ){
127625   int isEmpty = 0;
127626   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
127627   if( rc==SQLCIPHER_OK ){
127628     if( isEmpty ){
127629       /* Deleting this row means the whole table is empty. In this case
127630       ** delete the contents of all three tables and throw away any
127631       ** data in the pendingTerms hash table.  */
127632       rc = fts3DeleteAll(p, 1);
127633       *pnDoc = *pnDoc - 1;
127634     }else{
127635       sqlcipher3_int64 iRemove = sqlcipher3_value_int64(pRowid);
127636       rc = fts3PendingTermsDocid(p, iRemove);
127637       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
127638       if( p->zContentTbl==0 ){
127639         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
127640         if( sqlcipher3_changes(p->db) ) *pnDoc = *pnDoc - 1;
127641       }else{
127642         *pnDoc = *pnDoc - 1;
127643       }
127644       if( p->bHasDocsize ){
127645         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
127646       }
127647     }
127648   }
127649
127650   return rc;
127651 }
127652
127653 /*
127654 ** This function does the work for the xUpdate method of FTS3 virtual
127655 ** tables.
127656 */
127657 SQLCIPHER_PRIVATE int sqlcipher3Fts3UpdateMethod(
127658   sqlcipher3_vtab *pVtab,            /* FTS3 vtab object */
127659   int nArg,                       /* Size of argument array */
127660   sqlcipher3_value **apVal,          /* Array of arguments */
127661   sqlcipher_int64 *pRowid            /* OUT: The affected (or effected) rowid */
127662 ){
127663   Fts3Table *p = (Fts3Table *)pVtab;
127664   int rc = SQLCIPHER_OK;             /* Return Code */
127665   int isRemove = 0;               /* True for an UPDATE or DELETE */
127666   u32 *aSzIns = 0;                /* Sizes of inserted documents */
127667   u32 *aSzDel;                    /* Sizes of deleted documents */
127668   int nChng = 0;                  /* Net change in number of documents */
127669   int bInsertDone = 0;
127670
127671   assert( p->pSegments==0 );
127672
127673   /* Check for a "special" INSERT operation. One of the form:
127674   **
127675   **   INSERT INTO xyz(xyz) VALUES('command');
127676   */
127677   if( nArg>1 
127678    && sqlcipher3_value_type(apVal[0])==SQLCIPHER_NULL 
127679    && sqlcipher3_value_type(apVal[p->nColumn+2])!=SQLCIPHER_NULL 
127680   ){
127681     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
127682     goto update_out;
127683   }
127684
127685   /* Allocate space to hold the change in document sizes */
127686   aSzIns = sqlcipher3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
127687   if( aSzIns==0 ){
127688     rc = SQLCIPHER_NOMEM;
127689     goto update_out;
127690   }
127691   aSzDel = &aSzIns[p->nColumn+1];
127692   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
127693
127694   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
127695   ** value, then this operation requires constraint handling.
127696   **
127697   ** If the on-conflict mode is REPLACE, this means that the existing row
127698   ** should be deleted from the database before inserting the new row. Or,
127699   ** if the on-conflict mode is other than REPLACE, then this method must
127700   ** detect the conflict and return SQLCIPHER_CONSTRAINT before beginning to
127701   ** modify the database file.
127702   */
127703   if( nArg>1 && p->zContentTbl==0 ){
127704     /* Find the value object that holds the new rowid value. */
127705     sqlcipher3_value *pNewRowid = apVal[3+p->nColumn];
127706     if( sqlcipher3_value_type(pNewRowid)==SQLCIPHER_NULL ){
127707       pNewRowid = apVal[1];
127708     }
127709
127710     if( sqlcipher3_value_type(pNewRowid)!=SQLCIPHER_NULL && ( 
127711         sqlcipher3_value_type(apVal[0])==SQLCIPHER_NULL
127712      || sqlcipher3_value_int64(apVal[0])!=sqlcipher3_value_int64(pNewRowid)
127713     )){
127714       /* The new rowid is not NULL (in this case the rowid will be
127715       ** automatically assigned and there is no chance of a conflict), and 
127716       ** the statement is either an INSERT or an UPDATE that modifies the
127717       ** rowid column. So if the conflict mode is REPLACE, then delete any
127718       ** existing row with rowid=pNewRowid. 
127719       **
127720       ** Or, if the conflict mode is not REPLACE, insert the new record into 
127721       ** the %_content table. If we hit the duplicate rowid constraint (or any
127722       ** other error) while doing so, return immediately.
127723       **
127724       ** This branch may also run if pNewRowid contains a value that cannot
127725       ** be losslessly converted to an integer. In this case, the eventual 
127726       ** call to fts3InsertData() (either just below or further on in this
127727       ** function) will return SQLCIPHER_MISMATCH. If fts3DeleteByRowid is 
127728       ** invoked, it will delete zero rows (since no row will have
127729       ** docid=$pNewRowid if $pNewRowid is not an integer value).
127730       */
127731       if( sqlcipher3_vtab_on_conflict(p->db)==SQLCIPHER_REPLACE ){
127732         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
127733       }else{
127734         rc = fts3InsertData(p, apVal, pRowid);
127735         bInsertDone = 1;
127736       }
127737     }
127738   }
127739   if( rc!=SQLCIPHER_OK ){
127740     goto update_out;
127741   }
127742
127743   /* If this is a DELETE or UPDATE operation, remove the old record. */
127744   if( sqlcipher3_value_type(apVal[0])!=SQLCIPHER_NULL ){
127745     assert( sqlcipher3_value_type(apVal[0])==SQLCIPHER_INTEGER );
127746     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
127747     isRemove = 1;
127748   }
127749   
127750   /* If this is an INSERT or UPDATE operation, insert the new record. */
127751   if( nArg>1 && rc==SQLCIPHER_OK ){
127752     if( bInsertDone==0 ){
127753       rc = fts3InsertData(p, apVal, pRowid);
127754       if( rc==SQLCIPHER_CONSTRAINT && p->zContentTbl==0 ){
127755         rc = FTS_CORRUPT_VTAB;
127756       }
127757     }
127758     if( rc==SQLCIPHER_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
127759       rc = fts3PendingTermsDocid(p, *pRowid);
127760     }
127761     if( rc==SQLCIPHER_OK ){
127762       assert( p->iPrevDocid==*pRowid );
127763       rc = fts3InsertTerms(p, apVal, aSzIns);
127764     }
127765     if( p->bHasDocsize ){
127766       fts3InsertDocsize(&rc, p, aSzIns);
127767     }
127768     nChng++;
127769   }
127770
127771   if( p->bHasStat ){
127772     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
127773   }
127774
127775  update_out:
127776   sqlcipher3_free(aSzIns);
127777   sqlcipher3Fts3SegmentsClose(p);
127778   return rc;
127779 }
127780
127781 /* 
127782 ** Flush any data in the pending-terms hash table to disk. If successful,
127783 ** merge all segments in the database (including the new segment, if 
127784 ** there was any data to flush) into a single segment. 
127785 */
127786 SQLCIPHER_PRIVATE int sqlcipher3Fts3Optimize(Fts3Table *p){
127787   int rc;
127788   rc = sqlcipher3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
127789   if( rc==SQLCIPHER_OK ){
127790     rc = fts3DoOptimize(p, 1);
127791     if( rc==SQLCIPHER_OK || rc==SQLCIPHER_DONE ){
127792       int rc2 = sqlcipher3_exec(p->db, "RELEASE fts3", 0, 0, 0);
127793       if( rc2!=SQLCIPHER_OK ) rc = rc2;
127794     }else{
127795       sqlcipher3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
127796       sqlcipher3_exec(p->db, "RELEASE fts3", 0, 0, 0);
127797     }
127798   }
127799   sqlcipher3Fts3SegmentsClose(p);
127800   return rc;
127801 }
127802
127803 #endif
127804
127805 /************** End of fts3_write.c ******************************************/
127806 /************** Begin file fts3_snippet.c ************************************/
127807 /*
127808 ** 2009 Oct 23
127809 **
127810 ** The author disclaims copyright to this source code.  In place of
127811 ** a legal notice, here is a blessing:
127812 **
127813 **    May you do good and not evil.
127814 **    May you find forgiveness for yourself and forgive others.
127815 **    May you share freely, never taking more than you give.
127816 **
127817 ******************************************************************************
127818 */
127819
127820 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
127821
127822 /* #include <string.h> */
127823 /* #include <assert.h> */
127824
127825 /*
127826 ** Characters that may appear in the second argument to matchinfo().
127827 */
127828 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
127829 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
127830 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
127831 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
127832 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
127833 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
127834 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
127835
127836 /*
127837 ** The default value for the second argument to matchinfo(). 
127838 */
127839 #define FTS3_MATCHINFO_DEFAULT   "pcx"
127840
127841
127842 /*
127843 ** Used as an fts3ExprIterate() context when loading phrase doclists to
127844 ** Fts3Expr.aDoclist[]/nDoclist.
127845 */
127846 typedef struct LoadDoclistCtx LoadDoclistCtx;
127847 struct LoadDoclistCtx {
127848   Fts3Cursor *pCsr;               /* FTS3 Cursor */
127849   int nPhrase;                    /* Number of phrases seen so far */
127850   int nToken;                     /* Number of tokens seen so far */
127851 };
127852
127853 /*
127854 ** The following types are used as part of the implementation of the 
127855 ** fts3BestSnippet() routine.
127856 */
127857 typedef struct SnippetIter SnippetIter;
127858 typedef struct SnippetPhrase SnippetPhrase;
127859 typedef struct SnippetFragment SnippetFragment;
127860
127861 struct SnippetIter {
127862   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
127863   int iCol;                       /* Extract snippet from this column */
127864   int nSnippet;                   /* Requested snippet length (in tokens) */
127865   int nPhrase;                    /* Number of phrases in query */
127866   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
127867   int iCurrent;                   /* First token of current snippet */
127868 };
127869
127870 struct SnippetPhrase {
127871   int nToken;                     /* Number of tokens in phrase */
127872   char *pList;                    /* Pointer to start of phrase position list */
127873   int iHead;                      /* Next value in position list */
127874   char *pHead;                    /* Position list data following iHead */
127875   int iTail;                      /* Next value in trailing position list */
127876   char *pTail;                    /* Position list data following iTail */
127877 };
127878
127879 struct SnippetFragment {
127880   int iCol;                       /* Column snippet is extracted from */
127881   int iPos;                       /* Index of first token in snippet */
127882   u64 covered;                    /* Mask of query phrases covered */
127883   u64 hlmask;                     /* Mask of snippet terms to highlight */
127884 };
127885
127886 /*
127887 ** This type is used as an fts3ExprIterate() context object while 
127888 ** accumulating the data returned by the matchinfo() function.
127889 */
127890 typedef struct MatchInfo MatchInfo;
127891 struct MatchInfo {
127892   Fts3Cursor *pCursor;            /* FTS3 Cursor */
127893   int nCol;                       /* Number of columns in table */
127894   int nPhrase;                    /* Number of matchable phrases in query */
127895   sqlcipher3_int64 nDoc;             /* Number of docs in database */
127896   u32 *aMatchinfo;                /* Pre-allocated buffer */
127897 };
127898
127899
127900
127901 /*
127902 ** The snippet() and offsets() functions both return text values. An instance
127903 ** of the following structure is used to accumulate those values while the
127904 ** functions are running. See fts3StringAppend() for details.
127905 */
127906 typedef struct StrBuffer StrBuffer;
127907 struct StrBuffer {
127908   char *z;                        /* Pointer to buffer containing string */
127909   int n;                          /* Length of z in bytes (excl. nul-term) */
127910   int nAlloc;                     /* Allocated size of buffer z in bytes */
127911 };
127912
127913
127914 /*
127915 ** This function is used to help iterate through a position-list. A position
127916 ** list is a list of unique integers, sorted from smallest to largest. Each
127917 ** element of the list is represented by an FTS3 varint that takes the value
127918 ** of the difference between the current element and the previous one plus
127919 ** two. For example, to store the position-list:
127920 **
127921 **     4 9 113
127922 **
127923 ** the three varints:
127924 **
127925 **     6 7 106
127926 **
127927 ** are encoded.
127928 **
127929 ** When this function is called, *pp points to the start of an element of
127930 ** the list. *piPos contains the value of the previous entry in the list.
127931 ** After it returns, *piPos contains the value of the next element of the
127932 ** list and *pp is advanced to the following varint.
127933 */
127934 static void fts3GetDeltaPosition(char **pp, int *piPos){
127935   int iVal;
127936   *pp += sqlcipher3Fts3GetVarint32(*pp, &iVal);
127937   *piPos += (iVal-2);
127938 }
127939
127940 /*
127941 ** Helper function for fts3ExprIterate() (see below).
127942 */
127943 static int fts3ExprIterate2(
127944   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
127945   int *piPhrase,                  /* Pointer to phrase counter */
127946   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
127947   void *pCtx                      /* Second argument to pass to callback */
127948 ){
127949   int rc;                         /* Return code */
127950   int eType = pExpr->eType;       /* Type of expression node pExpr */
127951
127952   if( eType!=FTSQUERY_PHRASE ){
127953     assert( pExpr->pLeft && pExpr->pRight );
127954     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
127955     if( rc==SQLCIPHER_OK && eType!=FTSQUERY_NOT ){
127956       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
127957     }
127958   }else{
127959     rc = x(pExpr, *piPhrase, pCtx);
127960     (*piPhrase)++;
127961   }
127962   return rc;
127963 }
127964
127965 /*
127966 ** Iterate through all phrase nodes in an FTS3 query, except those that
127967 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
127968 ** For each phrase node found, the supplied callback function is invoked.
127969 **
127970 ** If the callback function returns anything other than SQLCIPHER_OK, 
127971 ** the iteration is abandoned and the error code returned immediately.
127972 ** Otherwise, SQLCIPHER_OK is returned after a callback has been made for
127973 ** all eligible phrase nodes.
127974 */
127975 static int fts3ExprIterate(
127976   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
127977   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
127978   void *pCtx                      /* Second argument to pass to callback */
127979 ){
127980   int iPhrase = 0;                /* Variable used as the phrase counter */
127981   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
127982 }
127983
127984 /*
127985 ** This is an fts3ExprIterate() callback used while loading the doclists
127986 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
127987 ** fts3ExprLoadDoclists().
127988 */
127989 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
127990   int rc = SQLCIPHER_OK;
127991   Fts3Phrase *pPhrase = pExpr->pPhrase;
127992   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
127993
127994   UNUSED_PARAMETER(iPhrase);
127995
127996   p->nPhrase++;
127997   p->nToken += pPhrase->nToken;
127998
127999   return rc;
128000 }
128001
128002 /*
128003 ** Load the doclists for each phrase in the query associated with FTS3 cursor
128004 ** pCsr. 
128005 **
128006 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
128007 ** phrases in the expression (all phrases except those directly or 
128008 ** indirectly descended from the right-hand-side of a NOT operator). If 
128009 ** pnToken is not NULL, then it is set to the number of tokens in all
128010 ** matchable phrases of the expression.
128011 */
128012 static int fts3ExprLoadDoclists(
128013   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
128014   int *pnPhrase,                  /* OUT: Number of phrases in query */
128015   int *pnToken                    /* OUT: Number of tokens in query */
128016 ){
128017   int rc;                         /* Return Code */
128018   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
128019   sCtx.pCsr = pCsr;
128020   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
128021   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
128022   if( pnToken ) *pnToken = sCtx.nToken;
128023   return rc;
128024 }
128025
128026 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
128027   (*(int *)ctx)++;
128028   UNUSED_PARAMETER(pExpr);
128029   UNUSED_PARAMETER(iPhrase);
128030   return SQLCIPHER_OK;
128031 }
128032 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
128033   int nPhrase = 0;
128034   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
128035   return nPhrase;
128036 }
128037
128038 /*
128039 ** Advance the position list iterator specified by the first two 
128040 ** arguments so that it points to the first element with a value greater
128041 ** than or equal to parameter iNext.
128042 */
128043 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
128044   char *pIter = *ppIter;
128045   if( pIter ){
128046     int iIter = *piIter;
128047
128048     while( iIter<iNext ){
128049       if( 0==(*pIter & 0xFE) ){
128050         iIter = -1;
128051         pIter = 0;
128052         break;
128053       }
128054       fts3GetDeltaPosition(&pIter, &iIter);
128055     }
128056
128057     *piIter = iIter;
128058     *ppIter = pIter;
128059   }
128060 }
128061
128062 /*
128063 ** Advance the snippet iterator to the next candidate snippet.
128064 */
128065 static int fts3SnippetNextCandidate(SnippetIter *pIter){
128066   int i;                          /* Loop counter */
128067
128068   if( pIter->iCurrent<0 ){
128069     /* The SnippetIter object has just been initialized. The first snippet
128070     ** candidate always starts at offset 0 (even if this candidate has a
128071     ** score of 0.0).
128072     */
128073     pIter->iCurrent = 0;
128074
128075     /* Advance the 'head' iterator of each phrase to the first offset that
128076     ** is greater than or equal to (iNext+nSnippet).
128077     */
128078     for(i=0; i<pIter->nPhrase; i++){
128079       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128080       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
128081     }
128082   }else{
128083     int iStart;
128084     int iEnd = 0x7FFFFFFF;
128085
128086     for(i=0; i<pIter->nPhrase; i++){
128087       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128088       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
128089         iEnd = pPhrase->iHead;
128090       }
128091     }
128092     if( iEnd==0x7FFFFFFF ){
128093       return 1;
128094     }
128095
128096     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
128097     for(i=0; i<pIter->nPhrase; i++){
128098       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128099       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
128100       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
128101     }
128102   }
128103
128104   return 0;
128105 }
128106
128107 /*
128108 ** Retrieve information about the current candidate snippet of snippet 
128109 ** iterator pIter.
128110 */
128111 static void fts3SnippetDetails(
128112   SnippetIter *pIter,             /* Snippet iterator */
128113   u64 mCovered,                   /* Bitmask of phrases already covered */
128114   int *piToken,                   /* OUT: First token of proposed snippet */
128115   int *piScore,                   /* OUT: "Score" for this snippet */
128116   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
128117   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
128118 ){
128119   int iStart = pIter->iCurrent;   /* First token of snippet */
128120   int iScore = 0;                 /* Score of this snippet */
128121   int i;                          /* Loop counter */
128122   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
128123   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
128124
128125   for(i=0; i<pIter->nPhrase; i++){
128126     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128127     if( pPhrase->pTail ){
128128       char *pCsr = pPhrase->pTail;
128129       int iCsr = pPhrase->iTail;
128130
128131       while( iCsr<(iStart+pIter->nSnippet) ){
128132         int j;
128133         u64 mPhrase = (u64)1 << i;
128134         u64 mPos = (u64)1 << (iCsr - iStart);
128135         assert( iCsr>=iStart );
128136         if( (mCover|mCovered)&mPhrase ){
128137           iScore++;
128138         }else{
128139           iScore += 1000;
128140         }
128141         mCover |= mPhrase;
128142
128143         for(j=0; j<pPhrase->nToken; j++){
128144           mHighlight |= (mPos>>j);
128145         }
128146
128147         if( 0==(*pCsr & 0x0FE) ) break;
128148         fts3GetDeltaPosition(&pCsr, &iCsr);
128149       }
128150     }
128151   }
128152
128153   /* Set the output variables before returning. */
128154   *piToken = iStart;
128155   *piScore = iScore;
128156   *pmCover = mCover;
128157   *pmHighlight = mHighlight;
128158 }
128159
128160 /*
128161 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
128162 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
128163 */
128164 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
128165   SnippetIter *p = (SnippetIter *)ctx;
128166   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
128167   char *pCsr;
128168
128169   pPhrase->nToken = pExpr->pPhrase->nToken;
128170
128171   pCsr = sqlcipher3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
128172   if( pCsr ){
128173     int iFirst = 0;
128174     pPhrase->pList = pCsr;
128175     fts3GetDeltaPosition(&pCsr, &iFirst);
128176     assert( iFirst>=0 );
128177     pPhrase->pHead = pCsr;
128178     pPhrase->pTail = pCsr;
128179     pPhrase->iHead = iFirst;
128180     pPhrase->iTail = iFirst;
128181   }else{
128182     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
128183   }
128184
128185   return SQLCIPHER_OK;
128186 }
128187
128188 /*
128189 ** Select the fragment of text consisting of nFragment contiguous tokens 
128190 ** from column iCol that represent the "best" snippet. The best snippet
128191 ** is the snippet with the highest score, where scores are calculated
128192 ** by adding:
128193 **
128194 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
128195 **
128196 **   (b) +1000 points for the first occurence of each matchable phrase in 
128197 **       the snippet for which the corresponding mCovered bit is not set.
128198 **
128199 ** The selected snippet parameters are stored in structure *pFragment before
128200 ** returning. The score of the selected snippet is stored in *piScore
128201 ** before returning.
128202 */
128203 static int fts3BestSnippet(
128204   int nSnippet,                   /* Desired snippet length */
128205   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
128206   int iCol,                       /* Index of column to create snippet from */
128207   u64 mCovered,                   /* Mask of phrases already covered */
128208   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
128209   SnippetFragment *pFragment,     /* OUT: Best snippet found */
128210   int *piScore                    /* OUT: Score of snippet pFragment */
128211 ){
128212   int rc;                         /* Return Code */
128213   int nList;                      /* Number of phrases in expression */
128214   SnippetIter sIter;              /* Iterates through snippet candidates */
128215   int nByte;                      /* Number of bytes of space to allocate */
128216   int iBestScore = -1;            /* Best snippet score found so far */
128217   int i;                          /* Loop counter */
128218
128219   memset(&sIter, 0, sizeof(sIter));
128220
128221   /* Iterate through the phrases in the expression to count them. The same
128222   ** callback makes sure the doclists are loaded for each phrase.
128223   */
128224   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
128225   if( rc!=SQLCIPHER_OK ){
128226     return rc;
128227   }
128228
128229   /* Now that it is known how many phrases there are, allocate and zero
128230   ** the required space using malloc().
128231   */
128232   nByte = sizeof(SnippetPhrase) * nList;
128233   sIter.aPhrase = (SnippetPhrase *)sqlcipher3_malloc(nByte);
128234   if( !sIter.aPhrase ){
128235     return SQLCIPHER_NOMEM;
128236   }
128237   memset(sIter.aPhrase, 0, nByte);
128238
128239   /* Initialize the contents of the SnippetIter object. Then iterate through
128240   ** the set of phrases in the expression to populate the aPhrase[] array.
128241   */
128242   sIter.pCsr = pCsr;
128243   sIter.iCol = iCol;
128244   sIter.nSnippet = nSnippet;
128245   sIter.nPhrase = nList;
128246   sIter.iCurrent = -1;
128247   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
128248
128249   /* Set the *pmSeen output variable. */
128250   for(i=0; i<nList; i++){
128251     if( sIter.aPhrase[i].pHead ){
128252       *pmSeen |= (u64)1 << i;
128253     }
128254   }
128255
128256   /* Loop through all candidate snippets. Store the best snippet in 
128257   ** *pFragment. Store its associated 'score' in iBestScore.
128258   */
128259   pFragment->iCol = iCol;
128260   while( !fts3SnippetNextCandidate(&sIter) ){
128261     int iPos;
128262     int iScore;
128263     u64 mCover;
128264     u64 mHighlight;
128265     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
128266     assert( iScore>=0 );
128267     if( iScore>iBestScore ){
128268       pFragment->iPos = iPos;
128269       pFragment->hlmask = mHighlight;
128270       pFragment->covered = mCover;
128271       iBestScore = iScore;
128272     }
128273   }
128274
128275   sqlcipher3_free(sIter.aPhrase);
128276   *piScore = iBestScore;
128277   return SQLCIPHER_OK;
128278 }
128279
128280
128281 /*
128282 ** Append a string to the string-buffer passed as the first argument.
128283 **
128284 ** If nAppend is negative, then the length of the string zAppend is
128285 ** determined using strlen().
128286 */
128287 static int fts3StringAppend(
128288   StrBuffer *pStr,                /* Buffer to append to */
128289   const char *zAppend,            /* Pointer to data to append to buffer */
128290   int nAppend                     /* Size of zAppend in bytes (or -1) */
128291 ){
128292   if( nAppend<0 ){
128293     nAppend = (int)strlen(zAppend);
128294   }
128295
128296   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
128297   ** to grow the buffer until so that it is big enough to accomadate the
128298   ** appended data.
128299   */
128300   if( pStr->n+nAppend+1>=pStr->nAlloc ){
128301     int nAlloc = pStr->nAlloc+nAppend+100;
128302     char *zNew = sqlcipher3_realloc(pStr->z, nAlloc);
128303     if( !zNew ){
128304       return SQLCIPHER_NOMEM;
128305     }
128306     pStr->z = zNew;
128307     pStr->nAlloc = nAlloc;
128308   }
128309
128310   /* Append the data to the string buffer. */
128311   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
128312   pStr->n += nAppend;
128313   pStr->z[pStr->n] = '\0';
128314
128315   return SQLCIPHER_OK;
128316 }
128317
128318 /*
128319 ** The fts3BestSnippet() function often selects snippets that end with a
128320 ** query term. That is, the final term of the snippet is always a term
128321 ** that requires highlighting. For example, if 'X' is a highlighted term
128322 ** and '.' is a non-highlighted term, BestSnippet() may select:
128323 **
128324 **     ........X.....X
128325 **
128326 ** This function "shifts" the beginning of the snippet forward in the 
128327 ** document so that there are approximately the same number of 
128328 ** non-highlighted terms to the right of the final highlighted term as there
128329 ** are to the left of the first highlighted term. For example, to this:
128330 **
128331 **     ....X.....X....
128332 **
128333 ** This is done as part of extracting the snippet text, not when selecting
128334 ** the snippet. Snippet selection is done based on doclists only, so there
128335 ** is no way for fts3BestSnippet() to know whether or not the document 
128336 ** actually contains terms that follow the final highlighted term. 
128337 */
128338 static int fts3SnippetShift(
128339   Fts3Table *pTab,                /* FTS3 table snippet comes from */
128340   int nSnippet,                   /* Number of tokens desired for snippet */
128341   const char *zDoc,               /* Document text to extract snippet from */
128342   int nDoc,                       /* Size of buffer zDoc in bytes */
128343   int *piPos,                     /* IN/OUT: First token of snippet */
128344   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
128345 ){
128346   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
128347
128348   if( hlmask ){
128349     int nLeft;                    /* Tokens to the left of first highlight */
128350     int nRight;                   /* Tokens to the right of last highlight */
128351     int nDesired;                 /* Ideal number of tokens to shift forward */
128352
128353     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
128354     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
128355     nDesired = (nLeft-nRight)/2;
128356
128357     /* Ideally, the start of the snippet should be pushed forward in the
128358     ** document nDesired tokens. This block checks if there are actually
128359     ** nDesired tokens to the right of the snippet. If so, *piPos and
128360     ** *pHlMask are updated to shift the snippet nDesired tokens to the
128361     ** right. Otherwise, the snippet is shifted by the number of tokens
128362     ** available.
128363     */
128364     if( nDesired>0 ){
128365       int nShift;                 /* Number of tokens to shift snippet by */
128366       int iCurrent = 0;           /* Token counter */
128367       int rc;                     /* Return Code */
128368       sqlcipher3_tokenizer_module *pMod;
128369       sqlcipher3_tokenizer_cursor *pC;
128370       pMod = (sqlcipher3_tokenizer_module *)pTab->pTokenizer->pModule;
128371
128372       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
128373       ** or more tokens in zDoc/nDoc.
128374       */
128375       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
128376       if( rc!=SQLCIPHER_OK ){
128377         return rc;
128378       }
128379       pC->pTokenizer = pTab->pTokenizer;
128380       while( rc==SQLCIPHER_OK && iCurrent<(nSnippet+nDesired) ){
128381         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
128382         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
128383       }
128384       pMod->xClose(pC);
128385       if( rc!=SQLCIPHER_OK && rc!=SQLCIPHER_DONE ){ return rc; }
128386
128387       nShift = (rc==SQLCIPHER_DONE)+iCurrent-nSnippet;
128388       assert( nShift<=nDesired );
128389       if( nShift>0 ){
128390         *piPos += nShift;
128391         *pHlmask = hlmask >> nShift;
128392       }
128393     }
128394   }
128395   return SQLCIPHER_OK;
128396 }
128397
128398 /*
128399 ** Extract the snippet text for fragment pFragment from cursor pCsr and
128400 ** append it to string buffer pOut.
128401 */
128402 static int fts3SnippetText(
128403   Fts3Cursor *pCsr,               /* FTS3 Cursor */
128404   SnippetFragment *pFragment,     /* Snippet to extract */
128405   int iFragment,                  /* Fragment number */
128406   int isLast,                     /* True for final fragment in snippet */
128407   int nSnippet,                   /* Number of tokens in extracted snippet */
128408   const char *zOpen,              /* String inserted before highlighted term */
128409   const char *zClose,             /* String inserted after highlighted term */
128410   const char *zEllipsis,          /* String inserted between snippets */
128411   StrBuffer *pOut                 /* Write output here */
128412 ){
128413   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128414   int rc;                         /* Return code */
128415   const char *zDoc;               /* Document text to extract snippet from */
128416   int nDoc;                       /* Size of zDoc in bytes */
128417   int iCurrent = 0;               /* Current token number of document */
128418   int iEnd = 0;                   /* Byte offset of end of current token */
128419   int isShiftDone = 0;            /* True after snippet is shifted */
128420   int iPos = pFragment->iPos;     /* First token of snippet */
128421   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
128422   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
128423   sqlcipher3_tokenizer_module *pMod; /* Tokenizer module methods object */
128424   sqlcipher3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
128425   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
128426   int DUMMY1;                     /* Dummy argument used with tokenizer */
128427   
128428   zDoc = (const char *)sqlcipher3_column_text(pCsr->pStmt, iCol);
128429   if( zDoc==0 ){
128430     if( sqlcipher3_column_type(pCsr->pStmt, iCol)!=SQLCIPHER_NULL ){
128431       return SQLCIPHER_NOMEM;
128432     }
128433     return SQLCIPHER_OK;
128434   }
128435   nDoc = sqlcipher3_column_bytes(pCsr->pStmt, iCol);
128436
128437   /* Open a token cursor on the document. */
128438   pMod = (sqlcipher3_tokenizer_module *)pTab->pTokenizer->pModule;
128439   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
128440   if( rc!=SQLCIPHER_OK ){
128441     return rc;
128442   }
128443   pC->pTokenizer = pTab->pTokenizer;
128444
128445   while( rc==SQLCIPHER_OK ){
128446     int iBegin;                   /* Offset in zDoc of start of token */
128447     int iFin;                     /* Offset in zDoc of end of token */
128448     int isHighlight;              /* True for highlighted terms */
128449
128450     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
128451     if( rc!=SQLCIPHER_OK ){
128452       if( rc==SQLCIPHER_DONE ){
128453         /* Special case - the last token of the snippet is also the last token
128454         ** of the column. Append any punctuation that occurred between the end
128455         ** of the previous token and the end of the document to the output. 
128456         ** Then break out of the loop. */
128457         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
128458       }
128459       break;
128460     }
128461     if( iCurrent<iPos ){ continue; }
128462
128463     if( !isShiftDone ){
128464       int n = nDoc - iBegin;
128465       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
128466       isShiftDone = 1;
128467
128468       /* Now that the shift has been done, check if the initial "..." are
128469       ** required. They are required if (a) this is not the first fragment,
128470       ** or (b) this fragment does not begin at position 0 of its column. 
128471       */
128472       if( rc==SQLCIPHER_OK && (iPos>0 || iFragment>0) ){
128473         rc = fts3StringAppend(pOut, zEllipsis, -1);
128474       }
128475       if( rc!=SQLCIPHER_OK || iCurrent<iPos ) continue;
128476     }
128477
128478     if( iCurrent>=(iPos+nSnippet) ){
128479       if( isLast ){
128480         rc = fts3StringAppend(pOut, zEllipsis, -1);
128481       }
128482       break;
128483     }
128484
128485     /* Set isHighlight to true if this term should be highlighted. */
128486     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
128487
128488     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
128489     if( rc==SQLCIPHER_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
128490     if( rc==SQLCIPHER_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
128491     if( rc==SQLCIPHER_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
128492
128493     iEnd = iFin;
128494   }
128495
128496   pMod->xClose(pC);
128497   return rc;
128498 }
128499
128500
128501 /*
128502 ** This function is used to count the entries in a column-list (a 
128503 ** delta-encoded list of term offsets within a single column of a single 
128504 ** row). When this function is called, *ppCollist should point to the
128505 ** beginning of the first varint in the column-list (the varint that
128506 ** contains the position of the first matching term in the column data).
128507 ** Before returning, *ppCollist is set to point to the first byte after
128508 ** the last varint in the column-list (either the 0x00 signifying the end
128509 ** of the position-list, or the 0x01 that precedes the column number of
128510 ** the next column in the position-list).
128511 **
128512 ** The number of elements in the column-list is returned.
128513 */
128514 static int fts3ColumnlistCount(char **ppCollist){
128515   char *pEnd = *ppCollist;
128516   char c = 0;
128517   int nEntry = 0;
128518
128519   /* A column-list is terminated by either a 0x01 or 0x00. */
128520   while( 0xFE & (*pEnd | c) ){
128521     c = *pEnd++ & 0x80;
128522     if( !c ) nEntry++;
128523   }
128524
128525   *ppCollist = pEnd;
128526   return nEntry;
128527 }
128528
128529 /*
128530 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
128531 ** for a single query. 
128532 **
128533 ** fts3ExprIterate() callback to load the 'global' elements of a
128534 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
128535 ** of the matchinfo array that are constant for all rows returned by the 
128536 ** current query.
128537 **
128538 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
128539 ** function populates Matchinfo.aMatchinfo[] as follows:
128540 **
128541 **   for(iCol=0; iCol<nCol; iCol++){
128542 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
128543 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
128544 **   }
128545 **
128546 ** where X is the number of matches for phrase iPhrase is column iCol of all
128547 ** rows of the table. Y is the number of rows for which column iCol contains
128548 ** at least one instance of phrase iPhrase.
128549 **
128550 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
128551 ** Y values are set to nDoc, where nDoc is the number of documents in the 
128552 ** file system. This is done because the full-text index doclist is required
128553 ** to calculate these values properly, and the full-text index doclist is
128554 ** not available for deferred tokens.
128555 */
128556 static int fts3ExprGlobalHitsCb(
128557   Fts3Expr *pExpr,                /* Phrase expression node */
128558   int iPhrase,                    /* Phrase number (numbered from zero) */
128559   void *pCtx                      /* Pointer to MatchInfo structure */
128560 ){
128561   MatchInfo *p = (MatchInfo *)pCtx;
128562   return sqlcipher3Fts3EvalPhraseStats(
128563       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
128564   );
128565 }
128566
128567 /*
128568 ** fts3ExprIterate() callback used to collect the "local" part of the
128569 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
128570 ** array that are different for each row returned by the query.
128571 */
128572 static int fts3ExprLocalHitsCb(
128573   Fts3Expr *pExpr,                /* Phrase expression node */
128574   int iPhrase,                    /* Phrase number */
128575   void *pCtx                      /* Pointer to MatchInfo structure */
128576 ){
128577   MatchInfo *p = (MatchInfo *)pCtx;
128578   int iStart = iPhrase * p->nCol * 3;
128579   int i;
128580
128581   for(i=0; i<p->nCol; i++){
128582     char *pCsr;
128583     pCsr = sqlcipher3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
128584     if( pCsr ){
128585       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
128586     }else{
128587       p->aMatchinfo[iStart+i*3] = 0;
128588     }
128589   }
128590
128591   return SQLCIPHER_OK;
128592 }
128593
128594 static int fts3MatchinfoCheck(
128595   Fts3Table *pTab, 
128596   char cArg,
128597   char **pzErr
128598 ){
128599   if( (cArg==FTS3_MATCHINFO_NPHRASE)
128600    || (cArg==FTS3_MATCHINFO_NCOL)
128601    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
128602    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
128603    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
128604    || (cArg==FTS3_MATCHINFO_LCS)
128605    || (cArg==FTS3_MATCHINFO_HITS)
128606   ){
128607     return SQLCIPHER_OK;
128608   }
128609   *pzErr = sqlcipher3_mprintf("unrecognized matchinfo request: %c", cArg);
128610   return SQLCIPHER_ERROR;
128611 }
128612
128613 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
128614   int nVal;                       /* Number of integers output by cArg */
128615
128616   switch( cArg ){
128617     case FTS3_MATCHINFO_NDOC:
128618     case FTS3_MATCHINFO_NPHRASE: 
128619     case FTS3_MATCHINFO_NCOL: 
128620       nVal = 1;
128621       break;
128622
128623     case FTS3_MATCHINFO_AVGLENGTH:
128624     case FTS3_MATCHINFO_LENGTH:
128625     case FTS3_MATCHINFO_LCS:
128626       nVal = pInfo->nCol;
128627       break;
128628
128629     default:
128630       assert( cArg==FTS3_MATCHINFO_HITS );
128631       nVal = pInfo->nCol * pInfo->nPhrase * 3;
128632       break;
128633   }
128634
128635   return nVal;
128636 }
128637
128638 static int fts3MatchinfoSelectDoctotal(
128639   Fts3Table *pTab,
128640   sqlcipher3_stmt **ppStmt,
128641   sqlcipher3_int64 *pnDoc,
128642   const char **paLen
128643 ){
128644   sqlcipher3_stmt *pStmt;
128645   const char *a;
128646   sqlcipher3_int64 nDoc;
128647
128648   if( !*ppStmt ){
128649     int rc = sqlcipher3Fts3SelectDoctotal(pTab, ppStmt);
128650     if( rc!=SQLCIPHER_OK ) return rc;
128651   }
128652   pStmt = *ppStmt;
128653   assert( sqlcipher3_data_count(pStmt)==1 );
128654
128655   a = sqlcipher3_column_blob(pStmt, 0);
128656   a += sqlcipher3Fts3GetVarint(a, &nDoc);
128657   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
128658   *pnDoc = (u32)nDoc;
128659
128660   if( paLen ) *paLen = a;
128661   return SQLCIPHER_OK;
128662 }
128663
128664 /*
128665 ** An instance of the following structure is used to store state while 
128666 ** iterating through a multi-column position-list corresponding to the
128667 ** hits for a single phrase on a single row in order to calculate the
128668 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
128669 */
128670 typedef struct LcsIterator LcsIterator;
128671 struct LcsIterator {
128672   Fts3Expr *pExpr;                /* Pointer to phrase expression */
128673   int iPosOffset;                 /* Tokens count up to end of this phrase */
128674   char *pRead;                    /* Cursor used to iterate through aDoclist */
128675   int iPos;                       /* Current position */
128676 };
128677
128678 /* 
128679 ** If LcsIterator.iCol is set to the following value, the iterator has
128680 ** finished iterating through all offsets for all columns.
128681 */
128682 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
128683
128684 static int fts3MatchinfoLcsCb(
128685   Fts3Expr *pExpr,                /* Phrase expression node */
128686   int iPhrase,                    /* Phrase number (numbered from zero) */
128687   void *pCtx                      /* Pointer to MatchInfo structure */
128688 ){
128689   LcsIterator *aIter = (LcsIterator *)pCtx;
128690   aIter[iPhrase].pExpr = pExpr;
128691   return SQLCIPHER_OK;
128692 }
128693
128694 /*
128695 ** Advance the iterator passed as an argument to the next position. Return
128696 ** 1 if the iterator is at EOF or if it now points to the start of the
128697 ** position list for the next column.
128698 */
128699 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
128700   char *pRead = pIter->pRead;
128701   sqlcipher3_int64 iRead;
128702   int rc = 0;
128703
128704   pRead += sqlcipher3Fts3GetVarint(pRead, &iRead);
128705   if( iRead==0 || iRead==1 ){
128706     pRead = 0;
128707     rc = 1;
128708   }else{
128709     pIter->iPos += (int)(iRead-2);
128710   }
128711
128712   pIter->pRead = pRead;
128713   return rc;
128714 }
128715   
128716 /*
128717 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
128718 **
128719 ** If the call is successful, the longest-common-substring lengths for each
128720 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
128721 ** array before returning. SQLCIPHER_OK is returned in this case.
128722 **
128723 ** Otherwise, if an error occurs, an SQLite error code is returned and the
128724 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
128725 ** undefined.
128726 */
128727 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
128728   LcsIterator *aIter;
128729   int i;
128730   int iCol;
128731   int nToken = 0;
128732
128733   /* Allocate and populate the array of LcsIterator objects. The array
128734   ** contains one element for each matchable phrase in the query.
128735   **/
128736   aIter = sqlcipher3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
128737   if( !aIter ) return SQLCIPHER_NOMEM;
128738   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
128739   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
128740
128741   for(i=0; i<pInfo->nPhrase; i++){
128742     LcsIterator *pIter = &aIter[i];
128743     nToken -= pIter->pExpr->pPhrase->nToken;
128744     pIter->iPosOffset = nToken;
128745   }
128746
128747   for(iCol=0; iCol<pInfo->nCol; iCol++){
128748     int nLcs = 0;                 /* LCS value for this column */
128749     int nLive = 0;                /* Number of iterators in aIter not at EOF */
128750
128751     for(i=0; i<pInfo->nPhrase; i++){
128752       LcsIterator *pIt = &aIter[i];
128753       pIt->pRead = sqlcipher3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
128754       if( pIt->pRead ){
128755         pIt->iPos = pIt->iPosOffset;
128756         fts3LcsIteratorAdvance(&aIter[i]);
128757         nLive++;
128758       }
128759     }
128760
128761     while( nLive>0 ){
128762       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
128763       int nThisLcs = 0;           /* LCS for the current iterator positions */
128764
128765       for(i=0; i<pInfo->nPhrase; i++){
128766         LcsIterator *pIter = &aIter[i];
128767         if( pIter->pRead==0 ){
128768           /* This iterator is already at EOF for this column. */
128769           nThisLcs = 0;
128770         }else{
128771           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
128772             pAdv = pIter;
128773           }
128774           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
128775             nThisLcs++;
128776           }else{
128777             nThisLcs = 1;
128778           }
128779           if( nThisLcs>nLcs ) nLcs = nThisLcs;
128780         }
128781       }
128782       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
128783     }
128784
128785     pInfo->aMatchinfo[iCol] = nLcs;
128786   }
128787
128788   sqlcipher3_free(aIter);
128789   return SQLCIPHER_OK;
128790 }
128791
128792 /*
128793 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
128794 ** be returned by the matchinfo() function. Argument zArg contains the 
128795 ** format string passed as the second argument to matchinfo (or the
128796 ** default value "pcx" if no second argument was specified). The format
128797 ** string has already been validated and the pInfo->aMatchinfo[] array
128798 ** is guaranteed to be large enough for the output.
128799 **
128800 ** If bGlobal is true, then populate all fields of the matchinfo() output.
128801 ** If it is false, then assume that those fields that do not change between
128802 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
128803 ** have already been populated.
128804 **
128805 ** Return SQLCIPHER_OK if successful, or an SQLite error code if an error 
128806 ** occurs. If a value other than SQLCIPHER_OK is returned, the state the
128807 ** pInfo->aMatchinfo[] buffer is left in is undefined.
128808 */
128809 static int fts3MatchinfoValues(
128810   Fts3Cursor *pCsr,               /* FTS3 cursor object */
128811   int bGlobal,                    /* True to grab the global stats */
128812   MatchInfo *pInfo,               /* Matchinfo context object */
128813   const char *zArg                /* Matchinfo format string */
128814 ){
128815   int rc = SQLCIPHER_OK;
128816   int i;
128817   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128818   sqlcipher3_stmt *pSelect = 0;
128819
128820   for(i=0; rc==SQLCIPHER_OK && zArg[i]; i++){
128821
128822     switch( zArg[i] ){
128823       case FTS3_MATCHINFO_NPHRASE:
128824         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
128825         break;
128826
128827       case FTS3_MATCHINFO_NCOL:
128828         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
128829         break;
128830         
128831       case FTS3_MATCHINFO_NDOC:
128832         if( bGlobal ){
128833           sqlcipher3_int64 nDoc = 0;
128834           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
128835           pInfo->aMatchinfo[0] = (u32)nDoc;
128836         }
128837         break;
128838
128839       case FTS3_MATCHINFO_AVGLENGTH: 
128840         if( bGlobal ){
128841           sqlcipher3_int64 nDoc;     /* Number of rows in table */
128842           const char *a;          /* Aggregate column length array */
128843
128844           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
128845           if( rc==SQLCIPHER_OK ){
128846             int iCol;
128847             for(iCol=0; iCol<pInfo->nCol; iCol++){
128848               u32 iVal;
128849               sqlcipher3_int64 nToken;
128850               a += sqlcipher3Fts3GetVarint(a, &nToken);
128851               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
128852               pInfo->aMatchinfo[iCol] = iVal;
128853             }
128854           }
128855         }
128856         break;
128857
128858       case FTS3_MATCHINFO_LENGTH: {
128859         sqlcipher3_stmt *pSelectDocsize = 0;
128860         rc = sqlcipher3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
128861         if( rc==SQLCIPHER_OK ){
128862           int iCol;
128863           const char *a = sqlcipher3_column_blob(pSelectDocsize, 0);
128864           for(iCol=0; iCol<pInfo->nCol; iCol++){
128865             sqlcipher3_int64 nToken;
128866             a += sqlcipher3Fts3GetVarint(a, &nToken);
128867             pInfo->aMatchinfo[iCol] = (u32)nToken;
128868           }
128869         }
128870         sqlcipher3_reset(pSelectDocsize);
128871         break;
128872       }
128873
128874       case FTS3_MATCHINFO_LCS:
128875         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
128876         if( rc==SQLCIPHER_OK ){
128877           rc = fts3MatchinfoLcs(pCsr, pInfo);
128878         }
128879         break;
128880
128881       default: {
128882         Fts3Expr *pExpr;
128883         assert( zArg[i]==FTS3_MATCHINFO_HITS );
128884         pExpr = pCsr->pExpr;
128885         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
128886         if( rc!=SQLCIPHER_OK ) break;
128887         if( bGlobal ){
128888           if( pCsr->pDeferred ){
128889             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
128890             if( rc!=SQLCIPHER_OK ) break;
128891           }
128892           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
128893           if( rc!=SQLCIPHER_OK ) break;
128894         }
128895         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
128896         break;
128897       }
128898     }
128899
128900     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
128901   }
128902
128903   sqlcipher3_reset(pSelect);
128904   return rc;
128905 }
128906
128907
128908 /*
128909 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
128910 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
128911 */
128912 static int fts3GetMatchinfo(
128913   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
128914   const char *zArg                /* Second argument to matchinfo() function */
128915 ){
128916   MatchInfo sInfo;
128917   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128918   int rc = SQLCIPHER_OK;
128919   int bGlobal = 0;                /* Collect 'global' stats as well as local */
128920
128921   memset(&sInfo, 0, sizeof(MatchInfo));
128922   sInfo.pCursor = pCsr;
128923   sInfo.nCol = pTab->nColumn;
128924
128925   /* If there is cached matchinfo() data, but the format string for the 
128926   ** cache does not match the format string for this request, discard 
128927   ** the cached data. */
128928   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
128929     assert( pCsr->aMatchinfo );
128930     sqlcipher3_free(pCsr->aMatchinfo);
128931     pCsr->zMatchinfo = 0;
128932     pCsr->aMatchinfo = 0;
128933   }
128934
128935   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
128936   ** matchinfo function has been called for this query. In this case 
128937   ** allocate the array used to accumulate the matchinfo data and
128938   ** initialize those elements that are constant for every row.
128939   */
128940   if( pCsr->aMatchinfo==0 ){
128941     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
128942     int nArg;                     /* Bytes in zArg */
128943     int i;                        /* Used to iterate through zArg */
128944
128945     /* Determine the number of phrases in the query */
128946     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
128947     sInfo.nPhrase = pCsr->nPhrase;
128948
128949     /* Determine the number of integers in the buffer returned by this call. */
128950     for(i=0; zArg[i]; i++){
128951       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
128952     }
128953
128954     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
128955     nArg = (int)strlen(zArg);
128956     pCsr->aMatchinfo = (u32 *)sqlcipher3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
128957     if( !pCsr->aMatchinfo ) return SQLCIPHER_NOMEM;
128958
128959     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
128960     pCsr->nMatchinfo = nMatchinfo;
128961     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
128962     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
128963     pCsr->isMatchinfoNeeded = 1;
128964     bGlobal = 1;
128965   }
128966
128967   sInfo.aMatchinfo = pCsr->aMatchinfo;
128968   sInfo.nPhrase = pCsr->nPhrase;
128969   if( pCsr->isMatchinfoNeeded ){
128970     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
128971     pCsr->isMatchinfoNeeded = 0;
128972   }
128973
128974   return rc;
128975 }
128976
128977 /*
128978 ** Implementation of snippet() function.
128979 */
128980 SQLCIPHER_PRIVATE void sqlcipher3Fts3Snippet(
128981   sqlcipher3_context *pCtx,          /* SQLite function call context */
128982   Fts3Cursor *pCsr,               /* Cursor object */
128983   const char *zStart,             /* Snippet start text - "<b>" */
128984   const char *zEnd,               /* Snippet end text - "</b>" */
128985   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
128986   int iCol,                       /* Extract snippet from this column */
128987   int nToken                      /* Approximate number of tokens in snippet */
128988 ){
128989   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128990   int rc = SQLCIPHER_OK;
128991   int i;
128992   StrBuffer res = {0, 0, 0};
128993
128994   /* The returned text includes up to four fragments of text extracted from
128995   ** the data in the current row. The first iteration of the for(...) loop
128996   ** below attempts to locate a single fragment of text nToken tokens in 
128997   ** size that contains at least one instance of all phrases in the query
128998   ** expression that appear in the current row. If such a fragment of text
128999   ** cannot be found, the second iteration of the loop attempts to locate
129000   ** a pair of fragments, and so on.
129001   */
129002   int nSnippet = 0;               /* Number of fragments in this snippet */
129003   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
129004   int nFToken = -1;               /* Number of tokens in each fragment */
129005
129006   if( !pCsr->pExpr ){
129007     sqlcipher3_result_text(pCtx, "", 0, SQLCIPHER_STATIC);
129008     return;
129009   }
129010
129011   for(nSnippet=1; 1; nSnippet++){
129012
129013     int iSnip;                    /* Loop counter 0..nSnippet-1 */
129014     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
129015     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
129016
129017     if( nToken>=0 ){
129018       nFToken = (nToken+nSnippet-1) / nSnippet;
129019     }else{
129020       nFToken = -1 * nToken;
129021     }
129022
129023     for(iSnip=0; iSnip<nSnippet; iSnip++){
129024       int iBestScore = -1;        /* Best score of columns checked so far */
129025       int iRead;                  /* Used to iterate through columns */
129026       SnippetFragment *pFragment = &aSnippet[iSnip];
129027
129028       memset(pFragment, 0, sizeof(*pFragment));
129029
129030       /* Loop through all columns of the table being considered for snippets.
129031       ** If the iCol argument to this function was negative, this means all
129032       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
129033       */
129034       for(iRead=0; iRead<pTab->nColumn; iRead++){
129035         SnippetFragment sF = {0, 0, 0, 0};
129036         int iS;
129037         if( iCol>=0 && iRead!=iCol ) continue;
129038
129039         /* Find the best snippet of nFToken tokens in column iRead. */
129040         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
129041         if( rc!=SQLCIPHER_OK ){
129042           goto snippet_out;
129043         }
129044         if( iS>iBestScore ){
129045           *pFragment = sF;
129046           iBestScore = iS;
129047         }
129048       }
129049
129050       mCovered |= pFragment->covered;
129051     }
129052
129053     /* If all query phrases seen by fts3BestSnippet() are present in at least
129054     ** one of the nSnippet snippet fragments, break out of the loop.
129055     */
129056     assert( (mCovered&mSeen)==mCovered );
129057     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
129058   }
129059
129060   assert( nFToken>0 );
129061
129062   for(i=0; i<nSnippet && rc==SQLCIPHER_OK; i++){
129063     rc = fts3SnippetText(pCsr, &aSnippet[i], 
129064         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
129065     );
129066   }
129067
129068  snippet_out:
129069   sqlcipher3Fts3SegmentsClose(pTab);
129070   if( rc!=SQLCIPHER_OK ){
129071     sqlcipher3_result_error_code(pCtx, rc);
129072     sqlcipher3_free(res.z);
129073   }else{
129074     sqlcipher3_result_text(pCtx, res.z, -1, sqlcipher3_free);
129075   }
129076 }
129077
129078
129079 typedef struct TermOffset TermOffset;
129080 typedef struct TermOffsetCtx TermOffsetCtx;
129081
129082 struct TermOffset {
129083   char *pList;                    /* Position-list */
129084   int iPos;                       /* Position just read from pList */
129085   int iOff;                       /* Offset of this term from read positions */
129086 };
129087
129088 struct TermOffsetCtx {
129089   Fts3Cursor *pCsr;
129090   int iCol;                       /* Column of table to populate aTerm for */
129091   int iTerm;
129092   sqlcipher3_int64 iDocid;
129093   TermOffset *aTerm;
129094 };
129095
129096 /*
129097 ** This function is an fts3ExprIterate() callback used by sqlcipher3Fts3Offsets().
129098 */
129099 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
129100   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
129101   int nTerm;                      /* Number of tokens in phrase */
129102   int iTerm;                      /* For looping through nTerm phrase terms */
129103   char *pList;                    /* Pointer to position list for phrase */
129104   int iPos = 0;                   /* First position in position-list */
129105
129106   UNUSED_PARAMETER(iPhrase);
129107   pList = sqlcipher3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
129108   nTerm = pExpr->pPhrase->nToken;
129109   if( pList ){
129110     fts3GetDeltaPosition(&pList, &iPos);
129111     assert( iPos>=0 );
129112   }
129113
129114   for(iTerm=0; iTerm<nTerm; iTerm++){
129115     TermOffset *pT = &p->aTerm[p->iTerm++];
129116     pT->iOff = nTerm-iTerm-1;
129117     pT->pList = pList;
129118     pT->iPos = iPos;
129119   }
129120
129121   return SQLCIPHER_OK;
129122 }
129123
129124 /*
129125 ** Implementation of offsets() function.
129126 */
129127 SQLCIPHER_PRIVATE void sqlcipher3Fts3Offsets(
129128   sqlcipher3_context *pCtx,          /* SQLite function call context */
129129   Fts3Cursor *pCsr                /* Cursor object */
129130 ){
129131   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129132   sqlcipher3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
129133   const char *ZDUMMY;             /* Dummy argument used with xNext() */
129134   int NDUMMY;                     /* Dummy argument used with xNext() */
129135   int rc;                         /* Return Code */
129136   int nToken;                     /* Number of tokens in query */
129137   int iCol;                       /* Column currently being processed */
129138   StrBuffer res = {0, 0, 0};      /* Result string */
129139   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
129140
129141   if( !pCsr->pExpr ){
129142     sqlcipher3_result_text(pCtx, "", 0, SQLCIPHER_STATIC);
129143     return;
129144   }
129145
129146   memset(&sCtx, 0, sizeof(sCtx));
129147   assert( pCsr->isRequireSeek==0 );
129148
129149   /* Count the number of terms in the query */
129150   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
129151   if( rc!=SQLCIPHER_OK ) goto offsets_out;
129152
129153   /* Allocate the array of TermOffset iterators. */
129154   sCtx.aTerm = (TermOffset *)sqlcipher3_malloc(sizeof(TermOffset)*nToken);
129155   if( 0==sCtx.aTerm ){
129156     rc = SQLCIPHER_NOMEM;
129157     goto offsets_out;
129158   }
129159   sCtx.iDocid = pCsr->iPrevId;
129160   sCtx.pCsr = pCsr;
129161
129162   /* Loop through the table columns, appending offset information to 
129163   ** string-buffer res for each column.
129164   */
129165   for(iCol=0; iCol<pTab->nColumn; iCol++){
129166     sqlcipher3_tokenizer_cursor *pC; /* Tokenizer cursor */
129167     int iStart;
129168     int iEnd;
129169     int iCurrent;
129170     const char *zDoc;
129171     int nDoc;
129172
129173     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
129174     ** no way that this operation can fail, so the return code from
129175     ** fts3ExprIterate() can be discarded.
129176     */
129177     sCtx.iCol = iCol;
129178     sCtx.iTerm = 0;
129179     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
129180
129181     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
129182     ** in column iCol, jump immediately to the next iteration of the loop.
129183     ** If an OOM occurs while retrieving the data (this can happen if SQLite
129184     ** needs to transform the data from utf-16 to utf-8), return SQLCIPHER_NOMEM 
129185     ** to the caller. 
129186     */
129187     zDoc = (const char *)sqlcipher3_column_text(pCsr->pStmt, iCol+1);
129188     nDoc = sqlcipher3_column_bytes(pCsr->pStmt, iCol+1);
129189     if( zDoc==0 ){
129190       if( sqlcipher3_column_type(pCsr->pStmt, iCol+1)==SQLCIPHER_NULL ){
129191         continue;
129192       }
129193       rc = SQLCIPHER_NOMEM;
129194       goto offsets_out;
129195     }
129196
129197     /* Initialize a tokenizer iterator to iterate through column iCol. */
129198     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
129199     if( rc!=SQLCIPHER_OK ) goto offsets_out;
129200     pC->pTokenizer = pTab->pTokenizer;
129201
129202     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
129203     while( rc==SQLCIPHER_OK ){
129204       int i;                      /* Used to loop through terms */
129205       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
129206       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
129207
129208       for(i=0; i<nToken; i++){
129209         TermOffset *pT = &sCtx.aTerm[i];
129210         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
129211           iMinPos = pT->iPos-pT->iOff;
129212           pTerm = pT;
129213         }
129214       }
129215
129216       if( !pTerm ){
129217         /* All offsets for this column have been gathered. */
129218         rc = SQLCIPHER_DONE;
129219       }else{
129220         assert( iCurrent<=iMinPos );
129221         if( 0==(0xFE&*pTerm->pList) ){
129222           pTerm->pList = 0;
129223         }else{
129224           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
129225         }
129226         while( rc==SQLCIPHER_OK && iCurrent<iMinPos ){
129227           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
129228         }
129229         if( rc==SQLCIPHER_OK ){
129230           char aBuffer[64];
129231           sqlcipher3_snprintf(sizeof(aBuffer), aBuffer, 
129232               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
129233           );
129234           rc = fts3StringAppend(&res, aBuffer, -1);
129235         }else if( rc==SQLCIPHER_DONE && pTab->zContentTbl==0 ){
129236           rc = FTS_CORRUPT_VTAB;
129237         }
129238       }
129239     }
129240     if( rc==SQLCIPHER_DONE ){
129241       rc = SQLCIPHER_OK;
129242     }
129243
129244     pMod->xClose(pC);
129245     if( rc!=SQLCIPHER_OK ) goto offsets_out;
129246   }
129247
129248  offsets_out:
129249   sqlcipher3_free(sCtx.aTerm);
129250   assert( rc!=SQLCIPHER_DONE );
129251   sqlcipher3Fts3SegmentsClose(pTab);
129252   if( rc!=SQLCIPHER_OK ){
129253     sqlcipher3_result_error_code(pCtx,  rc);
129254     sqlcipher3_free(res.z);
129255   }else{
129256     sqlcipher3_result_text(pCtx, res.z, res.n-1, sqlcipher3_free);
129257   }
129258   return;
129259 }
129260
129261 /*
129262 ** Implementation of matchinfo() function.
129263 */
129264 SQLCIPHER_PRIVATE void sqlcipher3Fts3Matchinfo(
129265   sqlcipher3_context *pContext,      /* Function call context */
129266   Fts3Cursor *pCsr,               /* FTS3 table cursor */
129267   const char *zArg                /* Second arg to matchinfo() function */
129268 ){
129269   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129270   int rc;
129271   int i;
129272   const char *zFormat;
129273
129274   if( zArg ){
129275     for(i=0; zArg[i]; i++){
129276       char *zErr = 0;
129277       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
129278         sqlcipher3_result_error(pContext, zErr, -1);
129279         sqlcipher3_free(zErr);
129280         return;
129281       }
129282     }
129283     zFormat = zArg;
129284   }else{
129285     zFormat = FTS3_MATCHINFO_DEFAULT;
129286   }
129287
129288   if( !pCsr->pExpr ){
129289     sqlcipher3_result_blob(pContext, "", 0, SQLCIPHER_STATIC);
129290     return;
129291   }
129292
129293   /* Retrieve matchinfo() data. */
129294   rc = fts3GetMatchinfo(pCsr, zFormat);
129295   sqlcipher3Fts3SegmentsClose(pTab);
129296
129297   if( rc!=SQLCIPHER_OK ){
129298     sqlcipher3_result_error_code(pContext, rc);
129299   }else{
129300     int n = pCsr->nMatchinfo * sizeof(u32);
129301     sqlcipher3_result_blob(pContext, pCsr->aMatchinfo, n, SQLCIPHER_TRANSIENT);
129302   }
129303 }
129304
129305 #endif
129306
129307 /************** End of fts3_snippet.c ****************************************/
129308 /************** Begin file rtree.c *******************************************/
129309 /*
129310 ** 2001 September 15
129311 **
129312 ** The author disclaims copyright to this source code.  In place of
129313 ** a legal notice, here is a blessing:
129314 **
129315 **    May you do good and not evil.
129316 **    May you find forgiveness for yourself and forgive others.
129317 **    May you share freely, never taking more than you give.
129318 **
129319 *************************************************************************
129320 ** This file contains code for implementations of the r-tree and r*-tree
129321 ** algorithms packaged as an SQLite virtual table module.
129322 */
129323
129324 /*
129325 ** Database Format of R-Tree Tables
129326 ** --------------------------------
129327 **
129328 ** The data structure for a single virtual r-tree table is stored in three 
129329 ** native SQLite tables declared as follows. In each case, the '%' character
129330 ** in the table name is replaced with the user-supplied name of the r-tree
129331 ** table.
129332 **
129333 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
129334 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
129335 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
129336 **
129337 ** The data for each node of the r-tree structure is stored in the %_node
129338 ** table. For each node that is not the root node of the r-tree, there is
129339 ** an entry in the %_parent table associating the node with its parent.
129340 ** And for each row of data in the table, there is an entry in the %_rowid
129341 ** table that maps from the entries rowid to the id of the node that it
129342 ** is stored on.
129343 **
129344 ** The root node of an r-tree always exists, even if the r-tree table is
129345 ** empty. The nodeno of the root node is always 1. All other nodes in the
129346 ** table must be the same size as the root node. The content of each node
129347 ** is formatted as follows:
129348 **
129349 **   1. If the node is the root node (node 1), then the first 2 bytes
129350 **      of the node contain the tree depth as a big-endian integer.
129351 **      For non-root nodes, the first 2 bytes are left unused.
129352 **
129353 **   2. The next 2 bytes contain the number of entries currently 
129354 **      stored in the node.
129355 **
129356 **   3. The remainder of the node contains the node entries. Each entry
129357 **      consists of a single 8-byte integer followed by an even number
129358 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
129359 **      of a record. For internal nodes it is the node number of a
129360 **      child page.
129361 */
129362
129363 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_RTREE)
129364
129365 /*
129366 ** This file contains an implementation of a couple of different variants
129367 ** of the r-tree algorithm. See the README file for further details. The 
129368 ** same data-structure is used for all, but the algorithms for insert and
129369 ** delete operations vary. The variants used are selected at compile time 
129370 ** by defining the following symbols:
129371 */
129372
129373 /* Either, both or none of the following may be set to activate 
129374 ** r*tree variant algorithms.
129375 */
129376 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
129377 #define VARIANT_RSTARTREE_REINSERT      1
129378
129379 /* 
129380 ** Exactly one of the following must be set to 1.
129381 */
129382 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
129383 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
129384 #define VARIANT_RSTARTREE_SPLIT         1
129385
129386 #define VARIANT_GUTTMAN_SPLIT \
129387         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
129388
129389 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
129390   #define PickNext QuadraticPickNext
129391   #define PickSeeds QuadraticPickSeeds
129392   #define AssignCells splitNodeGuttman
129393 #endif
129394 #if VARIANT_GUTTMAN_LINEAR_SPLIT
129395   #define PickNext LinearPickNext
129396   #define PickSeeds LinearPickSeeds
129397   #define AssignCells splitNodeGuttman
129398 #endif
129399 #if VARIANT_RSTARTREE_SPLIT
129400   #define AssignCells splitNodeStartree
129401 #endif
129402
129403 #if !defined(NDEBUG) && !defined(SQLCIPHER_DEBUG) 
129404 # define NDEBUG 1
129405 #endif
129406
129407 #ifndef SQLCIPHER_CORE
129408   SQLCIPHER_EXTENSION_INIT1
129409 #else
129410 #endif
129411
129412 /* #include <string.h> */
129413 /* #include <assert.h> */
129414
129415 #ifndef SQLCIPHER_AMALGAMATION
129416 #include "sqlcipher3rtree.h"
129417 typedef sqlcipher3_int64 i64;
129418 typedef unsigned char u8;
129419 typedef unsigned int u32;
129420 #endif
129421
129422 /*  The following macro is used to suppress compiler warnings.
129423 */
129424 #ifndef UNUSED_PARAMETER
129425 # define UNUSED_PARAMETER(x) (void)(x)
129426 #endif
129427
129428 typedef struct Rtree Rtree;
129429 typedef struct RtreeCursor RtreeCursor;
129430 typedef struct RtreeNode RtreeNode;
129431 typedef struct RtreeCell RtreeCell;
129432 typedef struct RtreeConstraint RtreeConstraint;
129433 typedef struct RtreeMatchArg RtreeMatchArg;
129434 typedef struct RtreeGeomCallback RtreeGeomCallback;
129435 typedef union RtreeCoord RtreeCoord;
129436
129437 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
129438 #define RTREE_MAX_DIMENSIONS 5
129439
129440 /* Size of hash table Rtree.aHash. This hash table is not expected to
129441 ** ever contain very many entries, so a fixed number of buckets is 
129442 ** used.
129443 */
129444 #define HASHSIZE 128
129445
129446 /* 
129447 ** An rtree virtual-table object.
129448 */
129449 struct Rtree {
129450   sqlcipher3_vtab base;
129451   sqlcipher3 *db;                /* Host database connection */
129452   int iNodeSize;              /* Size in bytes of each node in the node table */
129453   int nDim;                   /* Number of dimensions */
129454   int nBytesPerCell;          /* Bytes consumed per cell */
129455   int iDepth;                 /* Current depth of the r-tree structure */
129456   char *zDb;                  /* Name of database containing r-tree table */
129457   char *zName;                /* Name of r-tree table */ 
129458   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
129459   int nBusy;                  /* Current number of users of this structure */
129460
129461   /* List of nodes removed during a CondenseTree operation. List is
129462   ** linked together via the pointer normally used for hash chains -
129463   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
129464   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
129465   */
129466   RtreeNode *pDeleted;
129467   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
129468
129469   /* Statements to read/write/delete a record from xxx_node */
129470   sqlcipher3_stmt *pReadNode;
129471   sqlcipher3_stmt *pWriteNode;
129472   sqlcipher3_stmt *pDeleteNode;
129473
129474   /* Statements to read/write/delete a record from xxx_rowid */
129475   sqlcipher3_stmt *pReadRowid;
129476   sqlcipher3_stmt *pWriteRowid;
129477   sqlcipher3_stmt *pDeleteRowid;
129478
129479   /* Statements to read/write/delete a record from xxx_parent */
129480   sqlcipher3_stmt *pReadParent;
129481   sqlcipher3_stmt *pWriteParent;
129482   sqlcipher3_stmt *pDeleteParent;
129483
129484   int eCoordType;
129485 };
129486
129487 /* Possible values for eCoordType: */
129488 #define RTREE_COORD_REAL32 0
129489 #define RTREE_COORD_INT32  1
129490
129491 /*
129492 ** The minimum number of cells allowed for a node is a third of the 
129493 ** maximum. In Gutman's notation:
129494 **
129495 **     m = M/3
129496 **
129497 ** If an R*-tree "Reinsert" operation is required, the same number of
129498 ** cells are removed from the overfull node and reinserted into the tree.
129499 */
129500 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
129501 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
129502 #define RTREE_MAXCELLS 51
129503
129504 /*
129505 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
129506 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
129507 ** Therefore all non-root nodes must contain at least 3 entries. Since 
129508 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
129509 ** 40 or less.
129510 */
129511 #define RTREE_MAX_DEPTH 40
129512
129513 /* 
129514 ** An rtree cursor object.
129515 */
129516 struct RtreeCursor {
129517   sqlcipher3_vtab_cursor base;
129518   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
129519   int iCell;                        /* Index of current cell in pNode */
129520   int iStrategy;                    /* Copy of idxNum search parameter */
129521   int nConstraint;                  /* Number of entries in aConstraint */
129522   RtreeConstraint *aConstraint;     /* Search constraints. */
129523 };
129524
129525 union RtreeCoord {
129526   float f;
129527   int i;
129528 };
129529
129530 /*
129531 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
129532 ** formatted as a double. This macro assumes that local variable pRtree points
129533 ** to the Rtree structure associated with the RtreeCoord.
129534 */
129535 #define DCOORD(coord) (                           \
129536   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
129537     ((double)coord.f) :                           \
129538     ((double)coord.i)                             \
129539 )
129540
129541 /*
129542 ** A search constraint.
129543 */
129544 struct RtreeConstraint {
129545   int iCoord;                     /* Index of constrained coordinate */
129546   int op;                         /* Constraining operation */
129547   double rValue;                  /* Constraint value. */
129548   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *);
129549   sqlcipher3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
129550 };
129551
129552 /* Possible values for RtreeConstraint.op */
129553 #define RTREE_EQ    0x41
129554 #define RTREE_LE    0x42
129555 #define RTREE_LT    0x43
129556 #define RTREE_GE    0x44
129557 #define RTREE_GT    0x45
129558 #define RTREE_MATCH 0x46
129559
129560 /* 
129561 ** An rtree structure node.
129562 */
129563 struct RtreeNode {
129564   RtreeNode *pParent;               /* Parent node */
129565   i64 iNode;
129566   int nRef;
129567   int isDirty;
129568   u8 *zData;
129569   RtreeNode *pNext;                 /* Next node in this hash chain */
129570 };
129571 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
129572
129573 /* 
129574 ** Structure to store a deserialized rtree record.
129575 */
129576 struct RtreeCell {
129577   i64 iRowid;
129578   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
129579 };
129580
129581
129582 /*
129583 ** Value for the first field of every RtreeMatchArg object. The MATCH
129584 ** operator tests that the first field of a blob operand matches this
129585 ** value to avoid operating on invalid blobs (which could cause a segfault).
129586 */
129587 #define RTREE_GEOMETRY_MAGIC 0x891245AB
129588
129589 /*
129590 ** An instance of this structure must be supplied as a blob argument to
129591 ** the right-hand-side of an SQL MATCH operator used to constrain an
129592 ** r-tree query.
129593 */
129594 struct RtreeMatchArg {
129595   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
129596   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *);
129597   void *pContext;
129598   int nParam;
129599   double aParam[1];
129600 };
129601
129602 /*
129603 ** When a geometry callback is created (see sqlcipher3_rtree_geometry_callback),
129604 ** a single instance of the following structure is allocated. It is used
129605 ** as the context for the user-function created by by s_r_g_c(). The object
129606 ** is eventually deleted by the destructor mechanism provided by
129607 ** sqlcipher3_create_function_v2() (which is called by s_r_g_c() to create
129608 ** the geometry callback function).
129609 */
129610 struct RtreeGeomCallback {
129611   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *);
129612   void *pContext;
129613 };
129614
129615 #ifndef MAX
129616 # define MAX(x,y) ((x) < (y) ? (y) : (x))
129617 #endif
129618 #ifndef MIN
129619 # define MIN(x,y) ((x) > (y) ? (y) : (x))
129620 #endif
129621
129622 /*
129623 ** Functions to deserialize a 16 bit integer, 32 bit real number and
129624 ** 64 bit integer. The deserialized value is returned.
129625 */
129626 static int readInt16(u8 *p){
129627   return (p[0]<<8) + p[1];
129628 }
129629 static void readCoord(u8 *p, RtreeCoord *pCoord){
129630   u32 i = (
129631     (((u32)p[0]) << 24) + 
129632     (((u32)p[1]) << 16) + 
129633     (((u32)p[2]) <<  8) + 
129634     (((u32)p[3]) <<  0)
129635   );
129636   *(u32 *)pCoord = i;
129637 }
129638 static i64 readInt64(u8 *p){
129639   return (
129640     (((i64)p[0]) << 56) + 
129641     (((i64)p[1]) << 48) + 
129642     (((i64)p[2]) << 40) + 
129643     (((i64)p[3]) << 32) + 
129644     (((i64)p[4]) << 24) + 
129645     (((i64)p[5]) << 16) + 
129646     (((i64)p[6]) <<  8) + 
129647     (((i64)p[7]) <<  0)
129648   );
129649 }
129650
129651 /*
129652 ** Functions to serialize a 16 bit integer, 32 bit real number and
129653 ** 64 bit integer. The value returned is the number of bytes written
129654 ** to the argument buffer (always 2, 4 and 8 respectively).
129655 */
129656 static int writeInt16(u8 *p, int i){
129657   p[0] = (i>> 8)&0xFF;
129658   p[1] = (i>> 0)&0xFF;
129659   return 2;
129660 }
129661 static int writeCoord(u8 *p, RtreeCoord *pCoord){
129662   u32 i;
129663   assert( sizeof(RtreeCoord)==4 );
129664   assert( sizeof(u32)==4 );
129665   i = *(u32 *)pCoord;
129666   p[0] = (i>>24)&0xFF;
129667   p[1] = (i>>16)&0xFF;
129668   p[2] = (i>> 8)&0xFF;
129669   p[3] = (i>> 0)&0xFF;
129670   return 4;
129671 }
129672 static int writeInt64(u8 *p, i64 i){
129673   p[0] = (i>>56)&0xFF;
129674   p[1] = (i>>48)&0xFF;
129675   p[2] = (i>>40)&0xFF;
129676   p[3] = (i>>32)&0xFF;
129677   p[4] = (i>>24)&0xFF;
129678   p[5] = (i>>16)&0xFF;
129679   p[6] = (i>> 8)&0xFF;
129680   p[7] = (i>> 0)&0xFF;
129681   return 8;
129682 }
129683
129684 /*
129685 ** Increment the reference count of node p.
129686 */
129687 static void nodeReference(RtreeNode *p){
129688   if( p ){
129689     p->nRef++;
129690   }
129691 }
129692
129693 /*
129694 ** Clear the content of node p (set all bytes to 0x00).
129695 */
129696 static void nodeZero(Rtree *pRtree, RtreeNode *p){
129697   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
129698   p->isDirty = 1;
129699 }
129700
129701 /*
129702 ** Given a node number iNode, return the corresponding key to use
129703 ** in the Rtree.aHash table.
129704 */
129705 static int nodeHash(i64 iNode){
129706   return (
129707     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
129708     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
129709   ) % HASHSIZE;
129710 }
129711
129712 /*
129713 ** Search the node hash table for node iNode. If found, return a pointer
129714 ** to it. Otherwise, return 0.
129715 */
129716 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
129717   RtreeNode *p;
129718   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
129719   return p;
129720 }
129721
129722 /*
129723 ** Add node pNode to the node hash table.
129724 */
129725 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
129726   int iHash;
129727   assert( pNode->pNext==0 );
129728   iHash = nodeHash(pNode->iNode);
129729   pNode->pNext = pRtree->aHash[iHash];
129730   pRtree->aHash[iHash] = pNode;
129731 }
129732
129733 /*
129734 ** Remove node pNode from the node hash table.
129735 */
129736 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
129737   RtreeNode **pp;
129738   if( pNode->iNode!=0 ){
129739     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
129740     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
129741     *pp = pNode->pNext;
129742     pNode->pNext = 0;
129743   }
129744 }
129745
129746 /*
129747 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
129748 ** indicating that node has not yet been assigned a node number. It is
129749 ** assigned a node number when nodeWrite() is called to write the
129750 ** node contents out to the database.
129751 */
129752 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
129753   RtreeNode *pNode;
129754   pNode = (RtreeNode *)sqlcipher3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
129755   if( pNode ){
129756     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
129757     pNode->zData = (u8 *)&pNode[1];
129758     pNode->nRef = 1;
129759     pNode->pParent = pParent;
129760     pNode->isDirty = 1;
129761     nodeReference(pParent);
129762   }
129763   return pNode;
129764 }
129765
129766 /*
129767 ** Obtain a reference to an r-tree node.
129768 */
129769 static int
129770 nodeAcquire(
129771   Rtree *pRtree,             /* R-tree structure */
129772   i64 iNode,                 /* Node number to load */
129773   RtreeNode *pParent,        /* Either the parent node or NULL */
129774   RtreeNode **ppNode         /* OUT: Acquired node */
129775 ){
129776   int rc;
129777   int rc2 = SQLCIPHER_OK;
129778   RtreeNode *pNode;
129779
129780   /* Check if the requested node is already in the hash table. If so,
129781   ** increase its reference count and return it.
129782   */
129783   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
129784     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
129785     if( pParent && !pNode->pParent ){
129786       nodeReference(pParent);
129787       pNode->pParent = pParent;
129788     }
129789     pNode->nRef++;
129790     *ppNode = pNode;
129791     return SQLCIPHER_OK;
129792   }
129793
129794   sqlcipher3_bind_int64(pRtree->pReadNode, 1, iNode);
129795   rc = sqlcipher3_step(pRtree->pReadNode);
129796   if( rc==SQLCIPHER_ROW ){
129797     const u8 *zBlob = sqlcipher3_column_blob(pRtree->pReadNode, 0);
129798     if( pRtree->iNodeSize==sqlcipher3_column_bytes(pRtree->pReadNode, 0) ){
129799       pNode = (RtreeNode *)sqlcipher3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
129800       if( !pNode ){
129801         rc2 = SQLCIPHER_NOMEM;
129802       }else{
129803         pNode->pParent = pParent;
129804         pNode->zData = (u8 *)&pNode[1];
129805         pNode->nRef = 1;
129806         pNode->iNode = iNode;
129807         pNode->isDirty = 0;
129808         pNode->pNext = 0;
129809         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
129810         nodeReference(pParent);
129811       }
129812     }
129813   }
129814   rc = sqlcipher3_reset(pRtree->pReadNode);
129815   if( rc==SQLCIPHER_OK ) rc = rc2;
129816
129817   /* If the root node was just loaded, set pRtree->iDepth to the height
129818   ** of the r-tree structure. A height of zero means all data is stored on
129819   ** the root node. A height of one means the children of the root node
129820   ** are the leaves, and so on. If the depth as specified on the root node
129821   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
129822   */
129823   if( pNode && iNode==1 ){
129824     pRtree->iDepth = readInt16(pNode->zData);
129825     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
129826       rc = SQLCIPHER_CORRUPT_VTAB;
129827     }
129828   }
129829
129830   /* If no error has occurred so far, check if the "number of entries"
129831   ** field on the node is too large. If so, set the return code to 
129832   ** SQLCIPHER_CORRUPT_VTAB.
129833   */
129834   if( pNode && rc==SQLCIPHER_OK ){
129835     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
129836       rc = SQLCIPHER_CORRUPT_VTAB;
129837     }
129838   }
129839
129840   if( rc==SQLCIPHER_OK ){
129841     if( pNode!=0 ){
129842       nodeHashInsert(pRtree, pNode);
129843     }else{
129844       rc = SQLCIPHER_CORRUPT_VTAB;
129845     }
129846     *ppNode = pNode;
129847   }else{
129848     sqlcipher3_free(pNode);
129849     *ppNode = 0;
129850   }
129851
129852   return rc;
129853 }
129854
129855 /*
129856 ** Overwrite cell iCell of node pNode with the contents of pCell.
129857 */
129858 static void nodeOverwriteCell(
129859   Rtree *pRtree, 
129860   RtreeNode *pNode,  
129861   RtreeCell *pCell, 
129862   int iCell
129863 ){
129864   int ii;
129865   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
129866   p += writeInt64(p, pCell->iRowid);
129867   for(ii=0; ii<(pRtree->nDim*2); ii++){
129868     p += writeCoord(p, &pCell->aCoord[ii]);
129869   }
129870   pNode->isDirty = 1;
129871 }
129872
129873 /*
129874 ** Remove cell the cell with index iCell from node pNode.
129875 */
129876 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
129877   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
129878   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
129879   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
129880   memmove(pDst, pSrc, nByte);
129881   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
129882   pNode->isDirty = 1;
129883 }
129884
129885 /*
129886 ** Insert the contents of cell pCell into node pNode. If the insert
129887 ** is successful, return SQLCIPHER_OK.
129888 **
129889 ** If there is not enough free space in pNode, return SQLCIPHER_FULL.
129890 */
129891 static int
129892 nodeInsertCell(
129893   Rtree *pRtree, 
129894   RtreeNode *pNode, 
129895   RtreeCell *pCell 
129896 ){
129897   int nCell;                    /* Current number of cells in pNode */
129898   int nMaxCell;                 /* Maximum number of cells for pNode */
129899
129900   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
129901   nCell = NCELL(pNode);
129902
129903   assert( nCell<=nMaxCell );
129904   if( nCell<nMaxCell ){
129905     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
129906     writeInt16(&pNode->zData[2], nCell+1);
129907     pNode->isDirty = 1;
129908   }
129909
129910   return (nCell==nMaxCell);
129911 }
129912
129913 /*
129914 ** If the node is dirty, write it out to the database.
129915 */
129916 static int
129917 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
129918   int rc = SQLCIPHER_OK;
129919   if( pNode->isDirty ){
129920     sqlcipher3_stmt *p = pRtree->pWriteNode;
129921     if( pNode->iNode ){
129922       sqlcipher3_bind_int64(p, 1, pNode->iNode);
129923     }else{
129924       sqlcipher3_bind_null(p, 1);
129925     }
129926     sqlcipher3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLCIPHER_STATIC);
129927     sqlcipher3_step(p);
129928     pNode->isDirty = 0;
129929     rc = sqlcipher3_reset(p);
129930     if( pNode->iNode==0 && rc==SQLCIPHER_OK ){
129931       pNode->iNode = sqlcipher3_last_insert_rowid(pRtree->db);
129932       nodeHashInsert(pRtree, pNode);
129933     }
129934   }
129935   return rc;
129936 }
129937
129938 /*
129939 ** Release a reference to a node. If the node is dirty and the reference
129940 ** count drops to zero, the node data is written to the database.
129941 */
129942 static int
129943 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
129944   int rc = SQLCIPHER_OK;
129945   if( pNode ){
129946     assert( pNode->nRef>0 );
129947     pNode->nRef--;
129948     if( pNode->nRef==0 ){
129949       if( pNode->iNode==1 ){
129950         pRtree->iDepth = -1;
129951       }
129952       if( pNode->pParent ){
129953         rc = nodeRelease(pRtree, pNode->pParent);
129954       }
129955       if( rc==SQLCIPHER_OK ){
129956         rc = nodeWrite(pRtree, pNode);
129957       }
129958       nodeHashDelete(pRtree, pNode);
129959       sqlcipher3_free(pNode);
129960     }
129961   }
129962   return rc;
129963 }
129964
129965 /*
129966 ** Return the 64-bit integer value associated with cell iCell of
129967 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
129968 ** an internal node, then the 64-bit integer is a child page number.
129969 */
129970 static i64 nodeGetRowid(
129971   Rtree *pRtree, 
129972   RtreeNode *pNode, 
129973   int iCell
129974 ){
129975   assert( iCell<NCELL(pNode) );
129976   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
129977 }
129978
129979 /*
129980 ** Return coordinate iCoord from cell iCell in node pNode.
129981 */
129982 static void nodeGetCoord(
129983   Rtree *pRtree, 
129984   RtreeNode *pNode, 
129985   int iCell,
129986   int iCoord,
129987   RtreeCoord *pCoord           /* Space to write result to */
129988 ){
129989   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
129990 }
129991
129992 /*
129993 ** Deserialize cell iCell of node pNode. Populate the structure pointed
129994 ** to by pCell with the results.
129995 */
129996 static void nodeGetCell(
129997   Rtree *pRtree, 
129998   RtreeNode *pNode, 
129999   int iCell,
130000   RtreeCell *pCell
130001 ){
130002   int ii;
130003   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
130004   for(ii=0; ii<pRtree->nDim*2; ii++){
130005     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
130006   }
130007 }
130008
130009
130010 /* Forward declaration for the function that does the work of
130011 ** the virtual table module xCreate() and xConnect() methods.
130012 */
130013 static int rtreeInit(
130014   sqlcipher3 *, void *, int, const char *const*, sqlcipher3_vtab **, char **, int
130015 );
130016
130017 /* 
130018 ** Rtree virtual table module xCreate method.
130019 */
130020 static int rtreeCreate(
130021   sqlcipher3 *db,
130022   void *pAux,
130023   int argc, const char *const*argv,
130024   sqlcipher3_vtab **ppVtab,
130025   char **pzErr
130026 ){
130027   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
130028 }
130029
130030 /* 
130031 ** Rtree virtual table module xConnect method.
130032 */
130033 static int rtreeConnect(
130034   sqlcipher3 *db,
130035   void *pAux,
130036   int argc, const char *const*argv,
130037   sqlcipher3_vtab **ppVtab,
130038   char **pzErr
130039 ){
130040   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
130041 }
130042
130043 /*
130044 ** Increment the r-tree reference count.
130045 */
130046 static void rtreeReference(Rtree *pRtree){
130047   pRtree->nBusy++;
130048 }
130049
130050 /*
130051 ** Decrement the r-tree reference count. When the reference count reaches
130052 ** zero the structure is deleted.
130053 */
130054 static void rtreeRelease(Rtree *pRtree){
130055   pRtree->nBusy--;
130056   if( pRtree->nBusy==0 ){
130057     sqlcipher3_finalize(pRtree->pReadNode);
130058     sqlcipher3_finalize(pRtree->pWriteNode);
130059     sqlcipher3_finalize(pRtree->pDeleteNode);
130060     sqlcipher3_finalize(pRtree->pReadRowid);
130061     sqlcipher3_finalize(pRtree->pWriteRowid);
130062     sqlcipher3_finalize(pRtree->pDeleteRowid);
130063     sqlcipher3_finalize(pRtree->pReadParent);
130064     sqlcipher3_finalize(pRtree->pWriteParent);
130065     sqlcipher3_finalize(pRtree->pDeleteParent);
130066     sqlcipher3_free(pRtree);
130067   }
130068 }
130069
130070 /* 
130071 ** Rtree virtual table module xDisconnect method.
130072 */
130073 static int rtreeDisconnect(sqlcipher3_vtab *pVtab){
130074   rtreeRelease((Rtree *)pVtab);
130075   return SQLCIPHER_OK;
130076 }
130077
130078 /* 
130079 ** Rtree virtual table module xDestroy method.
130080 */
130081 static int rtreeDestroy(sqlcipher3_vtab *pVtab){
130082   Rtree *pRtree = (Rtree *)pVtab;
130083   int rc;
130084   char *zCreate = sqlcipher3_mprintf(
130085     "DROP TABLE '%q'.'%q_node';"
130086     "DROP TABLE '%q'.'%q_rowid';"
130087     "DROP TABLE '%q'.'%q_parent';",
130088     pRtree->zDb, pRtree->zName, 
130089     pRtree->zDb, pRtree->zName,
130090     pRtree->zDb, pRtree->zName
130091   );
130092   if( !zCreate ){
130093     rc = SQLCIPHER_NOMEM;
130094   }else{
130095     rc = sqlcipher3_exec(pRtree->db, zCreate, 0, 0, 0);
130096     sqlcipher3_free(zCreate);
130097   }
130098   if( rc==SQLCIPHER_OK ){
130099     rtreeRelease(pRtree);
130100   }
130101
130102   return rc;
130103 }
130104
130105 /* 
130106 ** Rtree virtual table module xOpen method.
130107 */
130108 static int rtreeOpen(sqlcipher3_vtab *pVTab, sqlcipher3_vtab_cursor **ppCursor){
130109   int rc = SQLCIPHER_NOMEM;
130110   RtreeCursor *pCsr;
130111
130112   pCsr = (RtreeCursor *)sqlcipher3_malloc(sizeof(RtreeCursor));
130113   if( pCsr ){
130114     memset(pCsr, 0, sizeof(RtreeCursor));
130115     pCsr->base.pVtab = pVTab;
130116     rc = SQLCIPHER_OK;
130117   }
130118   *ppCursor = (sqlcipher3_vtab_cursor *)pCsr;
130119
130120   return rc;
130121 }
130122
130123
130124 /*
130125 ** Free the RtreeCursor.aConstraint[] array and its contents.
130126 */
130127 static void freeCursorConstraints(RtreeCursor *pCsr){
130128   if( pCsr->aConstraint ){
130129     int i;                        /* Used to iterate through constraint array */
130130     for(i=0; i<pCsr->nConstraint; i++){
130131       sqlcipher3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
130132       if( pGeom ){
130133         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
130134         sqlcipher3_free(pGeom);
130135       }
130136     }
130137     sqlcipher3_free(pCsr->aConstraint);
130138     pCsr->aConstraint = 0;
130139   }
130140 }
130141
130142 /* 
130143 ** Rtree virtual table module xClose method.
130144 */
130145 static int rtreeClose(sqlcipher3_vtab_cursor *cur){
130146   Rtree *pRtree = (Rtree *)(cur->pVtab);
130147   int rc;
130148   RtreeCursor *pCsr = (RtreeCursor *)cur;
130149   freeCursorConstraints(pCsr);
130150   rc = nodeRelease(pRtree, pCsr->pNode);
130151   sqlcipher3_free(pCsr);
130152   return rc;
130153 }
130154
130155 /*
130156 ** Rtree virtual table module xEof method.
130157 **
130158 ** Return non-zero if the cursor does not currently point to a valid 
130159 ** record (i.e if the scan has finished), or zero otherwise.
130160 */
130161 static int rtreeEof(sqlcipher3_vtab_cursor *cur){
130162   RtreeCursor *pCsr = (RtreeCursor *)cur;
130163   return (pCsr->pNode==0);
130164 }
130165
130166 /*
130167 ** The r-tree constraint passed as the second argument to this function is
130168 ** guaranteed to be a MATCH constraint.
130169 */
130170 static int testRtreeGeom(
130171   Rtree *pRtree,                  /* R-Tree object */
130172   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
130173   RtreeCell *pCell,               /* Cell to test */
130174   int *pbRes                      /* OUT: Test result */
130175 ){
130176   int i;
130177   double aCoord[RTREE_MAX_DIMENSIONS*2];
130178   int nCoord = pRtree->nDim*2;
130179
130180   assert( pConstraint->op==RTREE_MATCH );
130181   assert( pConstraint->pGeom );
130182
130183   for(i=0; i<nCoord; i++){
130184     aCoord[i] = DCOORD(pCell->aCoord[i]);
130185   }
130186   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
130187 }
130188
130189 /* 
130190 ** Cursor pCursor currently points to a cell in a non-leaf page.
130191 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
130192 ** (excluded) by the constraints in the pCursor->aConstraint[] 
130193 ** array, or false otherwise.
130194 **
130195 ** Return SQLCIPHER_OK if successful or an SQLite error code if an error
130196 ** occurs within a geometry callback.
130197 */
130198 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
130199   RtreeCell cell;
130200   int ii;
130201   int bRes = 0;
130202   int rc = SQLCIPHER_OK;
130203
130204   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
130205   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
130206     RtreeConstraint *p = &pCursor->aConstraint[ii];
130207     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
130208     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
130209
130210     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
130211         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
130212     );
130213
130214     switch( p->op ){
130215       case RTREE_LE: case RTREE_LT: 
130216         bRes = p->rValue<cell_min; 
130217         break;
130218
130219       case RTREE_GE: case RTREE_GT: 
130220         bRes = p->rValue>cell_max; 
130221         break;
130222
130223       case RTREE_EQ:
130224         bRes = (p->rValue>cell_max || p->rValue<cell_min);
130225         break;
130226
130227       default: {
130228         assert( p->op==RTREE_MATCH );
130229         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
130230         bRes = !bRes;
130231         break;
130232       }
130233     }
130234   }
130235
130236   *pbEof = bRes;
130237   return rc;
130238 }
130239
130240 /* 
130241 ** Test if the cell that cursor pCursor currently points to
130242 ** would be filtered (excluded) by the constraints in the 
130243 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
130244 ** returning. If the cell is not filtered (excluded) by the constraints,
130245 ** set pbEof to zero.
130246 **
130247 ** Return SQLCIPHER_OK if successful or an SQLite error code if an error
130248 ** occurs within a geometry callback.
130249 **
130250 ** This function assumes that the cell is part of a leaf node.
130251 */
130252 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
130253   RtreeCell cell;
130254   int ii;
130255   *pbEof = 0;
130256
130257   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
130258   for(ii=0; ii<pCursor->nConstraint; ii++){
130259     RtreeConstraint *p = &pCursor->aConstraint[ii];
130260     double coord = DCOORD(cell.aCoord[p->iCoord]);
130261     int res;
130262     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
130263         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
130264     );
130265     switch( p->op ){
130266       case RTREE_LE: res = (coord<=p->rValue); break;
130267       case RTREE_LT: res = (coord<p->rValue);  break;
130268       case RTREE_GE: res = (coord>=p->rValue); break;
130269       case RTREE_GT: res = (coord>p->rValue);  break;
130270       case RTREE_EQ: res = (coord==p->rValue); break;
130271       default: {
130272         int rc;
130273         assert( p->op==RTREE_MATCH );
130274         rc = testRtreeGeom(pRtree, p, &cell, &res);
130275         if( rc!=SQLCIPHER_OK ){
130276           return rc;
130277         }
130278         break;
130279       }
130280     }
130281
130282     if( !res ){
130283       *pbEof = 1;
130284       return SQLCIPHER_OK;
130285     }
130286   }
130287
130288   return SQLCIPHER_OK;
130289 }
130290
130291 /*
130292 ** Cursor pCursor currently points at a node that heads a sub-tree of
130293 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
130294 ** to point to the left-most cell of the sub-tree that matches the 
130295 ** configured constraints.
130296 */
130297 static int descendToCell(
130298   Rtree *pRtree, 
130299   RtreeCursor *pCursor, 
130300   int iHeight,
130301   int *pEof                 /* OUT: Set to true if cannot descend */
130302 ){
130303   int isEof;
130304   int rc;
130305   int ii;
130306   RtreeNode *pChild;
130307   sqlcipher3_int64 iRowid;
130308
130309   RtreeNode *pSavedNode = pCursor->pNode;
130310   int iSavedCell = pCursor->iCell;
130311
130312   assert( iHeight>=0 );
130313
130314   if( iHeight==0 ){
130315     rc = testRtreeEntry(pRtree, pCursor, &isEof);
130316   }else{
130317     rc = testRtreeCell(pRtree, pCursor, &isEof);
130318   }
130319   if( rc!=SQLCIPHER_OK || isEof || iHeight==0 ){
130320     goto descend_to_cell_out;
130321   }
130322
130323   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
130324   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
130325   if( rc!=SQLCIPHER_OK ){
130326     goto descend_to_cell_out;
130327   }
130328
130329   nodeRelease(pRtree, pCursor->pNode);
130330   pCursor->pNode = pChild;
130331   isEof = 1;
130332   for(ii=0; isEof && ii<NCELL(pChild); ii++){
130333     pCursor->iCell = ii;
130334     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
130335     if( rc!=SQLCIPHER_OK ){
130336       goto descend_to_cell_out;
130337     }
130338   }
130339
130340   if( isEof ){
130341     assert( pCursor->pNode==pChild );
130342     nodeReference(pSavedNode);
130343     nodeRelease(pRtree, pChild);
130344     pCursor->pNode = pSavedNode;
130345     pCursor->iCell = iSavedCell;
130346   }
130347
130348 descend_to_cell_out:
130349   *pEof = isEof;
130350   return rc;
130351 }
130352
130353 /*
130354 ** One of the cells in node pNode is guaranteed to have a 64-bit 
130355 ** integer value equal to iRowid. Return the index of this cell.
130356 */
130357 static int nodeRowidIndex(
130358   Rtree *pRtree, 
130359   RtreeNode *pNode, 
130360   i64 iRowid,
130361   int *piIndex
130362 ){
130363   int ii;
130364   int nCell = NCELL(pNode);
130365   for(ii=0; ii<nCell; ii++){
130366     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
130367       *piIndex = ii;
130368       return SQLCIPHER_OK;
130369     }
130370   }
130371   return SQLCIPHER_CORRUPT_VTAB;
130372 }
130373
130374 /*
130375 ** Return the index of the cell containing a pointer to node pNode
130376 ** in its parent. If pNode is the root node, return -1.
130377 */
130378 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
130379   RtreeNode *pParent = pNode->pParent;
130380   if( pParent ){
130381     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
130382   }
130383   *piIndex = -1;
130384   return SQLCIPHER_OK;
130385 }
130386
130387 /* 
130388 ** Rtree virtual table module xNext method.
130389 */
130390 static int rtreeNext(sqlcipher3_vtab_cursor *pVtabCursor){
130391   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
130392   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
130393   int rc = SQLCIPHER_OK;
130394
130395   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
130396   ** already at EOF. It is against the rules to call the xNext() method of
130397   ** a cursor that has already reached EOF.
130398   */
130399   assert( pCsr->pNode );
130400
130401   if( pCsr->iStrategy==1 ){
130402     /* This "scan" is a direct lookup by rowid. There is no next entry. */
130403     nodeRelease(pRtree, pCsr->pNode);
130404     pCsr->pNode = 0;
130405   }else{
130406     /* Move to the next entry that matches the configured constraints. */
130407     int iHeight = 0;
130408     while( pCsr->pNode ){
130409       RtreeNode *pNode = pCsr->pNode;
130410       int nCell = NCELL(pNode);
130411       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
130412         int isEof;
130413         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
130414         if( rc!=SQLCIPHER_OK || !isEof ){
130415           return rc;
130416         }
130417       }
130418       pCsr->pNode = pNode->pParent;
130419       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
130420       if( rc!=SQLCIPHER_OK ){
130421         return rc;
130422       }
130423       nodeReference(pCsr->pNode);
130424       nodeRelease(pRtree, pNode);
130425       iHeight++;
130426     }
130427   }
130428
130429   return rc;
130430 }
130431
130432 /* 
130433 ** Rtree virtual table module xRowid method.
130434 */
130435 static int rtreeRowid(sqlcipher3_vtab_cursor *pVtabCursor, sqlcipher_int64 *pRowid){
130436   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
130437   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
130438
130439   assert(pCsr->pNode);
130440   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
130441
130442   return SQLCIPHER_OK;
130443 }
130444
130445 /* 
130446 ** Rtree virtual table module xColumn method.
130447 */
130448 static int rtreeColumn(sqlcipher3_vtab_cursor *cur, sqlcipher3_context *ctx, int i){
130449   Rtree *pRtree = (Rtree *)cur->pVtab;
130450   RtreeCursor *pCsr = (RtreeCursor *)cur;
130451
130452   if( i==0 ){
130453     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
130454     sqlcipher3_result_int64(ctx, iRowid);
130455   }else{
130456     RtreeCoord c;
130457     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
130458     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
130459       sqlcipher3_result_double(ctx, c.f);
130460     }else{
130461       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
130462       sqlcipher3_result_int(ctx, c.i);
130463     }
130464   }
130465
130466   return SQLCIPHER_OK;
130467 }
130468
130469 /* 
130470 ** Use nodeAcquire() to obtain the leaf node containing the record with 
130471 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
130472 ** return SQLCIPHER_OK. If there is no such record in the table, set
130473 ** *ppLeaf to 0 and return SQLCIPHER_OK. If an error occurs, set *ppLeaf
130474 ** to zero and return an SQLite error code.
130475 */
130476 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
130477   int rc;
130478   *ppLeaf = 0;
130479   sqlcipher3_bind_int64(pRtree->pReadRowid, 1, iRowid);
130480   if( sqlcipher3_step(pRtree->pReadRowid)==SQLCIPHER_ROW ){
130481     i64 iNode = sqlcipher3_column_int64(pRtree->pReadRowid, 0);
130482     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
130483     sqlcipher3_reset(pRtree->pReadRowid);
130484   }else{
130485     rc = sqlcipher3_reset(pRtree->pReadRowid);
130486   }
130487   return rc;
130488 }
130489
130490 /*
130491 ** This function is called to configure the RtreeConstraint object passed
130492 ** as the second argument for a MATCH constraint. The value passed as the
130493 ** first argument to this function is the right-hand operand to the MATCH
130494 ** operator.
130495 */
130496 static int deserializeGeometry(sqlcipher3_value *pValue, RtreeConstraint *pCons){
130497   RtreeMatchArg *p;
130498   sqlcipher3_rtree_geometry *pGeom;
130499   int nBlob;
130500
130501   /* Check that value is actually a blob. */
130502   if( !sqlcipher3_value_type(pValue)==SQLCIPHER_BLOB ) return SQLCIPHER_ERROR;
130503
130504   /* Check that the blob is roughly the right size. */
130505   nBlob = sqlcipher3_value_bytes(pValue);
130506   if( nBlob<(int)sizeof(RtreeMatchArg) 
130507    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
130508   ){
130509     return SQLCIPHER_ERROR;
130510   }
130511
130512   pGeom = (sqlcipher3_rtree_geometry *)sqlcipher3_malloc(
130513       sizeof(sqlcipher3_rtree_geometry) + nBlob
130514   );
130515   if( !pGeom ) return SQLCIPHER_NOMEM;
130516   memset(pGeom, 0, sizeof(sqlcipher3_rtree_geometry));
130517   p = (RtreeMatchArg *)&pGeom[1];
130518
130519   memcpy(p, sqlcipher3_value_blob(pValue), nBlob);
130520   if( p->magic!=RTREE_GEOMETRY_MAGIC 
130521    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
130522   ){
130523     sqlcipher3_free(pGeom);
130524     return SQLCIPHER_ERROR;
130525   }
130526
130527   pGeom->pContext = p->pContext;
130528   pGeom->nParam = p->nParam;
130529   pGeom->aParam = p->aParam;
130530
130531   pCons->xGeom = p->xGeom;
130532   pCons->pGeom = pGeom;
130533   return SQLCIPHER_OK;
130534 }
130535
130536 /* 
130537 ** Rtree virtual table module xFilter method.
130538 */
130539 static int rtreeFilter(
130540   sqlcipher3_vtab_cursor *pVtabCursor, 
130541   int idxNum, const char *idxStr,
130542   int argc, sqlcipher3_value **argv
130543 ){
130544   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
130545   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
130546
130547   RtreeNode *pRoot = 0;
130548   int ii;
130549   int rc = SQLCIPHER_OK;
130550
130551   rtreeReference(pRtree);
130552
130553   freeCursorConstraints(pCsr);
130554   pCsr->iStrategy = idxNum;
130555
130556   if( idxNum==1 ){
130557     /* Special case - lookup by rowid. */
130558     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
130559     i64 iRowid = sqlcipher3_value_int64(argv[0]);
130560     rc = findLeafNode(pRtree, iRowid, &pLeaf);
130561     pCsr->pNode = pLeaf; 
130562     if( pLeaf ){
130563       assert( rc==SQLCIPHER_OK );
130564       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
130565     }
130566   }else{
130567     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
130568     ** with the configured constraints. 
130569     */
130570     if( argc>0 ){
130571       pCsr->aConstraint = sqlcipher3_malloc(sizeof(RtreeConstraint)*argc);
130572       pCsr->nConstraint = argc;
130573       if( !pCsr->aConstraint ){
130574         rc = SQLCIPHER_NOMEM;
130575       }else{
130576         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
130577         assert( (idxStr==0 && argc==0)
130578                 || (idxStr && (int)strlen(idxStr)==argc*2) );
130579         for(ii=0; ii<argc; ii++){
130580           RtreeConstraint *p = &pCsr->aConstraint[ii];
130581           p->op = idxStr[ii*2];
130582           p->iCoord = idxStr[ii*2+1]-'a';
130583           if( p->op==RTREE_MATCH ){
130584             /* A MATCH operator. The right-hand-side must be a blob that
130585             ** can be cast into an RtreeMatchArg object. One created using
130586             ** an sqlcipher3_rtree_geometry_callback() SQL user function.
130587             */
130588             rc = deserializeGeometry(argv[ii], p);
130589             if( rc!=SQLCIPHER_OK ){
130590               break;
130591             }
130592           }else{
130593             p->rValue = sqlcipher3_value_double(argv[ii]);
130594           }
130595         }
130596       }
130597     }
130598   
130599     if( rc==SQLCIPHER_OK ){
130600       pCsr->pNode = 0;
130601       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
130602     }
130603     if( rc==SQLCIPHER_OK ){
130604       int isEof = 1;
130605       int nCell = NCELL(pRoot);
130606       pCsr->pNode = pRoot;
130607       for(pCsr->iCell=0; rc==SQLCIPHER_OK && pCsr->iCell<nCell; pCsr->iCell++){
130608         assert( pCsr->pNode==pRoot );
130609         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
130610         if( !isEof ){
130611           break;
130612         }
130613       }
130614       if( rc==SQLCIPHER_OK && isEof ){
130615         assert( pCsr->pNode==pRoot );
130616         nodeRelease(pRtree, pRoot);
130617         pCsr->pNode = 0;
130618       }
130619       assert( rc!=SQLCIPHER_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
130620     }
130621   }
130622
130623   rtreeRelease(pRtree);
130624   return rc;
130625 }
130626
130627 /*
130628 ** Rtree virtual table module xBestIndex method. There are three
130629 ** table scan strategies to choose from (in order from most to 
130630 ** least desirable):
130631 **
130632 **   idxNum     idxStr        Strategy
130633 **   ------------------------------------------------
130634 **     1        Unused        Direct lookup by rowid.
130635 **     2        See below     R-tree query or full-table scan.
130636 **   ------------------------------------------------
130637 **
130638 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
130639 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
130640 ** constraint used. The first two bytes of idxStr correspond to 
130641 ** the constraint in sqlcipher3_index_info.aConstraintUsage[] with
130642 ** (argvIndex==1) etc.
130643 **
130644 ** The first of each pair of bytes in idxStr identifies the constraint
130645 ** operator as follows:
130646 **
130647 **   Operator    Byte Value
130648 **   ----------------------
130649 **      =        0x41 ('A')
130650 **     <=        0x42 ('B')
130651 **      <        0x43 ('C')
130652 **     >=        0x44 ('D')
130653 **      >        0x45 ('E')
130654 **   MATCH       0x46 ('F')
130655 **   ----------------------
130656 **
130657 ** The second of each pair of bytes identifies the coordinate column
130658 ** to which the constraint applies. The leftmost coordinate column
130659 ** is 'a', the second from the left 'b' etc.
130660 */
130661 static int rtreeBestIndex(sqlcipher3_vtab *tab, sqlcipher3_index_info *pIdxInfo){
130662   int rc = SQLCIPHER_OK;
130663   int ii;
130664
130665   int iIdx = 0;
130666   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
130667   memset(zIdxStr, 0, sizeof(zIdxStr));
130668   UNUSED_PARAMETER(tab);
130669
130670   assert( pIdxInfo->idxStr==0 );
130671   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
130672     struct sqlcipher3_index_constraint *p = &pIdxInfo->aConstraint[ii];
130673
130674     if( p->usable && p->iColumn==0 && p->op==SQLCIPHER_INDEX_CONSTRAINT_EQ ){
130675       /* We have an equality constraint on the rowid. Use strategy 1. */
130676       int jj;
130677       for(jj=0; jj<ii; jj++){
130678         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
130679         pIdxInfo->aConstraintUsage[jj].omit = 0;
130680       }
130681       pIdxInfo->idxNum = 1;
130682       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
130683       pIdxInfo->aConstraintUsage[jj].omit = 1;
130684
130685       /* This strategy involves a two rowid lookups on an B-Tree structures
130686       ** and then a linear search of an R-Tree node. This should be 
130687       ** considered almost as quick as a direct rowid lookup (for which 
130688       ** sqlcipher uses an internal cost of 0.0).
130689       */ 
130690       pIdxInfo->estimatedCost = 10.0;
130691       return SQLCIPHER_OK;
130692     }
130693
130694     if( p->usable && (p->iColumn>0 || p->op==SQLCIPHER_INDEX_CONSTRAINT_MATCH) ){
130695       u8 op;
130696       switch( p->op ){
130697         case SQLCIPHER_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
130698         case SQLCIPHER_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
130699         case SQLCIPHER_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
130700         case SQLCIPHER_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
130701         case SQLCIPHER_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
130702         default:
130703           assert( p->op==SQLCIPHER_INDEX_CONSTRAINT_MATCH );
130704           op = RTREE_MATCH; 
130705           break;
130706       }
130707       zIdxStr[iIdx++] = op;
130708       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
130709       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
130710       pIdxInfo->aConstraintUsage[ii].omit = 1;
130711     }
130712   }
130713
130714   pIdxInfo->idxNum = 2;
130715   pIdxInfo->needToFreeIdxStr = 1;
130716   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlcipher3_mprintf("%s", zIdxStr)) ){
130717     return SQLCIPHER_NOMEM;
130718   }
130719   assert( iIdx>=0 );
130720   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
130721   return rc;
130722 }
130723
130724 /*
130725 ** Return the N-dimensional volumn of the cell stored in *p.
130726 */
130727 static float cellArea(Rtree *pRtree, RtreeCell *p){
130728   float area = 1.0;
130729   int ii;
130730   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130731     area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
130732   }
130733   return area;
130734 }
130735
130736 /*
130737 ** Return the margin length of cell p. The margin length is the sum
130738 ** of the objects size in each dimension.
130739 */
130740 static float cellMargin(Rtree *pRtree, RtreeCell *p){
130741   float margin = 0.0;
130742   int ii;
130743   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130744     margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
130745   }
130746   return margin;
130747 }
130748
130749 /*
130750 ** Store the union of cells p1 and p2 in p1.
130751 */
130752 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
130753   int ii;
130754   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
130755     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130756       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
130757       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
130758     }
130759   }else{
130760     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130761       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
130762       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
130763     }
130764   }
130765 }
130766
130767 /*
130768 ** Return true if the area covered by p2 is a subset of the area covered
130769 ** by p1. False otherwise.
130770 */
130771 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
130772   int ii;
130773   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
130774   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130775     RtreeCoord *a1 = &p1->aCoord[ii];
130776     RtreeCoord *a2 = &p2->aCoord[ii];
130777     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
130778      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
130779     ){
130780       return 0;
130781     }
130782   }
130783   return 1;
130784 }
130785
130786 /*
130787 ** Return the amount cell p would grow by if it were unioned with pCell.
130788 */
130789 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
130790   float area;
130791   RtreeCell cell;
130792   memcpy(&cell, p, sizeof(RtreeCell));
130793   area = cellArea(pRtree, &cell);
130794   cellUnion(pRtree, &cell, pCell);
130795   return (cellArea(pRtree, &cell)-area);
130796 }
130797
130798 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
130799 static float cellOverlap(
130800   Rtree *pRtree, 
130801   RtreeCell *p, 
130802   RtreeCell *aCell, 
130803   int nCell, 
130804   int iExclude
130805 ){
130806   int ii;
130807   float overlap = 0.0;
130808   for(ii=0; ii<nCell; ii++){
130809 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130810     if( ii!=iExclude )
130811 #else
130812     assert( iExclude==-1 );
130813     UNUSED_PARAMETER(iExclude);
130814 #endif
130815     {
130816       int jj;
130817       float o = 1.0;
130818       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
130819         double x1;
130820         double x2;
130821
130822         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
130823         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
130824
130825         if( x2<x1 ){
130826           o = 0.0;
130827           break;
130828         }else{
130829           o = o * (float)(x2-x1);
130830         }
130831       }
130832       overlap += o;
130833     }
130834   }
130835   return overlap;
130836 }
130837 #endif
130838
130839 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130840 static float cellOverlapEnlargement(
130841   Rtree *pRtree, 
130842   RtreeCell *p, 
130843   RtreeCell *pInsert, 
130844   RtreeCell *aCell, 
130845   int nCell, 
130846   int iExclude
130847 ){
130848   double before;
130849   double after;
130850   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
130851   cellUnion(pRtree, p, pInsert);
130852   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
130853   return (float)(after-before);
130854 }
130855 #endif
130856
130857
130858 /*
130859 ** This function implements the ChooseLeaf algorithm from Gutman[84].
130860 ** ChooseSubTree in r*tree terminology.
130861 */
130862 static int ChooseLeaf(
130863   Rtree *pRtree,               /* Rtree table */
130864   RtreeCell *pCell,            /* Cell to insert into rtree */
130865   int iHeight,                 /* Height of sub-tree rooted at pCell */
130866   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
130867 ){
130868   int rc;
130869   int ii;
130870   RtreeNode *pNode;
130871   rc = nodeAcquire(pRtree, 1, 0, &pNode);
130872
130873   for(ii=0; rc==SQLCIPHER_OK && ii<(pRtree->iDepth-iHeight); ii++){
130874     int iCell;
130875     sqlcipher3_int64 iBest = 0;
130876
130877     float fMinGrowth = 0.0;
130878     float fMinArea = 0.0;
130879 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130880     float fMinOverlap = 0.0;
130881     float overlap;
130882 #endif
130883
130884     int nCell = NCELL(pNode);
130885     RtreeCell cell;
130886     RtreeNode *pChild;
130887
130888     RtreeCell *aCell = 0;
130889
130890 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130891     if( ii==(pRtree->iDepth-1) ){
130892       int jj;
130893       aCell = sqlcipher3_malloc(sizeof(RtreeCell)*nCell);
130894       if( !aCell ){
130895         rc = SQLCIPHER_NOMEM;
130896         nodeRelease(pRtree, pNode);
130897         pNode = 0;
130898         continue;
130899       }
130900       for(jj=0; jj<nCell; jj++){
130901         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
130902       }
130903     }
130904 #endif
130905
130906     /* Select the child node which will be enlarged the least if pCell
130907     ** is inserted into it. Resolve ties by choosing the entry with
130908     ** the smallest area.
130909     */
130910     for(iCell=0; iCell<nCell; iCell++){
130911       int bBest = 0;
130912       float growth;
130913       float area;
130914       nodeGetCell(pRtree, pNode, iCell, &cell);
130915       growth = cellGrowth(pRtree, &cell, pCell);
130916       area = cellArea(pRtree, &cell);
130917
130918 #if VARIANT_RSTARTREE_CHOOSESUBTREE
130919       if( ii==(pRtree->iDepth-1) ){
130920         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
130921       }else{
130922         overlap = 0.0;
130923       }
130924       if( (iCell==0) 
130925        || (overlap<fMinOverlap) 
130926        || (overlap==fMinOverlap && growth<fMinGrowth)
130927        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
130928       ){
130929         bBest = 1;
130930         fMinOverlap = overlap;
130931       }
130932 #else
130933       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
130934         bBest = 1;
130935       }
130936 #endif
130937       if( bBest ){
130938         fMinGrowth = growth;
130939         fMinArea = area;
130940         iBest = cell.iRowid;
130941       }
130942     }
130943
130944     sqlcipher3_free(aCell);
130945     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
130946     nodeRelease(pRtree, pNode);
130947     pNode = pChild;
130948   }
130949
130950   *ppLeaf = pNode;
130951   return rc;
130952 }
130953
130954 /*
130955 ** A cell with the same content as pCell has just been inserted into
130956 ** the node pNode. This function updates the bounding box cells in
130957 ** all ancestor elements.
130958 */
130959 static int AdjustTree(
130960   Rtree *pRtree,                    /* Rtree table */
130961   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
130962   RtreeCell *pCell                  /* This cell was just inserted */
130963 ){
130964   RtreeNode *p = pNode;
130965   while( p->pParent ){
130966     RtreeNode *pParent = p->pParent;
130967     RtreeCell cell;
130968     int iCell;
130969
130970     if( nodeParentIndex(pRtree, p, &iCell) ){
130971       return SQLCIPHER_CORRUPT_VTAB;
130972     }
130973
130974     nodeGetCell(pRtree, pParent, iCell, &cell);
130975     if( !cellContains(pRtree, &cell, pCell) ){
130976       cellUnion(pRtree, &cell, pCell);
130977       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
130978     }
130979  
130980     p = pParent;
130981   }
130982   return SQLCIPHER_OK;
130983 }
130984
130985 /*
130986 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
130987 */
130988 static int rowidWrite(Rtree *pRtree, sqlcipher3_int64 iRowid, sqlcipher3_int64 iNode){
130989   sqlcipher3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
130990   sqlcipher3_bind_int64(pRtree->pWriteRowid, 2, iNode);
130991   sqlcipher3_step(pRtree->pWriteRowid);
130992   return sqlcipher3_reset(pRtree->pWriteRowid);
130993 }
130994
130995 /*
130996 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
130997 */
130998 static int parentWrite(Rtree *pRtree, sqlcipher3_int64 iNode, sqlcipher3_int64 iPar){
130999   sqlcipher3_bind_int64(pRtree->pWriteParent, 1, iNode);
131000   sqlcipher3_bind_int64(pRtree->pWriteParent, 2, iPar);
131001   sqlcipher3_step(pRtree->pWriteParent);
131002   return sqlcipher3_reset(pRtree->pWriteParent);
131003 }
131004
131005 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
131006
131007 #if VARIANT_GUTTMAN_LINEAR_SPLIT
131008 /*
131009 ** Implementation of the linear variant of the PickNext() function from
131010 ** Guttman[84].
131011 */
131012 static RtreeCell *LinearPickNext(
131013   Rtree *pRtree,
131014   RtreeCell *aCell, 
131015   int nCell, 
131016   RtreeCell *pLeftBox, 
131017   RtreeCell *pRightBox,
131018   int *aiUsed
131019 ){
131020   int ii;
131021   for(ii=0; aiUsed[ii]; ii++);
131022   aiUsed[ii] = 1;
131023   return &aCell[ii];
131024 }
131025
131026 /*
131027 ** Implementation of the linear variant of the PickSeeds() function from
131028 ** Guttman[84].
131029 */
131030 static void LinearPickSeeds(
131031   Rtree *pRtree,
131032   RtreeCell *aCell, 
131033   int nCell, 
131034   int *piLeftSeed, 
131035   int *piRightSeed
131036 ){
131037   int i;
131038   int iLeftSeed = 0;
131039   int iRightSeed = 1;
131040   float maxNormalInnerWidth = 0.0;
131041
131042   /* Pick two "seed" cells from the array of cells. The algorithm used
131043   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
131044   ** indices of the two seed cells in the array are stored in local
131045   ** variables iLeftSeek and iRightSeed.
131046   */
131047   for(i=0; i<pRtree->nDim; i++){
131048     float x1 = DCOORD(aCell[0].aCoord[i*2]);
131049     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
131050     float x3 = x1;
131051     float x4 = x2;
131052     int jj;
131053
131054     int iCellLeft = 0;
131055     int iCellRight = 0;
131056
131057     for(jj=1; jj<nCell; jj++){
131058       float left = DCOORD(aCell[jj].aCoord[i*2]);
131059       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
131060
131061       if( left<x1 ) x1 = left;
131062       if( right>x4 ) x4 = right;
131063       if( left>x3 ){
131064         x3 = left;
131065         iCellRight = jj;
131066       }
131067       if( right<x2 ){
131068         x2 = right;
131069         iCellLeft = jj;
131070       }
131071     }
131072
131073     if( x4!=x1 ){
131074       float normalwidth = (x3 - x2) / (x4 - x1);
131075       if( normalwidth>maxNormalInnerWidth ){
131076         iLeftSeed = iCellLeft;
131077         iRightSeed = iCellRight;
131078       }
131079     }
131080   }
131081
131082   *piLeftSeed = iLeftSeed;
131083   *piRightSeed = iRightSeed;
131084 }
131085 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
131086
131087 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
131088 /*
131089 ** Implementation of the quadratic variant of the PickNext() function from
131090 ** Guttman[84].
131091 */
131092 static RtreeCell *QuadraticPickNext(
131093   Rtree *pRtree,
131094   RtreeCell *aCell, 
131095   int nCell, 
131096   RtreeCell *pLeftBox, 
131097   RtreeCell *pRightBox,
131098   int *aiUsed
131099 ){
131100   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
131101
131102   int iSelect = -1;
131103   float fDiff;
131104   int ii;
131105   for(ii=0; ii<nCell; ii++){
131106     if( aiUsed[ii]==0 ){
131107       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131108       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131109       float diff = FABS(right-left);
131110       if( iSelect<0 || diff>fDiff ){
131111         fDiff = diff;
131112         iSelect = ii;
131113       }
131114     }
131115   }
131116   aiUsed[iSelect] = 1;
131117   return &aCell[iSelect];
131118 }
131119
131120 /*
131121 ** Implementation of the quadratic variant of the PickSeeds() function from
131122 ** Guttman[84].
131123 */
131124 static void QuadraticPickSeeds(
131125   Rtree *pRtree,
131126   RtreeCell *aCell, 
131127   int nCell, 
131128   int *piLeftSeed, 
131129   int *piRightSeed
131130 ){
131131   int ii;
131132   int jj;
131133
131134   int iLeftSeed = 0;
131135   int iRightSeed = 1;
131136   float fWaste = 0.0;
131137
131138   for(ii=0; ii<nCell; ii++){
131139     for(jj=ii+1; jj<nCell; jj++){
131140       float right = cellArea(pRtree, &aCell[jj]);
131141       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
131142       float waste = growth - right;
131143
131144       if( waste>fWaste ){
131145         iLeftSeed = ii;
131146         iRightSeed = jj;
131147         fWaste = waste;
131148       }
131149     }
131150   }
131151
131152   *piLeftSeed = iLeftSeed;
131153   *piRightSeed = iRightSeed;
131154 }
131155 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
131156
131157 /*
131158 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
131159 ** nIdx. The aIdx array contains the set of integers from 0 to 
131160 ** (nIdx-1) in no particular order. This function sorts the values
131161 ** in aIdx according to the indexed values in aDistance. For
131162 ** example, assuming the inputs:
131163 **
131164 **   aIdx      = { 0,   1,   2,   3 }
131165 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
131166 **
131167 ** this function sets the aIdx array to contain:
131168 **
131169 **   aIdx      = { 0,   1,   2,   3 }
131170 **
131171 ** The aSpare array is used as temporary working space by the
131172 ** sorting algorithm.
131173 */
131174 static void SortByDistance(
131175   int *aIdx, 
131176   int nIdx, 
131177   float *aDistance, 
131178   int *aSpare
131179 ){
131180   if( nIdx>1 ){
131181     int iLeft = 0;
131182     int iRight = 0;
131183
131184     int nLeft = nIdx/2;
131185     int nRight = nIdx-nLeft;
131186     int *aLeft = aIdx;
131187     int *aRight = &aIdx[nLeft];
131188
131189     SortByDistance(aLeft, nLeft, aDistance, aSpare);
131190     SortByDistance(aRight, nRight, aDistance, aSpare);
131191
131192     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
131193     aLeft = aSpare;
131194
131195     while( iLeft<nLeft || iRight<nRight ){
131196       if( iLeft==nLeft ){
131197         aIdx[iLeft+iRight] = aRight[iRight];
131198         iRight++;
131199       }else if( iRight==nRight ){
131200         aIdx[iLeft+iRight] = aLeft[iLeft];
131201         iLeft++;
131202       }else{
131203         float fLeft = aDistance[aLeft[iLeft]];
131204         float fRight = aDistance[aRight[iRight]];
131205         if( fLeft<fRight ){
131206           aIdx[iLeft+iRight] = aLeft[iLeft];
131207           iLeft++;
131208         }else{
131209           aIdx[iLeft+iRight] = aRight[iRight];
131210           iRight++;
131211         }
131212       }
131213     }
131214
131215 #if 0
131216     /* Check that the sort worked */
131217     {
131218       int jj;
131219       for(jj=1; jj<nIdx; jj++){
131220         float left = aDistance[aIdx[jj-1]];
131221         float right = aDistance[aIdx[jj]];
131222         assert( left<=right );
131223       }
131224     }
131225 #endif
131226   }
131227 }
131228
131229 /*
131230 ** Arguments aIdx, aCell and aSpare all point to arrays of size
131231 ** nIdx. The aIdx array contains the set of integers from 0 to 
131232 ** (nIdx-1) in no particular order. This function sorts the values
131233 ** in aIdx according to dimension iDim of the cells in aCell. The
131234 ** minimum value of dimension iDim is considered first, the
131235 ** maximum used to break ties.
131236 **
131237 ** The aSpare array is used as temporary working space by the
131238 ** sorting algorithm.
131239 */
131240 static void SortByDimension(
131241   Rtree *pRtree,
131242   int *aIdx, 
131243   int nIdx, 
131244   int iDim, 
131245   RtreeCell *aCell, 
131246   int *aSpare
131247 ){
131248   if( nIdx>1 ){
131249
131250     int iLeft = 0;
131251     int iRight = 0;
131252
131253     int nLeft = nIdx/2;
131254     int nRight = nIdx-nLeft;
131255     int *aLeft = aIdx;
131256     int *aRight = &aIdx[nLeft];
131257
131258     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
131259     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
131260
131261     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
131262     aLeft = aSpare;
131263     while( iLeft<nLeft || iRight<nRight ){
131264       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
131265       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
131266       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
131267       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
131268       if( (iLeft!=nLeft) && ((iRight==nRight)
131269        || (xleft1<xright1)
131270        || (xleft1==xright1 && xleft2<xright2)
131271       )){
131272         aIdx[iLeft+iRight] = aLeft[iLeft];
131273         iLeft++;
131274       }else{
131275         aIdx[iLeft+iRight] = aRight[iRight];
131276         iRight++;
131277       }
131278     }
131279
131280 #if 0
131281     /* Check that the sort worked */
131282     {
131283       int jj;
131284       for(jj=1; jj<nIdx; jj++){
131285         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
131286         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
131287         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
131288         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
131289         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
131290       }
131291     }
131292 #endif
131293   }
131294 }
131295
131296 #if VARIANT_RSTARTREE_SPLIT
131297 /*
131298 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
131299 */
131300 static int splitNodeStartree(
131301   Rtree *pRtree,
131302   RtreeCell *aCell,
131303   int nCell,
131304   RtreeNode *pLeft,
131305   RtreeNode *pRight,
131306   RtreeCell *pBboxLeft,
131307   RtreeCell *pBboxRight
131308 ){
131309   int **aaSorted;
131310   int *aSpare;
131311   int ii;
131312
131313   int iBestDim = 0;
131314   int iBestSplit = 0;
131315   float fBestMargin = 0.0;
131316
131317   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
131318
131319   aaSorted = (int **)sqlcipher3_malloc(nByte);
131320   if( !aaSorted ){
131321     return SQLCIPHER_NOMEM;
131322   }
131323
131324   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
131325   memset(aaSorted, 0, nByte);
131326   for(ii=0; ii<pRtree->nDim; ii++){
131327     int jj;
131328     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
131329     for(jj=0; jj<nCell; jj++){
131330       aaSorted[ii][jj] = jj;
131331     }
131332     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
131333   }
131334
131335   for(ii=0; ii<pRtree->nDim; ii++){
131336     float margin = 0.0;
131337     float fBestOverlap = 0.0;
131338     float fBestArea = 0.0;
131339     int iBestLeft = 0;
131340     int nLeft;
131341
131342     for(
131343       nLeft=RTREE_MINCELLS(pRtree); 
131344       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
131345       nLeft++
131346     ){
131347       RtreeCell left;
131348       RtreeCell right;
131349       int kk;
131350       float overlap;
131351       float area;
131352
131353       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
131354       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
131355       for(kk=1; kk<(nCell-1); kk++){
131356         if( kk<nLeft ){
131357           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
131358         }else{
131359           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
131360         }
131361       }
131362       margin += cellMargin(pRtree, &left);
131363       margin += cellMargin(pRtree, &right);
131364       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
131365       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
131366       if( (nLeft==RTREE_MINCELLS(pRtree))
131367        || (overlap<fBestOverlap)
131368        || (overlap==fBestOverlap && area<fBestArea)
131369       ){
131370         iBestLeft = nLeft;
131371         fBestOverlap = overlap;
131372         fBestArea = area;
131373       }
131374     }
131375
131376     if( ii==0 || margin<fBestMargin ){
131377       iBestDim = ii;
131378       fBestMargin = margin;
131379       iBestSplit = iBestLeft;
131380     }
131381   }
131382
131383   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
131384   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
131385   for(ii=0; ii<nCell; ii++){
131386     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
131387     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
131388     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
131389     nodeInsertCell(pRtree, pTarget, pCell);
131390     cellUnion(pRtree, pBbox, pCell);
131391   }
131392
131393   sqlcipher3_free(aaSorted);
131394   return SQLCIPHER_OK;
131395 }
131396 #endif
131397
131398 #if VARIANT_GUTTMAN_SPLIT
131399 /*
131400 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
131401 */
131402 static int splitNodeGuttman(
131403   Rtree *pRtree,
131404   RtreeCell *aCell,
131405   int nCell,
131406   RtreeNode *pLeft,
131407   RtreeNode *pRight,
131408   RtreeCell *pBboxLeft,
131409   RtreeCell *pBboxRight
131410 ){
131411   int iLeftSeed = 0;
131412   int iRightSeed = 1;
131413   int *aiUsed;
131414   int i;
131415
131416   aiUsed = sqlcipher3_malloc(sizeof(int)*nCell);
131417   if( !aiUsed ){
131418     return SQLCIPHER_NOMEM;
131419   }
131420   memset(aiUsed, 0, sizeof(int)*nCell);
131421
131422   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
131423
131424   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
131425   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
131426   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
131427   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
131428   aiUsed[iLeftSeed] = 1;
131429   aiUsed[iRightSeed] = 1;
131430
131431   for(i=nCell-2; i>0; i--){
131432     RtreeCell *pNext;
131433     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
131434     float diff =  
131435       cellGrowth(pRtree, pBboxLeft, pNext) - 
131436       cellGrowth(pRtree, pBboxRight, pNext)
131437     ;
131438     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
131439      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
131440     ){
131441       nodeInsertCell(pRtree, pRight, pNext);
131442       cellUnion(pRtree, pBboxRight, pNext);
131443     }else{
131444       nodeInsertCell(pRtree, pLeft, pNext);
131445       cellUnion(pRtree, pBboxLeft, pNext);
131446     }
131447   }
131448
131449   sqlcipher3_free(aiUsed);
131450   return SQLCIPHER_OK;
131451 }
131452 #endif
131453
131454 static int updateMapping(
131455   Rtree *pRtree, 
131456   i64 iRowid, 
131457   RtreeNode *pNode, 
131458   int iHeight
131459 ){
131460   int (*xSetMapping)(Rtree *, sqlcipher3_int64, sqlcipher3_int64);
131461   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
131462   if( iHeight>0 ){
131463     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
131464     if( pChild ){
131465       nodeRelease(pRtree, pChild->pParent);
131466       nodeReference(pNode);
131467       pChild->pParent = pNode;
131468     }
131469   }
131470   return xSetMapping(pRtree, iRowid, pNode->iNode);
131471 }
131472
131473 static int SplitNode(
131474   Rtree *pRtree,
131475   RtreeNode *pNode,
131476   RtreeCell *pCell,
131477   int iHeight
131478 ){
131479   int i;
131480   int newCellIsRight = 0;
131481
131482   int rc = SQLCIPHER_OK;
131483   int nCell = NCELL(pNode);
131484   RtreeCell *aCell;
131485   int *aiUsed;
131486
131487   RtreeNode *pLeft = 0;
131488   RtreeNode *pRight = 0;
131489
131490   RtreeCell leftbbox;
131491   RtreeCell rightbbox;
131492
131493   /* Allocate an array and populate it with a copy of pCell and 
131494   ** all cells from node pLeft. Then zero the original node.
131495   */
131496   aCell = sqlcipher3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
131497   if( !aCell ){
131498     rc = SQLCIPHER_NOMEM;
131499     goto splitnode_out;
131500   }
131501   aiUsed = (int *)&aCell[nCell+1];
131502   memset(aiUsed, 0, sizeof(int)*(nCell+1));
131503   for(i=0; i<nCell; i++){
131504     nodeGetCell(pRtree, pNode, i, &aCell[i]);
131505   }
131506   nodeZero(pRtree, pNode);
131507   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
131508   nCell++;
131509
131510   if( pNode->iNode==1 ){
131511     pRight = nodeNew(pRtree, pNode);
131512     pLeft = nodeNew(pRtree, pNode);
131513     pRtree->iDepth++;
131514     pNode->isDirty = 1;
131515     writeInt16(pNode->zData, pRtree->iDepth);
131516   }else{
131517     pLeft = pNode;
131518     pRight = nodeNew(pRtree, pLeft->pParent);
131519     nodeReference(pLeft);
131520   }
131521
131522   if( !pLeft || !pRight ){
131523     rc = SQLCIPHER_NOMEM;
131524     goto splitnode_out;
131525   }
131526
131527   memset(pLeft->zData, 0, pRtree->iNodeSize);
131528   memset(pRight->zData, 0, pRtree->iNodeSize);
131529
131530   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
131531   if( rc!=SQLCIPHER_OK ){
131532     goto splitnode_out;
131533   }
131534
131535   /* Ensure both child nodes have node numbers assigned to them by calling
131536   ** nodeWrite(). Node pRight always needs a node number, as it was created
131537   ** by nodeNew() above. But node pLeft sometimes already has a node number.
131538   ** In this case avoid the all to nodeWrite().
131539   */
131540   if( SQLCIPHER_OK!=(rc = nodeWrite(pRtree, pRight))
131541    || (0==pLeft->iNode && SQLCIPHER_OK!=(rc = nodeWrite(pRtree, pLeft)))
131542   ){
131543     goto splitnode_out;
131544   }
131545
131546   rightbbox.iRowid = pRight->iNode;
131547   leftbbox.iRowid = pLeft->iNode;
131548
131549   if( pNode->iNode==1 ){
131550     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
131551     if( rc!=SQLCIPHER_OK ){
131552       goto splitnode_out;
131553     }
131554   }else{
131555     RtreeNode *pParent = pLeft->pParent;
131556     int iCell;
131557     rc = nodeParentIndex(pRtree, pLeft, &iCell);
131558     if( rc==SQLCIPHER_OK ){
131559       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
131560       rc = AdjustTree(pRtree, pParent, &leftbbox);
131561     }
131562     if( rc!=SQLCIPHER_OK ){
131563       goto splitnode_out;
131564     }
131565   }
131566   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
131567     goto splitnode_out;
131568   }
131569
131570   for(i=0; i<NCELL(pRight); i++){
131571     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
131572     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
131573     if( iRowid==pCell->iRowid ){
131574       newCellIsRight = 1;
131575     }
131576     if( rc!=SQLCIPHER_OK ){
131577       goto splitnode_out;
131578     }
131579   }
131580   if( pNode->iNode==1 ){
131581     for(i=0; i<NCELL(pLeft); i++){
131582       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
131583       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
131584       if( rc!=SQLCIPHER_OK ){
131585         goto splitnode_out;
131586       }
131587     }
131588   }else if( newCellIsRight==0 ){
131589     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
131590   }
131591
131592   if( rc==SQLCIPHER_OK ){
131593     rc = nodeRelease(pRtree, pRight);
131594     pRight = 0;
131595   }
131596   if( rc==SQLCIPHER_OK ){
131597     rc = nodeRelease(pRtree, pLeft);
131598     pLeft = 0;
131599   }
131600
131601 splitnode_out:
131602   nodeRelease(pRtree, pRight);
131603   nodeRelease(pRtree, pLeft);
131604   sqlcipher3_free(aCell);
131605   return rc;
131606 }
131607
131608 /*
131609 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
131610 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
131611 ** the pLeaf->pParent chain all the way up to the root node.
131612 **
131613 ** This operation is required when a row is deleted (or updated - an update
131614 ** is implemented as a delete followed by an insert). SQLite provides the
131615 ** rowid of the row to delete, which can be used to find the leaf on which
131616 ** the entry resides (argument pLeaf). Once the leaf is located, this 
131617 ** function is called to determine its ancestry.
131618 */
131619 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
131620   int rc = SQLCIPHER_OK;
131621   RtreeNode *pChild = pLeaf;
131622   while( rc==SQLCIPHER_OK && pChild->iNode!=1 && pChild->pParent==0 ){
131623     int rc2 = SQLCIPHER_OK;          /* sqlcipher3_reset() return code */
131624     sqlcipher3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
131625     rc = sqlcipher3_step(pRtree->pReadParent);
131626     if( rc==SQLCIPHER_ROW ){
131627       RtreeNode *pTest;           /* Used to test for reference loops */
131628       i64 iNode;                  /* Node number of parent node */
131629
131630       /* Before setting pChild->pParent, test that we are not creating a
131631       ** loop of references (as we would if, say, pChild==pParent). We don't
131632       ** want to do this as it leads to a memory leak when trying to delete
131633       ** the referenced counted node structures.
131634       */
131635       iNode = sqlcipher3_column_int64(pRtree->pReadParent, 0);
131636       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
131637       if( !pTest ){
131638         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
131639       }
131640     }
131641     rc = sqlcipher3_reset(pRtree->pReadParent);
131642     if( rc==SQLCIPHER_OK ) rc = rc2;
131643     if( rc==SQLCIPHER_OK && !pChild->pParent ) rc = SQLCIPHER_CORRUPT_VTAB;
131644     pChild = pChild->pParent;
131645   }
131646   return rc;
131647 }
131648
131649 static int deleteCell(Rtree *, RtreeNode *, int, int);
131650
131651 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
131652   int rc;
131653   int rc2;
131654   RtreeNode *pParent = 0;
131655   int iCell;
131656
131657   assert( pNode->nRef==1 );
131658
131659   /* Remove the entry in the parent cell. */
131660   rc = nodeParentIndex(pRtree, pNode, &iCell);
131661   if( rc==SQLCIPHER_OK ){
131662     pParent = pNode->pParent;
131663     pNode->pParent = 0;
131664     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
131665   }
131666   rc2 = nodeRelease(pRtree, pParent);
131667   if( rc==SQLCIPHER_OK ){
131668     rc = rc2;
131669   }
131670   if( rc!=SQLCIPHER_OK ){
131671     return rc;
131672   }
131673
131674   /* Remove the xxx_node entry. */
131675   sqlcipher3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
131676   sqlcipher3_step(pRtree->pDeleteNode);
131677   if( SQLCIPHER_OK!=(rc = sqlcipher3_reset(pRtree->pDeleteNode)) ){
131678     return rc;
131679   }
131680
131681   /* Remove the xxx_parent entry. */
131682   sqlcipher3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
131683   sqlcipher3_step(pRtree->pDeleteParent);
131684   if( SQLCIPHER_OK!=(rc = sqlcipher3_reset(pRtree->pDeleteParent)) ){
131685     return rc;
131686   }
131687   
131688   /* Remove the node from the in-memory hash table and link it into
131689   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
131690   */
131691   nodeHashDelete(pRtree, pNode);
131692   pNode->iNode = iHeight;
131693   pNode->pNext = pRtree->pDeleted;
131694   pNode->nRef++;
131695   pRtree->pDeleted = pNode;
131696
131697   return SQLCIPHER_OK;
131698 }
131699
131700 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
131701   RtreeNode *pParent = pNode->pParent;
131702   int rc = SQLCIPHER_OK; 
131703   if( pParent ){
131704     int ii; 
131705     int nCell = NCELL(pNode);
131706     RtreeCell box;                            /* Bounding box for pNode */
131707     nodeGetCell(pRtree, pNode, 0, &box);
131708     for(ii=1; ii<nCell; ii++){
131709       RtreeCell cell;
131710       nodeGetCell(pRtree, pNode, ii, &cell);
131711       cellUnion(pRtree, &box, &cell);
131712     }
131713     box.iRowid = pNode->iNode;
131714     rc = nodeParentIndex(pRtree, pNode, &ii);
131715     if( rc==SQLCIPHER_OK ){
131716       nodeOverwriteCell(pRtree, pParent, &box, ii);
131717       rc = fixBoundingBox(pRtree, pParent);
131718     }
131719   }
131720   return rc;
131721 }
131722
131723 /*
131724 ** Delete the cell at index iCell of node pNode. After removing the
131725 ** cell, adjust the r-tree data structure if required.
131726 */
131727 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
131728   RtreeNode *pParent;
131729   int rc;
131730
131731   if( SQLCIPHER_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
131732     return rc;
131733   }
131734
131735   /* Remove the cell from the node. This call just moves bytes around
131736   ** the in-memory node image, so it cannot fail.
131737   */
131738   nodeDeleteCell(pRtree, pNode, iCell);
131739
131740   /* If the node is not the tree root and now has less than the minimum
131741   ** number of cells, remove it from the tree. Otherwise, update the
131742   ** cell in the parent node so that it tightly contains the updated
131743   ** node.
131744   */
131745   pParent = pNode->pParent;
131746   assert( pParent || pNode->iNode==1 );
131747   if( pParent ){
131748     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
131749       rc = removeNode(pRtree, pNode, iHeight);
131750     }else{
131751       rc = fixBoundingBox(pRtree, pNode);
131752     }
131753   }
131754
131755   return rc;
131756 }
131757
131758 static int Reinsert(
131759   Rtree *pRtree, 
131760   RtreeNode *pNode, 
131761   RtreeCell *pCell, 
131762   int iHeight
131763 ){
131764   int *aOrder;
131765   int *aSpare;
131766   RtreeCell *aCell;
131767   float *aDistance;
131768   int nCell;
131769   float aCenterCoord[RTREE_MAX_DIMENSIONS];
131770   int iDim;
131771   int ii;
131772   int rc = SQLCIPHER_OK;
131773
131774   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
131775
131776   nCell = NCELL(pNode)+1;
131777
131778   /* Allocate the buffers used by this operation. The allocation is
131779   ** relinquished before this function returns.
131780   */
131781   aCell = (RtreeCell *)sqlcipher3_malloc(nCell * (
131782     sizeof(RtreeCell) +         /* aCell array */
131783     sizeof(int)       +         /* aOrder array */
131784     sizeof(int)       +         /* aSpare array */
131785     sizeof(float)               /* aDistance array */
131786   ));
131787   if( !aCell ){
131788     return SQLCIPHER_NOMEM;
131789   }
131790   aOrder    = (int *)&aCell[nCell];
131791   aSpare    = (int *)&aOrder[nCell];
131792   aDistance = (float *)&aSpare[nCell];
131793
131794   for(ii=0; ii<nCell; ii++){
131795     if( ii==(nCell-1) ){
131796       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
131797     }else{
131798       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
131799     }
131800     aOrder[ii] = ii;
131801     for(iDim=0; iDim<pRtree->nDim; iDim++){
131802       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
131803       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
131804     }
131805   }
131806   for(iDim=0; iDim<pRtree->nDim; iDim++){
131807     aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
131808   }
131809
131810   for(ii=0; ii<nCell; ii++){
131811     aDistance[ii] = 0.0;
131812     for(iDim=0; iDim<pRtree->nDim; iDim++){
131813       float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
131814           DCOORD(aCell[ii].aCoord[iDim*2]));
131815       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
131816     }
131817   }
131818
131819   SortByDistance(aOrder, nCell, aDistance, aSpare);
131820   nodeZero(pRtree, pNode);
131821
131822   for(ii=0; rc==SQLCIPHER_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
131823     RtreeCell *p = &aCell[aOrder[ii]];
131824     nodeInsertCell(pRtree, pNode, p);
131825     if( p->iRowid==pCell->iRowid ){
131826       if( iHeight==0 ){
131827         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
131828       }else{
131829         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
131830       }
131831     }
131832   }
131833   if( rc==SQLCIPHER_OK ){
131834     rc = fixBoundingBox(pRtree, pNode);
131835   }
131836   for(; rc==SQLCIPHER_OK && ii<nCell; ii++){
131837     /* Find a node to store this cell in. pNode->iNode currently contains
131838     ** the height of the sub-tree headed by the cell.
131839     */
131840     RtreeNode *pInsert;
131841     RtreeCell *p = &aCell[aOrder[ii]];
131842     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
131843     if( rc==SQLCIPHER_OK ){
131844       int rc2;
131845       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
131846       rc2 = nodeRelease(pRtree, pInsert);
131847       if( rc==SQLCIPHER_OK ){
131848         rc = rc2;
131849       }
131850     }
131851   }
131852
131853   sqlcipher3_free(aCell);
131854   return rc;
131855 }
131856
131857 /*
131858 ** Insert cell pCell into node pNode. Node pNode is the head of a 
131859 ** subtree iHeight high (leaf nodes have iHeight==0).
131860 */
131861 static int rtreeInsertCell(
131862   Rtree *pRtree,
131863   RtreeNode *pNode,
131864   RtreeCell *pCell,
131865   int iHeight
131866 ){
131867   int rc = SQLCIPHER_OK;
131868   if( iHeight>0 ){
131869     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
131870     if( pChild ){
131871       nodeRelease(pRtree, pChild->pParent);
131872       nodeReference(pNode);
131873       pChild->pParent = pNode;
131874     }
131875   }
131876   if( nodeInsertCell(pRtree, pNode, pCell) ){
131877 #if VARIANT_RSTARTREE_REINSERT
131878     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
131879       rc = SplitNode(pRtree, pNode, pCell, iHeight);
131880     }else{
131881       pRtree->iReinsertHeight = iHeight;
131882       rc = Reinsert(pRtree, pNode, pCell, iHeight);
131883     }
131884 #else
131885     rc = SplitNode(pRtree, pNode, pCell, iHeight);
131886 #endif
131887   }else{
131888     rc = AdjustTree(pRtree, pNode, pCell);
131889     if( rc==SQLCIPHER_OK ){
131890       if( iHeight==0 ){
131891         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
131892       }else{
131893         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
131894       }
131895     }
131896   }
131897   return rc;
131898 }
131899
131900 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
131901   int ii;
131902   int rc = SQLCIPHER_OK;
131903   int nCell = NCELL(pNode);
131904
131905   for(ii=0; rc==SQLCIPHER_OK && ii<nCell; ii++){
131906     RtreeNode *pInsert;
131907     RtreeCell cell;
131908     nodeGetCell(pRtree, pNode, ii, &cell);
131909
131910     /* Find a node to store this cell in. pNode->iNode currently contains
131911     ** the height of the sub-tree headed by the cell.
131912     */
131913     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
131914     if( rc==SQLCIPHER_OK ){
131915       int rc2;
131916       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
131917       rc2 = nodeRelease(pRtree, pInsert);
131918       if( rc==SQLCIPHER_OK ){
131919         rc = rc2;
131920       }
131921     }
131922   }
131923   return rc;
131924 }
131925
131926 /*
131927 ** Select a currently unused rowid for a new r-tree record.
131928 */
131929 static int newRowid(Rtree *pRtree, i64 *piRowid){
131930   int rc;
131931   sqlcipher3_bind_null(pRtree->pWriteRowid, 1);
131932   sqlcipher3_bind_null(pRtree->pWriteRowid, 2);
131933   sqlcipher3_step(pRtree->pWriteRowid);
131934   rc = sqlcipher3_reset(pRtree->pWriteRowid);
131935   *piRowid = sqlcipher3_last_insert_rowid(pRtree->db);
131936   return rc;
131937 }
131938
131939 /*
131940 ** Remove the entry with rowid=iDelete from the r-tree structure.
131941 */
131942 static int rtreeDeleteRowid(Rtree *pRtree, sqlcipher3_int64 iDelete){
131943   int rc;                         /* Return code */
131944   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
131945   int iCell;                      /* Index of iDelete cell in pLeaf */
131946   RtreeNode *pRoot;               /* Root node of rtree structure */
131947
131948
131949   /* Obtain a reference to the root node to initialise Rtree.iDepth */
131950   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
131951
131952   /* Obtain a reference to the leaf node that contains the entry 
131953   ** about to be deleted. 
131954   */
131955   if( rc==SQLCIPHER_OK ){
131956     rc = findLeafNode(pRtree, iDelete, &pLeaf);
131957   }
131958
131959   /* Delete the cell in question from the leaf node. */
131960   if( rc==SQLCIPHER_OK ){
131961     int rc2;
131962     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
131963     if( rc==SQLCIPHER_OK ){
131964       rc = deleteCell(pRtree, pLeaf, iCell, 0);
131965     }
131966     rc2 = nodeRelease(pRtree, pLeaf);
131967     if( rc==SQLCIPHER_OK ){
131968       rc = rc2;
131969     }
131970   }
131971
131972   /* Delete the corresponding entry in the <rtree>_rowid table. */
131973   if( rc==SQLCIPHER_OK ){
131974     sqlcipher3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
131975     sqlcipher3_step(pRtree->pDeleteRowid);
131976     rc = sqlcipher3_reset(pRtree->pDeleteRowid);
131977   }
131978
131979   /* Check if the root node now has exactly one child. If so, remove
131980   ** it, schedule the contents of the child for reinsertion and 
131981   ** reduce the tree height by one.
131982   **
131983   ** This is equivalent to copying the contents of the child into
131984   ** the root node (the operation that Gutman's paper says to perform 
131985   ** in this scenario).
131986   */
131987   if( rc==SQLCIPHER_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
131988     int rc2;
131989     RtreeNode *pChild;
131990     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
131991     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
131992     if( rc==SQLCIPHER_OK ){
131993       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
131994     }
131995     rc2 = nodeRelease(pRtree, pChild);
131996     if( rc==SQLCIPHER_OK ) rc = rc2;
131997     if( rc==SQLCIPHER_OK ){
131998       pRtree->iDepth--;
131999       writeInt16(pRoot->zData, pRtree->iDepth);
132000       pRoot->isDirty = 1;
132001     }
132002   }
132003
132004   /* Re-insert the contents of any underfull nodes removed from the tree. */
132005   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
132006     if( rc==SQLCIPHER_OK ){
132007       rc = reinsertNodeContent(pRtree, pLeaf);
132008     }
132009     pRtree->pDeleted = pLeaf->pNext;
132010     sqlcipher3_free(pLeaf);
132011   }
132012
132013   /* Release the reference to the root node. */
132014   if( rc==SQLCIPHER_OK ){
132015     rc = nodeRelease(pRtree, pRoot);
132016   }else{
132017     nodeRelease(pRtree, pRoot);
132018   }
132019
132020   return rc;
132021 }
132022
132023 /*
132024 ** The xUpdate method for rtree module virtual tables.
132025 */
132026 static int rtreeUpdate(
132027   sqlcipher3_vtab *pVtab, 
132028   int nData, 
132029   sqlcipher3_value **azData, 
132030   sqlcipher_int64 *pRowid
132031 ){
132032   Rtree *pRtree = (Rtree *)pVtab;
132033   int rc = SQLCIPHER_OK;
132034   RtreeCell cell;                 /* New cell to insert if nData>1 */
132035   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
132036
132037   rtreeReference(pRtree);
132038   assert(nData>=1);
132039
132040   /* Constraint handling. A write operation on an r-tree table may return
132041   ** SQLCIPHER_CONSTRAINT for two reasons:
132042   **
132043   **   1. A duplicate rowid value, or
132044   **   2. The supplied data violates the "x2>=x1" constraint.
132045   **
132046   ** In the first case, if the conflict-handling mode is REPLACE, then
132047   ** the conflicting row can be removed before proceeding. In the second
132048   ** case, SQLCIPHER_CONSTRAINT must be returned regardless of the
132049   ** conflict-handling mode specified by the user.
132050   */
132051   if( nData>1 ){
132052     int ii;
132053
132054     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
132055     assert( nData==(pRtree->nDim*2 + 3) );
132056     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
132057       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132058         cell.aCoord[ii].f = (float)sqlcipher3_value_double(azData[ii+3]);
132059         cell.aCoord[ii+1].f = (float)sqlcipher3_value_double(azData[ii+4]);
132060         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
132061           rc = SQLCIPHER_CONSTRAINT;
132062           goto constraint;
132063         }
132064       }
132065     }else{
132066       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132067         cell.aCoord[ii].i = sqlcipher3_value_int(azData[ii+3]);
132068         cell.aCoord[ii+1].i = sqlcipher3_value_int(azData[ii+4]);
132069         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
132070           rc = SQLCIPHER_CONSTRAINT;
132071           goto constraint;
132072         }
132073       }
132074     }
132075
132076     /* If a rowid value was supplied, check if it is already present in 
132077     ** the table. If so, the constraint has failed. */
132078     if( sqlcipher3_value_type(azData[2])!=SQLCIPHER_NULL ){
132079       cell.iRowid = sqlcipher3_value_int64(azData[2]);
132080       if( sqlcipher3_value_type(azData[0])==SQLCIPHER_NULL
132081        || sqlcipher3_value_int64(azData[0])!=cell.iRowid
132082       ){
132083         int steprc;
132084         sqlcipher3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
132085         steprc = sqlcipher3_step(pRtree->pReadRowid);
132086         rc = sqlcipher3_reset(pRtree->pReadRowid);
132087         if( SQLCIPHER_ROW==steprc ){
132088           if( sqlcipher3_vtab_on_conflict(pRtree->db)==SQLCIPHER_REPLACE ){
132089             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
132090           }else{
132091             rc = SQLCIPHER_CONSTRAINT;
132092             goto constraint;
132093           }
132094         }
132095       }
132096       bHaveRowid = 1;
132097     }
132098   }
132099
132100   /* If azData[0] is not an SQL NULL value, it is the rowid of a
132101   ** record to delete from the r-tree table. The following block does
132102   ** just that.
132103   */
132104   if( sqlcipher3_value_type(azData[0])!=SQLCIPHER_NULL ){
132105     rc = rtreeDeleteRowid(pRtree, sqlcipher3_value_int64(azData[0]));
132106   }
132107
132108   /* If the azData[] array contains more than one element, elements
132109   ** (azData[2]..azData[argc-1]) contain a new record to insert into
132110   ** the r-tree structure.
132111   */
132112   if( rc==SQLCIPHER_OK && nData>1 ){
132113     /* Insert the new record into the r-tree */
132114     RtreeNode *pLeaf;
132115
132116     /* Figure out the rowid of the new row. */
132117     if( bHaveRowid==0 ){
132118       rc = newRowid(pRtree, &cell.iRowid);
132119     }
132120     *pRowid = cell.iRowid;
132121
132122     if( rc==SQLCIPHER_OK ){
132123       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
132124     }
132125     if( rc==SQLCIPHER_OK ){
132126       int rc2;
132127       pRtree->iReinsertHeight = -1;
132128       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
132129       rc2 = nodeRelease(pRtree, pLeaf);
132130       if( rc==SQLCIPHER_OK ){
132131         rc = rc2;
132132       }
132133     }
132134   }
132135
132136 constraint:
132137   rtreeRelease(pRtree);
132138   return rc;
132139 }
132140
132141 /*
132142 ** The xRename method for rtree module virtual tables.
132143 */
132144 static int rtreeRename(sqlcipher3_vtab *pVtab, const char *zNewName){
132145   Rtree *pRtree = (Rtree *)pVtab;
132146   int rc = SQLCIPHER_NOMEM;
132147   char *zSql = sqlcipher3_mprintf(
132148     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
132149     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
132150     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
132151     , pRtree->zDb, pRtree->zName, zNewName 
132152     , pRtree->zDb, pRtree->zName, zNewName 
132153     , pRtree->zDb, pRtree->zName, zNewName
132154   );
132155   if( zSql ){
132156     rc = sqlcipher3_exec(pRtree->db, zSql, 0, 0, 0);
132157     sqlcipher3_free(zSql);
132158   }
132159   return rc;
132160 }
132161
132162 static sqlcipher3_module rtreeModule = {
132163   0,                          /* iVersion */
132164   rtreeCreate,                /* xCreate - create a table */
132165   rtreeConnect,               /* xConnect - connect to an existing table */
132166   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
132167   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
132168   rtreeDestroy,               /* xDestroy - Drop a table */
132169   rtreeOpen,                  /* xOpen - open a cursor */
132170   rtreeClose,                 /* xClose - close a cursor */
132171   rtreeFilter,                /* xFilter - configure scan constraints */
132172   rtreeNext,                  /* xNext - advance a cursor */
132173   rtreeEof,                   /* xEof */
132174   rtreeColumn,                /* xColumn - read data */
132175   rtreeRowid,                 /* xRowid - read data */
132176   rtreeUpdate,                /* xUpdate - write data */
132177   0,                          /* xBegin - begin transaction */
132178   0,                          /* xSync - sync transaction */
132179   0,                          /* xCommit - commit transaction */
132180   0,                          /* xRollback - rollback transaction */
132181   0,                          /* xFindFunction - function overloading */
132182   rtreeRename,                /* xRename - rename the table */
132183   0,                          /* xSavepoint */
132184   0,                          /* xRelease */
132185   0                           /* xRollbackTo */
132186 };
132187
132188 static int rtreeSqlInit(
132189   Rtree *pRtree, 
132190   sqlcipher3 *db, 
132191   const char *zDb, 
132192   const char *zPrefix, 
132193   int isCreate
132194 ){
132195   int rc = SQLCIPHER_OK;
132196
132197   #define N_STATEMENT 9
132198   static const char *azSql[N_STATEMENT] = {
132199     /* Read and write the xxx_node table */
132200     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
132201     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
132202     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
132203
132204     /* Read and write the xxx_rowid table */
132205     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
132206     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
132207     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
132208
132209     /* Read and write the xxx_parent table */
132210     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
132211     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
132212     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
132213   };
132214   sqlcipher3_stmt **appStmt[N_STATEMENT];
132215   int i;
132216
132217   pRtree->db = db;
132218
132219   if( isCreate ){
132220     char *zCreate = sqlcipher3_mprintf(
132221 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
132222 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
132223 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
132224 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
132225       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
132226     );
132227     if( !zCreate ){
132228       return SQLCIPHER_NOMEM;
132229     }
132230     rc = sqlcipher3_exec(db, zCreate, 0, 0, 0);
132231     sqlcipher3_free(zCreate);
132232     if( rc!=SQLCIPHER_OK ){
132233       return rc;
132234     }
132235   }
132236
132237   appStmt[0] = &pRtree->pReadNode;
132238   appStmt[1] = &pRtree->pWriteNode;
132239   appStmt[2] = &pRtree->pDeleteNode;
132240   appStmt[3] = &pRtree->pReadRowid;
132241   appStmt[4] = &pRtree->pWriteRowid;
132242   appStmt[5] = &pRtree->pDeleteRowid;
132243   appStmt[6] = &pRtree->pReadParent;
132244   appStmt[7] = &pRtree->pWriteParent;
132245   appStmt[8] = &pRtree->pDeleteParent;
132246
132247   for(i=0; i<N_STATEMENT && rc==SQLCIPHER_OK; i++){
132248     char *zSql = sqlcipher3_mprintf(azSql[i], zDb, zPrefix);
132249     if( zSql ){
132250       rc = sqlcipher3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
132251     }else{
132252       rc = SQLCIPHER_NOMEM;
132253     }
132254     sqlcipher3_free(zSql);
132255   }
132256
132257   return rc;
132258 }
132259
132260 /*
132261 ** The second argument to this function contains the text of an SQL statement
132262 ** that returns a single integer value. The statement is compiled and executed
132263 ** using database connection db. If successful, the integer value returned
132264 ** is written to *piVal and SQLCIPHER_OK returned. Otherwise, an SQLite error
132265 ** code is returned and the value of *piVal after returning is not defined.
132266 */
132267 static int getIntFromStmt(sqlcipher3 *db, const char *zSql, int *piVal){
132268   int rc = SQLCIPHER_NOMEM;
132269   if( zSql ){
132270     sqlcipher3_stmt *pStmt = 0;
132271     rc = sqlcipher3_prepare_v2(db, zSql, -1, &pStmt, 0);
132272     if( rc==SQLCIPHER_OK ){
132273       if( SQLCIPHER_ROW==sqlcipher3_step(pStmt) ){
132274         *piVal = sqlcipher3_column_int(pStmt, 0);
132275       }
132276       rc = sqlcipher3_finalize(pStmt);
132277     }
132278   }
132279   return rc;
132280 }
132281
132282 /*
132283 ** This function is called from within the xConnect() or xCreate() method to
132284 ** determine the node-size used by the rtree table being created or connected
132285 ** to. If successful, pRtree->iNodeSize is populated and SQLCIPHER_OK returned.
132286 ** Otherwise, an SQLite error code is returned.
132287 **
132288 ** If this function is being called as part of an xConnect(), then the rtree
132289 ** table already exists. In this case the node-size is determined by inspecting
132290 ** the root node of the tree.
132291 **
132292 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
132293 ** This ensures that each node is stored on a single database page. If the 
132294 ** database page-size is so large that more than RTREE_MAXCELLS entries 
132295 ** would fit in a single node, use a smaller node-size.
132296 */
132297 static int getNodeSize(
132298   sqlcipher3 *db,                    /* Database handle */
132299   Rtree *pRtree,                  /* Rtree handle */
132300   int isCreate                    /* True for xCreate, false for xConnect */
132301 ){
132302   int rc;
132303   char *zSql;
132304   if( isCreate ){
132305     int iPageSize = 0;
132306     zSql = sqlcipher3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
132307     rc = getIntFromStmt(db, zSql, &iPageSize);
132308     if( rc==SQLCIPHER_OK ){
132309       pRtree->iNodeSize = iPageSize-64;
132310       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
132311         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
132312       }
132313     }
132314   }else{
132315     zSql = sqlcipher3_mprintf(
132316         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
132317         pRtree->zDb, pRtree->zName
132318     );
132319     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
132320   }
132321
132322   sqlcipher3_free(zSql);
132323   return rc;
132324 }
132325
132326 /* 
132327 ** This function is the implementation of both the xConnect and xCreate
132328 ** methods of the r-tree virtual table.
132329 **
132330 **   argv[0]   -> module name
132331 **   argv[1]   -> database name
132332 **   argv[2]   -> table name
132333 **   argv[...] -> column names...
132334 */
132335 static int rtreeInit(
132336   sqlcipher3 *db,                        /* Database connection */
132337   void *pAux,                         /* One of the RTREE_COORD_* constants */
132338   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
132339   sqlcipher3_vtab **ppVtab,              /* OUT: New virtual table */
132340   char **pzErr,                       /* OUT: Error message, if any */
132341   int isCreate                        /* True for xCreate, false for xConnect */
132342 ){
132343   int rc = SQLCIPHER_OK;
132344   Rtree *pRtree;
132345   int nDb;              /* Length of string argv[1] */
132346   int nName;            /* Length of string argv[2] */
132347   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
132348
132349   const char *aErrMsg[] = {
132350     0,                                                    /* 0 */
132351     "Wrong number of columns for an rtree table",         /* 1 */
132352     "Too few columns for an rtree table",                 /* 2 */
132353     "Too many columns for an rtree table"                 /* 3 */
132354   };
132355
132356   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
132357   if( aErrMsg[iErr] ){
132358     *pzErr = sqlcipher3_mprintf("%s", aErrMsg[iErr]);
132359     return SQLCIPHER_ERROR;
132360   }
132361
132362   sqlcipher3_vtab_config(db, SQLCIPHER_VTAB_CONSTRAINT_SUPPORT, 1);
132363
132364   /* Allocate the sqlcipher3_vtab structure */
132365   nDb = strlen(argv[1]);
132366   nName = strlen(argv[2]);
132367   pRtree = (Rtree *)sqlcipher3_malloc(sizeof(Rtree)+nDb+nName+2);
132368   if( !pRtree ){
132369     return SQLCIPHER_NOMEM;
132370   }
132371   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
132372   pRtree->nBusy = 1;
132373   pRtree->base.pModule = &rtreeModule;
132374   pRtree->zDb = (char *)&pRtree[1];
132375   pRtree->zName = &pRtree->zDb[nDb+1];
132376   pRtree->nDim = (argc-4)/2;
132377   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
132378   pRtree->eCoordType = eCoordType;
132379   memcpy(pRtree->zDb, argv[1], nDb);
132380   memcpy(pRtree->zName, argv[2], nName);
132381
132382   /* Figure out the node size to use. */
132383   rc = getNodeSize(db, pRtree, isCreate);
132384
132385   /* Create/Connect to the underlying relational database schema. If
132386   ** that is successful, call sqlcipher3_declare_vtab() to configure
132387   ** the r-tree table schema.
132388   */
132389   if( rc==SQLCIPHER_OK ){
132390     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
132391       *pzErr = sqlcipher3_mprintf("%s", sqlcipher3_errmsg(db));
132392     }else{
132393       char *zSql = sqlcipher3_mprintf("CREATE TABLE x(%s", argv[3]);
132394       char *zTmp;
132395       int ii;
132396       for(ii=4; zSql && ii<argc; ii++){
132397         zTmp = zSql;
132398         zSql = sqlcipher3_mprintf("%s, %s", zTmp, argv[ii]);
132399         sqlcipher3_free(zTmp);
132400       }
132401       if( zSql ){
132402         zTmp = zSql;
132403         zSql = sqlcipher3_mprintf("%s);", zTmp);
132404         sqlcipher3_free(zTmp);
132405       }
132406       if( !zSql ){
132407         rc = SQLCIPHER_NOMEM;
132408       }else if( SQLCIPHER_OK!=(rc = sqlcipher3_declare_vtab(db, zSql)) ){
132409         *pzErr = sqlcipher3_mprintf("%s", sqlcipher3_errmsg(db));
132410       }
132411       sqlcipher3_free(zSql);
132412     }
132413   }
132414
132415   if( rc==SQLCIPHER_OK ){
132416     *ppVtab = (sqlcipher3_vtab *)pRtree;
132417   }else{
132418     rtreeRelease(pRtree);
132419   }
132420   return rc;
132421 }
132422
132423
132424 /*
132425 ** Implementation of a scalar function that decodes r-tree nodes to
132426 ** human readable strings. This can be used for debugging and analysis.
132427 **
132428 ** The scalar function takes two arguments, a blob of data containing
132429 ** an r-tree node, and the number of dimensions the r-tree indexes.
132430 ** For a two-dimensional r-tree structure called "rt", to deserialize
132431 ** all nodes, a statement like:
132432 **
132433 **   SELECT rtreenode(2, data) FROM rt_node;
132434 **
132435 ** The human readable string takes the form of a Tcl list with one
132436 ** entry for each cell in the r-tree node. Each entry is itself a
132437 ** list, containing the 8-byte rowid/pageno followed by the 
132438 ** <num-dimension>*2 coordinates.
132439 */
132440 static void rtreenode(sqlcipher3_context *ctx, int nArg, sqlcipher3_value **apArg){
132441   char *zText = 0;
132442   RtreeNode node;
132443   Rtree tree;
132444   int ii;
132445
132446   UNUSED_PARAMETER(nArg);
132447   memset(&node, 0, sizeof(RtreeNode));
132448   memset(&tree, 0, sizeof(Rtree));
132449   tree.nDim = sqlcipher3_value_int(apArg[0]);
132450   tree.nBytesPerCell = 8 + 8 * tree.nDim;
132451   node.zData = (u8 *)sqlcipher3_value_blob(apArg[1]);
132452
132453   for(ii=0; ii<NCELL(&node); ii++){
132454     char zCell[512];
132455     int nCell = 0;
132456     RtreeCell cell;
132457     int jj;
132458
132459     nodeGetCell(&tree, &node, ii, &cell);
132460     sqlcipher3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
132461     nCell = strlen(zCell);
132462     for(jj=0; jj<tree.nDim*2; jj++){
132463       sqlcipher3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
132464       nCell = strlen(zCell);
132465     }
132466
132467     if( zText ){
132468       char *zTextNew = sqlcipher3_mprintf("%s {%s}", zText, zCell);
132469       sqlcipher3_free(zText);
132470       zText = zTextNew;
132471     }else{
132472       zText = sqlcipher3_mprintf("{%s}", zCell);
132473     }
132474   }
132475   
132476   sqlcipher3_result_text(ctx, zText, -1, sqlcipher3_free);
132477 }
132478
132479 static void rtreedepth(sqlcipher3_context *ctx, int nArg, sqlcipher3_value **apArg){
132480   UNUSED_PARAMETER(nArg);
132481   if( sqlcipher3_value_type(apArg[0])!=SQLCIPHER_BLOB 
132482    || sqlcipher3_value_bytes(apArg[0])<2
132483   ){
132484     sqlcipher3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
132485   }else{
132486     u8 *zBlob = (u8 *)sqlcipher3_value_blob(apArg[0]);
132487     sqlcipher3_result_int(ctx, readInt16(zBlob));
132488   }
132489 }
132490
132491 /*
132492 ** Register the r-tree module with database handle db. This creates the
132493 ** virtual table module "rtree" and the debugging/analysis scalar 
132494 ** function "rtreenode".
132495 */
132496 SQLCIPHER_PRIVATE int sqlcipher3RtreeInit(sqlcipher3 *db){
132497   const int utf8 = SQLCIPHER_UTF8;
132498   int rc;
132499
132500   rc = sqlcipher3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
132501   if( rc==SQLCIPHER_OK ){
132502     rc = sqlcipher3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
132503   }
132504   if( rc==SQLCIPHER_OK ){
132505     void *c = (void *)RTREE_COORD_REAL32;
132506     rc = sqlcipher3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
132507   }
132508   if( rc==SQLCIPHER_OK ){
132509     void *c = (void *)RTREE_COORD_INT32;
132510     rc = sqlcipher3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
132511   }
132512
132513   return rc;
132514 }
132515
132516 /*
132517 ** A version of sqlcipher3_free() that can be used as a callback. This is used
132518 ** in two places - as the destructor for the blob value returned by the
132519 ** invocation of a geometry function, and as the destructor for the geometry
132520 ** functions themselves.
132521 */
132522 static void doSqlite3Free(void *p){
132523   sqlcipher3_free(p);
132524 }
132525
132526 /*
132527 ** Each call to sqlcipher3_rtree_geometry_callback() creates an ordinary SQLite
132528 ** scalar user function. This C function is the callback used for all such
132529 ** registered SQL functions.
132530 **
132531 ** The scalar user functions return a blob that is interpreted by r-tree
132532 ** table MATCH operators.
132533 */
132534 static void geomCallback(sqlcipher3_context *ctx, int nArg, sqlcipher3_value **aArg){
132535   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlcipher3_user_data(ctx);
132536   RtreeMatchArg *pBlob;
132537   int nBlob;
132538
132539   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
132540   pBlob = (RtreeMatchArg *)sqlcipher3_malloc(nBlob);
132541   if( !pBlob ){
132542     sqlcipher3_result_error_nomem(ctx);
132543   }else{
132544     int i;
132545     pBlob->magic = RTREE_GEOMETRY_MAGIC;
132546     pBlob->xGeom = pGeomCtx->xGeom;
132547     pBlob->pContext = pGeomCtx->pContext;
132548     pBlob->nParam = nArg;
132549     for(i=0; i<nArg; i++){
132550       pBlob->aParam[i] = sqlcipher3_value_double(aArg[i]);
132551     }
132552     sqlcipher3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
132553   }
132554 }
132555
132556 /*
132557 ** Register a new geometry function for use with the r-tree MATCH operator.
132558 */
132559 SQLCIPHER_API int sqlcipher3_rtree_geometry_callback(
132560   sqlcipher3 *db,
132561   const char *zGeom,
132562   int (*xGeom)(sqlcipher3_rtree_geometry *, int, double *, int *),
132563   void *pContext
132564 ){
132565   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
132566
132567   /* Allocate and populate the context object. */
132568   pGeomCtx = (RtreeGeomCallback *)sqlcipher3_malloc(sizeof(RtreeGeomCallback));
132569   if( !pGeomCtx ) return SQLCIPHER_NOMEM;
132570   pGeomCtx->xGeom = xGeom;
132571   pGeomCtx->pContext = pContext;
132572
132573   /* Create the new user-function. Register a destructor function to delete
132574   ** the context object when it is no longer required.  */
132575   return sqlcipher3_create_function_v2(db, zGeom, -1, SQLCIPHER_ANY, 
132576       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
132577   );
132578 }
132579
132580 #if !SQLCIPHER_CORE
132581 SQLCIPHER_API int sqlcipher3_extension_init(
132582   sqlcipher3 *db,
132583   char **pzErrMsg,
132584   const sqlcipher3_api_routines *pApi
132585 ){
132586   SQLCIPHER_EXTENSION_INIT2(pApi)
132587   return sqlcipher3RtreeInit(db);
132588 }
132589 #endif
132590
132591 #endif
132592
132593 /************** End of rtree.c ***********************************************/
132594 /************** Begin file icu.c *********************************************/
132595 /*
132596 ** 2007 May 6
132597 **
132598 ** The author disclaims copyright to this source code.  In place of
132599 ** a legal notice, here is a blessing:
132600 **
132601 **    May you do good and not evil.
132602 **    May you find forgiveness for yourself and forgive others.
132603 **    May you share freely, never taking more than you give.
132604 **
132605 *************************************************************************
132606 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
132607 **
132608 ** This file implements an integration between the ICU library 
132609 ** ("International Components for Unicode", an open-source library 
132610 ** for handling unicode data) and SQLite. The integration uses 
132611 ** ICU to provide the following to SQLite:
132612 **
132613 **   * An implementation of the SQL regexp() function (and hence REGEXP
132614 **     operator) using the ICU uregex_XX() APIs.
132615 **
132616 **   * Implementations of the SQL scalar upper() and lower() functions
132617 **     for case mapping.
132618 **
132619 **   * Integration of ICU and SQLite collation seqences.
132620 **
132621 **   * An implementation of the LIKE operator that uses ICU to 
132622 **     provide case-independent matching.
132623 */
132624
132625 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_ICU)
132626
132627 /* Include ICU headers */
132628 #include <unicode/utypes.h>
132629 #include <unicode/uregex.h>
132630 #include <unicode/ustring.h>
132631 #include <unicode/ucol.h>
132632
132633 /* #include <assert.h> */
132634
132635 #ifndef SQLCIPHER_CORE
132636   SQLCIPHER_EXTENSION_INIT1
132637 #else
132638 #endif
132639
132640 /*
132641 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
132642 ** operator.
132643 */
132644 #ifndef SQLCIPHER_MAX_LIKE_PATTERN_LENGTH
132645 # define SQLCIPHER_MAX_LIKE_PATTERN_LENGTH 50000
132646 #endif
132647
132648 /*
132649 ** Version of sqlcipher3_free() that is always a function, never a macro.
132650 */
132651 static void xFree(void *p){
132652   sqlcipher3_free(p);
132653 }
132654
132655 /*
132656 ** Compare two UTF-8 strings for equality where the first string is
132657 ** a "LIKE" expression. Return true (1) if they are the same and 
132658 ** false (0) if they are different.
132659 */
132660 static int icuLikeCompare(
132661   const uint8_t *zPattern,   /* LIKE pattern */
132662   const uint8_t *zString,    /* The UTF-8 string to compare against */
132663   const UChar32 uEsc         /* The escape character */
132664 ){
132665   static const int MATCH_ONE = (UChar32)'_';
132666   static const int MATCH_ALL = (UChar32)'%';
132667
132668   int iPattern = 0;       /* Current byte index in zPattern */
132669   int iString = 0;        /* Current byte index in zString */
132670
132671   int prevEscape = 0;     /* True if the previous character was uEsc */
132672
132673   while( zPattern[iPattern]!=0 ){
132674
132675     /* Read (and consume) the next character from the input pattern. */
132676     UChar32 uPattern;
132677     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
132678     assert(uPattern!=0);
132679
132680     /* There are now 4 possibilities:
132681     **
132682     **     1. uPattern is an unescaped match-all character "%",
132683     **     2. uPattern is an unescaped match-one character "_",
132684     **     3. uPattern is an unescaped escape character, or
132685     **     4. uPattern is to be handled as an ordinary character
132686     */
132687     if( !prevEscape && uPattern==MATCH_ALL ){
132688       /* Case 1. */
132689       uint8_t c;
132690
132691       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
132692       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
132693       ** test string.
132694       */
132695       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
132696         if( c==MATCH_ONE ){
132697           if( zString[iString]==0 ) return 0;
132698           U8_FWD_1_UNSAFE(zString, iString);
132699         }
132700         iPattern++;
132701       }
132702
132703       if( zPattern[iPattern]==0 ) return 1;
132704
132705       while( zString[iString] ){
132706         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
132707           return 1;
132708         }
132709         U8_FWD_1_UNSAFE(zString, iString);
132710       }
132711       return 0;
132712
132713     }else if( !prevEscape && uPattern==MATCH_ONE ){
132714       /* Case 2. */
132715       if( zString[iString]==0 ) return 0;
132716       U8_FWD_1_UNSAFE(zString, iString);
132717
132718     }else if( !prevEscape && uPattern==uEsc){
132719       /* Case 3. */
132720       prevEscape = 1;
132721
132722     }else{
132723       /* Case 4. */
132724       UChar32 uString;
132725       U8_NEXT_UNSAFE(zString, iString, uString);
132726       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
132727       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
132728       if( uString!=uPattern ){
132729         return 0;
132730       }
132731       prevEscape = 0;
132732     }
132733   }
132734
132735   return zString[iString]==0;
132736 }
132737
132738 /*
132739 ** Implementation of the like() SQL function.  This function implements
132740 ** the build-in LIKE operator.  The first argument to the function is the
132741 ** pattern and the second argument is the string.  So, the SQL statements:
132742 **
132743 **       A LIKE B
132744 **
132745 ** is implemented as like(B, A). If there is an escape character E, 
132746 **
132747 **       A LIKE B ESCAPE E
132748 **
132749 ** is mapped to like(B, A, E).
132750 */
132751 static void icuLikeFunc(
132752   sqlcipher3_context *context, 
132753   int argc, 
132754   sqlcipher3_value **argv
132755 ){
132756   const unsigned char *zA = sqlcipher3_value_text(argv[0]);
132757   const unsigned char *zB = sqlcipher3_value_text(argv[1]);
132758   UChar32 uEsc = 0;
132759
132760   /* Limit the length of the LIKE or GLOB pattern to avoid problems
132761   ** of deep recursion and N*N behavior in patternCompare().
132762   */
132763   if( sqlcipher3_value_bytes(argv[0])>SQLCIPHER_MAX_LIKE_PATTERN_LENGTH ){
132764     sqlcipher3_result_error(context, "LIKE or GLOB pattern too complex", -1);
132765     return;
132766   }
132767
132768
132769   if( argc==3 ){
132770     /* The escape character string must consist of a single UTF-8 character.
132771     ** Otherwise, return an error.
132772     */
132773     int nE= sqlcipher3_value_bytes(argv[2]);
132774     const unsigned char *zE = sqlcipher3_value_text(argv[2]);
132775     int i = 0;
132776     if( zE==0 ) return;
132777     U8_NEXT(zE, i, nE, uEsc);
132778     if( i!=nE){
132779       sqlcipher3_result_error(context, 
132780           "ESCAPE expression must be a single character", -1);
132781       return;
132782     }
132783   }
132784
132785   if( zA && zB ){
132786     sqlcipher3_result_int(context, icuLikeCompare(zA, zB, uEsc));
132787   }
132788 }
132789
132790 /*
132791 ** This function is called when an ICU function called from within
132792 ** the implementation of an SQL scalar function returns an error.
132793 **
132794 ** The scalar function context passed as the first argument is 
132795 ** loaded with an error message based on the following two args.
132796 */
132797 static void icuFunctionError(
132798   sqlcipher3_context *pCtx,       /* SQLite scalar function context */
132799   const char *zName,           /* Name of ICU function that failed */
132800   UErrorCode e                 /* Error code returned by ICU function */
132801 ){
132802   char zBuf[128];
132803   sqlcipher3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
132804   zBuf[127] = '\0';
132805   sqlcipher3_result_error(pCtx, zBuf, -1);
132806 }
132807
132808 /*
132809 ** Function to delete compiled regexp objects. Registered as
132810 ** a destructor function with sqlcipher3_set_auxdata().
132811 */
132812 static void icuRegexpDelete(void *p){
132813   URegularExpression *pExpr = (URegularExpression *)p;
132814   uregex_close(pExpr);
132815 }
132816
132817 /*
132818 ** Implementation of SQLite REGEXP operator. This scalar function takes
132819 ** two arguments. The first is a regular expression pattern to compile
132820 ** the second is a string to match against that pattern. If either 
132821 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
132822 ** is 1 if the string matches the pattern, or 0 otherwise.
132823 **
132824 ** SQLite maps the regexp() function to the regexp() operator such
132825 ** that the following two are equivalent:
132826 **
132827 **     zString REGEXP zPattern
132828 **     regexp(zPattern, zString)
132829 **
132830 ** Uses the following ICU regexp APIs:
132831 **
132832 **     uregex_open()
132833 **     uregex_matches()
132834 **     uregex_close()
132835 */
132836 static void icuRegexpFunc(sqlcipher3_context *p, int nArg, sqlcipher3_value **apArg){
132837   UErrorCode status = U_ZERO_ERROR;
132838   URegularExpression *pExpr;
132839   UBool res;
132840   const UChar *zString = sqlcipher3_value_text16(apArg[1]);
132841
132842   (void)nArg;  /* Unused parameter */
132843
132844   /* If the left hand side of the regexp operator is NULL, 
132845   ** then the result is also NULL. 
132846   */
132847   if( !zString ){
132848     return;
132849   }
132850
132851   pExpr = sqlcipher3_get_auxdata(p, 0);
132852   if( !pExpr ){
132853     const UChar *zPattern = sqlcipher3_value_text16(apArg[0]);
132854     if( !zPattern ){
132855       return;
132856     }
132857     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
132858
132859     if( U_SUCCESS(status) ){
132860       sqlcipher3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
132861     }else{
132862       assert(!pExpr);
132863       icuFunctionError(p, "uregex_open", status);
132864       return;
132865     }
132866   }
132867
132868   /* Configure the text that the regular expression operates on. */
132869   uregex_setText(pExpr, zString, -1, &status);
132870   if( !U_SUCCESS(status) ){
132871     icuFunctionError(p, "uregex_setText", status);
132872     return;
132873   }
132874
132875   /* Attempt the match */
132876   res = uregex_matches(pExpr, 0, &status);
132877   if( !U_SUCCESS(status) ){
132878     icuFunctionError(p, "uregex_matches", status);
132879     return;
132880   }
132881
132882   /* Set the text that the regular expression operates on to a NULL
132883   ** pointer. This is not really necessary, but it is tidier than 
132884   ** leaving the regular expression object configured with an invalid
132885   ** pointer after this function returns.
132886   */
132887   uregex_setText(pExpr, 0, 0, &status);
132888
132889   /* Return 1 or 0. */
132890   sqlcipher3_result_int(p, res ? 1 : 0);
132891 }
132892
132893 /*
132894 ** Implementations of scalar functions for case mapping - upper() and 
132895 ** lower(). Function upper() converts its input to upper-case (ABC).
132896 ** Function lower() converts to lower-case (abc).
132897 **
132898 ** ICU provides two types of case mapping, "general" case mapping and
132899 ** "language specific". Refer to ICU documentation for the differences
132900 ** between the two.
132901 **
132902 ** To utilise "general" case mapping, the upper() or lower() scalar 
132903 ** functions are invoked with one argument:
132904 **
132905 **     upper('ABC') -> 'abc'
132906 **     lower('abc') -> 'ABC'
132907 **
132908 ** To access ICU "language specific" case mapping, upper() or lower()
132909 ** should be invoked with two arguments. The second argument is the name
132910 ** of the locale to use. Passing an empty string ("") or SQL NULL value
132911 ** as the second argument is the same as invoking the 1 argument version
132912 ** of upper() or lower().
132913 **
132914 **     lower('I', 'en_us') -> 'i'
132915 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
132916 **
132917 ** http://www.icu-project.org/userguide/posix.html#case_mappings
132918 */
132919 static void icuCaseFunc16(sqlcipher3_context *p, int nArg, sqlcipher3_value **apArg){
132920   const UChar *zInput;
132921   UChar *zOutput;
132922   int nInput;
132923   int nOutput;
132924
132925   UErrorCode status = U_ZERO_ERROR;
132926   const char *zLocale = 0;
132927
132928   assert(nArg==1 || nArg==2);
132929   if( nArg==2 ){
132930     zLocale = (const char *)sqlcipher3_value_text(apArg[1]);
132931   }
132932
132933   zInput = sqlcipher3_value_text16(apArg[0]);
132934   if( !zInput ){
132935     return;
132936   }
132937   nInput = sqlcipher3_value_bytes16(apArg[0]);
132938
132939   nOutput = nInput * 2 + 2;
132940   zOutput = sqlcipher3_malloc(nOutput);
132941   if( !zOutput ){
132942     return;
132943   }
132944
132945   if( sqlcipher3_user_data(p) ){
132946     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
132947   }else{
132948     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
132949   }
132950
132951   if( !U_SUCCESS(status) ){
132952     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
132953     return;
132954   }
132955
132956   sqlcipher3_result_text16(p, zOutput, -1, xFree);
132957 }
132958
132959 /*
132960 ** Collation sequence destructor function. The pCtx argument points to
132961 ** a UCollator structure previously allocated using ucol_open().
132962 */
132963 static void icuCollationDel(void *pCtx){
132964   UCollator *p = (UCollator *)pCtx;
132965   ucol_close(p);
132966 }
132967
132968 /*
132969 ** Collation sequence comparison function. The pCtx argument points to
132970 ** a UCollator structure previously allocated using ucol_open().
132971 */
132972 static int icuCollationColl(
132973   void *pCtx,
132974   int nLeft,
132975   const void *zLeft,
132976   int nRight,
132977   const void *zRight
132978 ){
132979   UCollationResult res;
132980   UCollator *p = (UCollator *)pCtx;
132981   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
132982   switch( res ){
132983     case UCOL_LESS:    return -1;
132984     case UCOL_GREATER: return +1;
132985     case UCOL_EQUAL:   return 0;
132986   }
132987   assert(!"Unexpected return value from ucol_strcoll()");
132988   return 0;
132989 }
132990
132991 /*
132992 ** Implementation of the scalar function icu_load_collation().
132993 **
132994 ** This scalar function is used to add ICU collation based collation 
132995 ** types to an SQLite database connection. It is intended to be called
132996 ** as follows:
132997 **
132998 **     SELECT icu_load_collation(<locale>, <collation-name>);
132999 **
133000 ** Where <locale> is a string containing an ICU locale identifier (i.e.
133001 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
133002 ** collation sequence to create.
133003 */
133004 static void icuLoadCollation(
133005   sqlcipher3_context *p, 
133006   int nArg, 
133007   sqlcipher3_value **apArg
133008 ){
133009   sqlcipher3 *db = (sqlcipher3 *)sqlcipher3_user_data(p);
133010   UErrorCode status = U_ZERO_ERROR;
133011   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
133012   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
133013   UCollator *pUCollator;    /* ICU library collation object */
133014   int rc;                   /* Return code from sqlcipher3_create_collation_x() */
133015
133016   assert(nArg==2);
133017   zLocale = (const char *)sqlcipher3_value_text(apArg[0]);
133018   zName = (const char *)sqlcipher3_value_text(apArg[1]);
133019
133020   if( !zLocale || !zName ){
133021     return;
133022   }
133023
133024   pUCollator = ucol_open(zLocale, &status);
133025   if( !U_SUCCESS(status) ){
133026     icuFunctionError(p, "ucol_open", status);
133027     return;
133028   }
133029   assert(p);
133030
133031   rc = sqlcipher3_create_collation_v2(db, zName, SQLCIPHER_UTF16, (void *)pUCollator, 
133032       icuCollationColl, icuCollationDel
133033   );
133034   if( rc!=SQLCIPHER_OK ){
133035     ucol_close(pUCollator);
133036     sqlcipher3_result_error(p, "Error registering collation function", -1);
133037   }
133038 }
133039
133040 /*
133041 ** Register the ICU extension functions with database db.
133042 */
133043 SQLCIPHER_PRIVATE int sqlcipher3IcuInit(sqlcipher3 *db){
133044   struct IcuScalar {
133045     const char *zName;                        /* Function name */
133046     int nArg;                                 /* Number of arguments */
133047     int enc;                                  /* Optimal text encoding */
133048     void *pContext;                           /* sqlcipher3_user_data() context */
133049     void (*xFunc)(sqlcipher3_context*,int,sqlcipher3_value**);
133050   } scalars[] = {
133051     {"regexp", 2, SQLCIPHER_ANY,          0, icuRegexpFunc},
133052
133053     {"lower",  1, SQLCIPHER_UTF16,        0, icuCaseFunc16},
133054     {"lower",  2, SQLCIPHER_UTF16,        0, icuCaseFunc16},
133055     {"upper",  1, SQLCIPHER_UTF16, (void*)1, icuCaseFunc16},
133056     {"upper",  2, SQLCIPHER_UTF16, (void*)1, icuCaseFunc16},
133057
133058     {"lower",  1, SQLCIPHER_UTF8,         0, icuCaseFunc16},
133059     {"lower",  2, SQLCIPHER_UTF8,         0, icuCaseFunc16},
133060     {"upper",  1, SQLCIPHER_UTF8,  (void*)1, icuCaseFunc16},
133061     {"upper",  2, SQLCIPHER_UTF8,  (void*)1, icuCaseFunc16},
133062
133063     {"like",   2, SQLCIPHER_UTF8,         0, icuLikeFunc},
133064     {"like",   3, SQLCIPHER_UTF8,         0, icuLikeFunc},
133065
133066     {"icu_load_collation",  2, SQLCIPHER_UTF8, (void*)db, icuLoadCollation},
133067   };
133068
133069   int rc = SQLCIPHER_OK;
133070   int i;
133071
133072   for(i=0; rc==SQLCIPHER_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
133073     struct IcuScalar *p = &scalars[i];
133074     rc = sqlcipher3_create_function(
133075         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
133076     );
133077   }
133078
133079   return rc;
133080 }
133081
133082 #if !SQLCIPHER_CORE
133083 SQLCIPHER_API int sqlcipher3_extension_init(
133084   sqlcipher3 *db, 
133085   char **pzErrMsg,
133086   const sqlcipher3_api_routines *pApi
133087 ){
133088   SQLCIPHER_EXTENSION_INIT2(pApi)
133089   return sqlcipher3IcuInit(db);
133090 }
133091 #endif
133092
133093 #endif
133094
133095 /************** End of icu.c *************************************************/
133096 /************** Begin file fts3_icu.c ****************************************/
133097 /*
133098 ** 2007 June 22
133099 **
133100 ** The author disclaims copyright to this source code.  In place of
133101 ** a legal notice, here is a blessing:
133102 **
133103 **    May you do good and not evil.
133104 **    May you find forgiveness for yourself and forgive others.
133105 **    May you share freely, never taking more than you give.
133106 **
133107 *************************************************************************
133108 ** This file implements a tokenizer for fts3 based on the ICU library.
133109 */
133110 #if !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3)
133111 #ifdef SQLCIPHER_ENABLE_ICU
133112
133113 /* #include <assert.h> */
133114 /* #include <string.h> */
133115
133116 #include <unicode/ubrk.h>
133117 /* #include <unicode/ucol.h> */
133118 /* #include <unicode/ustring.h> */
133119 #include <unicode/utf16.h>
133120
133121 typedef struct IcuTokenizer IcuTokenizer;
133122 typedef struct IcuCursor IcuCursor;
133123
133124 struct IcuTokenizer {
133125   sqlcipher3_tokenizer base;
133126   char *zLocale;
133127 };
133128
133129 struct IcuCursor {
133130   sqlcipher3_tokenizer_cursor base;
133131
133132   UBreakIterator *pIter;      /* ICU break-iterator object */
133133   int nChar;                  /* Number of UChar elements in pInput */
133134   UChar *aChar;               /* Copy of input using utf-16 encoding */
133135   int *aOffset;               /* Offsets of each character in utf-8 input */
133136
133137   int nBuffer;
133138   char *zBuffer;
133139
133140   int iToken;
133141 };
133142
133143 /*
133144 ** Create a new tokenizer instance.
133145 */
133146 static int icuCreate(
133147   int argc,                            /* Number of entries in argv[] */
133148   const char * const *argv,            /* Tokenizer creation arguments */
133149   sqlcipher3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
133150 ){
133151   IcuTokenizer *p;
133152   int n = 0;
133153
133154   if( argc>0 ){
133155     n = strlen(argv[0])+1;
133156   }
133157   p = (IcuTokenizer *)sqlcipher3_malloc(sizeof(IcuTokenizer)+n);
133158   if( !p ){
133159     return SQLCIPHER_NOMEM;
133160   }
133161   memset(p, 0, sizeof(IcuTokenizer));
133162
133163   if( n ){
133164     p->zLocale = (char *)&p[1];
133165     memcpy(p->zLocale, argv[0], n);
133166   }
133167
133168   *ppTokenizer = (sqlcipher3_tokenizer *)p;
133169
133170   return SQLCIPHER_OK;
133171 }
133172
133173 /*
133174 ** Destroy a tokenizer
133175 */
133176 static int icuDestroy(sqlcipher3_tokenizer *pTokenizer){
133177   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
133178   sqlcipher3_free(p);
133179   return SQLCIPHER_OK;
133180 }
133181
133182 /*
133183 ** Prepare to begin tokenizing a particular string.  The input
133184 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
133185 ** used to incrementally tokenize this string is returned in 
133186 ** *ppCursor.
133187 */
133188 static int icuOpen(
133189   sqlcipher3_tokenizer *pTokenizer,         /* The tokenizer */
133190   const char *zInput,                    /* Input string */
133191   int nInput,                            /* Length of zInput in bytes */
133192   sqlcipher3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
133193 ){
133194   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
133195   IcuCursor *pCsr;
133196
133197   const int32_t opt = U_FOLD_CASE_DEFAULT;
133198   UErrorCode status = U_ZERO_ERROR;
133199   int nChar;
133200
133201   UChar32 c;
133202   int iInput = 0;
133203   int iOut = 0;
133204
133205   *ppCursor = 0;
133206
133207   if( nInput<0 ){
133208     nInput = strlen(zInput);
133209   }
133210   nChar = nInput+1;
133211   pCsr = (IcuCursor *)sqlcipher3_malloc(
133212       sizeof(IcuCursor) +                /* IcuCursor */
133213       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
133214       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
133215   );
133216   if( !pCsr ){
133217     return SQLCIPHER_NOMEM;
133218   }
133219   memset(pCsr, 0, sizeof(IcuCursor));
133220   pCsr->aChar = (UChar *)&pCsr[1];
133221   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
133222
133223   pCsr->aOffset[iOut] = iInput;
133224   U8_NEXT(zInput, iInput, nInput, c); 
133225   while( c>0 ){
133226     int isError = 0;
133227     c = u_foldCase(c, opt);
133228     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
133229     if( isError ){
133230       sqlcipher3_free(pCsr);
133231       return SQLCIPHER_ERROR;
133232     }
133233     pCsr->aOffset[iOut] = iInput;
133234
133235     if( iInput<nInput ){
133236       U8_NEXT(zInput, iInput, nInput, c);
133237     }else{
133238       c = 0;
133239     }
133240   }
133241
133242   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
133243   if( !U_SUCCESS(status) ){
133244     sqlcipher3_free(pCsr);
133245     return SQLCIPHER_ERROR;
133246   }
133247   pCsr->nChar = iOut;
133248
133249   ubrk_first(pCsr->pIter);
133250   *ppCursor = (sqlcipher3_tokenizer_cursor *)pCsr;
133251   return SQLCIPHER_OK;
133252 }
133253
133254 /*
133255 ** Close a tokenization cursor previously opened by a call to icuOpen().
133256 */
133257 static int icuClose(sqlcipher3_tokenizer_cursor *pCursor){
133258   IcuCursor *pCsr = (IcuCursor *)pCursor;
133259   ubrk_close(pCsr->pIter);
133260   sqlcipher3_free(pCsr->zBuffer);
133261   sqlcipher3_free(pCsr);
133262   return SQLCIPHER_OK;
133263 }
133264
133265 /*
133266 ** Extract the next token from a tokenization cursor.
133267 */
133268 static int icuNext(
133269   sqlcipher3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
133270   const char **ppToken,               /* OUT: *ppToken is the token text */
133271   int *pnBytes,                       /* OUT: Number of bytes in token */
133272   int *piStartOffset,                 /* OUT: Starting offset of token */
133273   int *piEndOffset,                   /* OUT: Ending offset of token */
133274   int *piPosition                     /* OUT: Position integer of token */
133275 ){
133276   IcuCursor *pCsr = (IcuCursor *)pCursor;
133277
133278   int iStart = 0;
133279   int iEnd = 0;
133280   int nByte = 0;
133281
133282   while( iStart==iEnd ){
133283     UChar32 c;
133284
133285     iStart = ubrk_current(pCsr->pIter);
133286     iEnd = ubrk_next(pCsr->pIter);
133287     if( iEnd==UBRK_DONE ){
133288       return SQLCIPHER_DONE;
133289     }
133290
133291     while( iStart<iEnd ){
133292       int iWhite = iStart;
133293       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
133294       if( u_isspace(c) ){
133295         iStart = iWhite;
133296       }else{
133297         break;
133298       }
133299     }
133300     assert(iStart<=iEnd);
133301   }
133302
133303   do {
133304     UErrorCode status = U_ZERO_ERROR;
133305     if( nByte ){
133306       char *zNew = sqlcipher3_realloc(pCsr->zBuffer, nByte);
133307       if( !zNew ){
133308         return SQLCIPHER_NOMEM;
133309       }
133310       pCsr->zBuffer = zNew;
133311       pCsr->nBuffer = nByte;
133312     }
133313
133314     u_strToUTF8(
133315         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
133316         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
133317         &status                                  /* Output success/failure */
133318     );
133319   } while( nByte>pCsr->nBuffer );
133320
133321   *ppToken = pCsr->zBuffer;
133322   *pnBytes = nByte;
133323   *piStartOffset = pCsr->aOffset[iStart];
133324   *piEndOffset = pCsr->aOffset[iEnd];
133325   *piPosition = pCsr->iToken++;
133326
133327   return SQLCIPHER_OK;
133328 }
133329
133330 /*
133331 ** The set of routines that implement the simple tokenizer
133332 */
133333 static const sqlcipher3_tokenizer_module icuTokenizerModule = {
133334   0,                           /* iVersion */
133335   icuCreate,                   /* xCreate  */
133336   icuDestroy,                  /* xCreate  */
133337   icuOpen,                     /* xOpen    */
133338   icuClose,                    /* xClose   */
133339   icuNext,                     /* xNext    */
133340 };
133341
133342 /*
133343 ** Set *ppModule to point at the implementation of the ICU tokenizer.
133344 */
133345 SQLCIPHER_PRIVATE void sqlcipher3Fts3IcuTokenizerModule(
133346   sqlcipher3_tokenizer_module const**ppModule
133347 ){
133348   *ppModule = &icuTokenizerModule;
133349 }
133350
133351 #endif /* defined(SQLCIPHER_ENABLE_ICU) */
133352 #endif /* !defined(SQLCIPHER_CORE) || defined(SQLCIPHER_ENABLE_FTS3) */
133353
133354 #pragma GCC diagnostic pop
133355 /************** End of fts3_icu.c ********************************************/